aframe-master.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297
  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 e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({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 placeHoldersCount (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. // the number of equal signs (place holders)
  40. // if there are two placeholders, than the two characters before it
  41. // represent one byte
  42. // if there is only one, then the three characters before it represent 2 bytes
  43. // this is just a cheap hack to not do indexOf twice
  44. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  45. }
  46. function byteLength (b64) {
  47. // base64 is 4/3 + up to two characters of the original data
  48. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  49. }
  50. function toByteArray (b64) {
  51. var i, l, tmp, placeHolders, arr
  52. var len = b64.length
  53. placeHolders = placeHoldersCount(b64)
  54. arr = new Arr((len * 3 / 4) - placeHolders)
  55. // if there are placeholders, only get up to the last complete 4 chars
  56. l = placeHolders > 0 ? len - 4 : len
  57. var L = 0
  58. for (i = 0; i < l; i += 4) {
  59. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  60. arr[L++] = (tmp >> 16) & 0xFF
  61. arr[L++] = (tmp >> 8) & 0xFF
  62. arr[L++] = tmp & 0xFF
  63. }
  64. if (placeHolders === 2) {
  65. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  66. arr[L++] = tmp & 0xFF
  67. } else if (placeHolders === 1) {
  68. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  69. arr[L++] = (tmp >> 8) & 0xFF
  70. arr[L++] = tmp & 0xFF
  71. }
  72. return arr
  73. }
  74. function tripletToBase64 (num) {
  75. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  76. }
  77. function encodeChunk (uint8, start, end) {
  78. var tmp
  79. var output = []
  80. for (var i = start; i < end; i += 3) {
  81. tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
  82. output.push(tripletToBase64(tmp))
  83. }
  84. return output.join('')
  85. }
  86. function fromByteArray (uint8) {
  87. var tmp
  88. var len = uint8.length
  89. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  90. var output = ''
  91. var parts = []
  92. var maxChunkLength = 16383 // must be multiple of 3
  93. // go through the array every three bytes, we'll deal with trailing stuff later
  94. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  95. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  96. }
  97. // pad the end with zeros, but make sure to not forget the extra bytes
  98. if (extraBytes === 1) {
  99. tmp = uint8[len - 1]
  100. output += lookup[tmp >> 2]
  101. output += lookup[(tmp << 4) & 0x3F]
  102. output += '=='
  103. } else if (extraBytes === 2) {
  104. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  105. output += lookup[tmp >> 10]
  106. output += lookup[(tmp >> 4) & 0x3F]
  107. output += lookup[(tmp << 2) & 0x3F]
  108. output += '='
  109. }
  110. parts.push(output)
  111. return parts.join('')
  112. }
  113. },{}],4:[function(_dereq_,module,exports){
  114. 'use strict';
  115. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  116. module.exports = {
  117. // Create a <link> tag with optional data attributes
  118. createLink: function(href, attributes) {
  119. var head = document.head || document.getElementsByTagName('head')[0];
  120. var link = document.createElement('link');
  121. link.href = href;
  122. link.rel = 'stylesheet';
  123. for (var key in attributes) {
  124. if ( ! attributes.hasOwnProperty(key)) {
  125. continue;
  126. }
  127. var value = attributes[key];
  128. link.setAttribute('data-' + key, value);
  129. }
  130. head.appendChild(link);
  131. },
  132. // Create a <style> tag with optional data attributes
  133. createStyle: function(cssText, attributes) {
  134. var head = document.head || document.getElementsByTagName('head')[0],
  135. style = document.createElement('style');
  136. style.type = 'text/css';
  137. for (var key in attributes) {
  138. if ( ! attributes.hasOwnProperty(key)) {
  139. continue;
  140. }
  141. var value = attributes[key];
  142. style.setAttribute('data-' + key, value);
  143. }
  144. if (style.sheet) { // for jsdom and IE9+
  145. style.innerHTML = cssText;
  146. style.sheet.cssText = cssText;
  147. head.appendChild(style);
  148. } else if (style.styleSheet) { // for IE8 and below
  149. head.appendChild(style);
  150. style.styleSheet.cssText = cssText;
  151. } else { // for Chrome, Firefox, and Safari
  152. style.appendChild(document.createTextNode(cssText));
  153. head.appendChild(style);
  154. }
  155. }
  156. };
  157. },{}],5:[function(_dereq_,module,exports){
  158. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  159. module.exports = function (a, b) {
  160. if (!Buffer.isBuffer(a)) return undefined;
  161. if (!Buffer.isBuffer(b)) return undefined;
  162. if (typeof a.equals === 'function') return a.equals(b);
  163. if (a.length !== b.length) return false;
  164. for (var i = 0; i < a.length; i++) {
  165. if (a[i] !== b[i]) return false;
  166. }
  167. return true;
  168. };
  169. },{"buffer":6}],6:[function(_dereq_,module,exports){
  170. (function (global){
  171. /*!
  172. * The buffer module from node.js, for the browser.
  173. *
  174. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  175. * @license MIT
  176. */
  177. /* eslint-disable no-proto */
  178. 'use strict'
  179. var base64 = _dereq_('base64-js')
  180. var ieee754 = _dereq_('ieee754')
  181. var isArray = _dereq_('isarray')
  182. exports.Buffer = Buffer
  183. exports.SlowBuffer = SlowBuffer
  184. exports.INSPECT_MAX_BYTES = 50
  185. /**
  186. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  187. * === true Use Uint8Array implementation (fastest)
  188. * === false Use Object implementation (most compatible, even IE6)
  189. *
  190. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  191. * Opera 11.6+, iOS 4.2+.
  192. *
  193. * Due to various browser bugs, sometimes the Object implementation will be used even
  194. * when the browser supports typed arrays.
  195. *
  196. * Note:
  197. *
  198. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  199. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  200. *
  201. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  202. *
  203. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  204. * incorrect length in some situations.
  205. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  206. * get the Object implementation, which is slower but behaves correctly.
  207. */
  208. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  209. ? global.TYPED_ARRAY_SUPPORT
  210. : typedArraySupport()
  211. /*
  212. * Export kMaxLength after typed array support is determined.
  213. */
  214. exports.kMaxLength = kMaxLength()
  215. function typedArraySupport () {
  216. try {
  217. var arr = new Uint8Array(1)
  218. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  219. return arr.foo() === 42 && // typed array instances can be augmented
  220. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  221. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  222. } catch (e) {
  223. return false
  224. }
  225. }
  226. function kMaxLength () {
  227. return Buffer.TYPED_ARRAY_SUPPORT
  228. ? 0x7fffffff
  229. : 0x3fffffff
  230. }
  231. function createBuffer (that, length) {
  232. if (kMaxLength() < length) {
  233. throw new RangeError('Invalid typed array length')
  234. }
  235. if (Buffer.TYPED_ARRAY_SUPPORT) {
  236. // Return an augmented `Uint8Array` instance, for best performance
  237. that = new Uint8Array(length)
  238. that.__proto__ = Buffer.prototype
  239. } else {
  240. // Fallback: Return an object instance of the Buffer class
  241. if (that === null) {
  242. that = new Buffer(length)
  243. }
  244. that.length = length
  245. }
  246. return that
  247. }
  248. /**
  249. * The Buffer constructor returns instances of `Uint8Array` that have their
  250. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  251. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  252. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  253. * returns a single octet.
  254. *
  255. * The `Uint8Array` prototype remains unmodified.
  256. */
  257. function Buffer (arg, encodingOrOffset, length) {
  258. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  259. return new Buffer(arg, encodingOrOffset, length)
  260. }
  261. // Common case.
  262. if (typeof arg === 'number') {
  263. if (typeof encodingOrOffset === 'string') {
  264. throw new Error(
  265. 'If encoding is specified then the first argument must be a string'
  266. )
  267. }
  268. return allocUnsafe(this, arg)
  269. }
  270. return from(this, arg, encodingOrOffset, length)
  271. }
  272. Buffer.poolSize = 8192 // not used by this implementation
  273. // TODO: Legacy, not needed anymore. Remove in next major version.
  274. Buffer._augment = function (arr) {
  275. arr.__proto__ = Buffer.prototype
  276. return arr
  277. }
  278. function from (that, value, encodingOrOffset, length) {
  279. if (typeof value === 'number') {
  280. throw new TypeError('"value" argument must not be a number')
  281. }
  282. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  283. return fromArrayBuffer(that, value, encodingOrOffset, length)
  284. }
  285. if (typeof value === 'string') {
  286. return fromString(that, value, encodingOrOffset)
  287. }
  288. return fromObject(that, value)
  289. }
  290. /**
  291. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  292. * if value is a number.
  293. * Buffer.from(str[, encoding])
  294. * Buffer.from(array)
  295. * Buffer.from(buffer)
  296. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  297. **/
  298. Buffer.from = function (value, encodingOrOffset, length) {
  299. return from(null, value, encodingOrOffset, length)
  300. }
  301. if (Buffer.TYPED_ARRAY_SUPPORT) {
  302. Buffer.prototype.__proto__ = Uint8Array.prototype
  303. Buffer.__proto__ = Uint8Array
  304. if (typeof Symbol !== 'undefined' && Symbol.species &&
  305. Buffer[Symbol.species] === Buffer) {
  306. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  307. Object.defineProperty(Buffer, Symbol.species, {
  308. value: null,
  309. configurable: true
  310. })
  311. }
  312. }
  313. function assertSize (size) {
  314. if (typeof size !== 'number') {
  315. throw new TypeError('"size" argument must be a number')
  316. } else if (size < 0) {
  317. throw new RangeError('"size" argument must not be negative')
  318. }
  319. }
  320. function alloc (that, size, fill, encoding) {
  321. assertSize(size)
  322. if (size <= 0) {
  323. return createBuffer(that, size)
  324. }
  325. if (fill !== undefined) {
  326. // Only pay attention to encoding if it's a string. This
  327. // prevents accidentally sending in a number that would
  328. // be interpretted as a start offset.
  329. return typeof encoding === 'string'
  330. ? createBuffer(that, size).fill(fill, encoding)
  331. : createBuffer(that, size).fill(fill)
  332. }
  333. return createBuffer(that, size)
  334. }
  335. /**
  336. * Creates a new filled Buffer instance.
  337. * alloc(size[, fill[, encoding]])
  338. **/
  339. Buffer.alloc = function (size, fill, encoding) {
  340. return alloc(null, size, fill, encoding)
  341. }
  342. function allocUnsafe (that, size) {
  343. assertSize(size)
  344. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  345. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  346. for (var i = 0; i < size; ++i) {
  347. that[i] = 0
  348. }
  349. }
  350. return that
  351. }
  352. /**
  353. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  354. * */
  355. Buffer.allocUnsafe = function (size) {
  356. return allocUnsafe(null, size)
  357. }
  358. /**
  359. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  360. */
  361. Buffer.allocUnsafeSlow = function (size) {
  362. return allocUnsafe(null, size)
  363. }
  364. function fromString (that, string, encoding) {
  365. if (typeof encoding !== 'string' || encoding === '') {
  366. encoding = 'utf8'
  367. }
  368. if (!Buffer.isEncoding(encoding)) {
  369. throw new TypeError('"encoding" must be a valid string encoding')
  370. }
  371. var length = byteLength(string, encoding) | 0
  372. that = createBuffer(that, length)
  373. var actual = that.write(string, encoding)
  374. if (actual !== length) {
  375. // Writing a hex string, for example, that contains invalid characters will
  376. // cause everything after the first invalid character to be ignored. (e.g.
  377. // 'abxxcd' will be treated as 'ab')
  378. that = that.slice(0, actual)
  379. }
  380. return that
  381. }
  382. function fromArrayLike (that, array) {
  383. var length = array.length < 0 ? 0 : checked(array.length) | 0
  384. that = createBuffer(that, length)
  385. for (var i = 0; i < length; i += 1) {
  386. that[i] = array[i] & 255
  387. }
  388. return that
  389. }
  390. function fromArrayBuffer (that, array, byteOffset, length) {
  391. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  392. if (byteOffset < 0 || array.byteLength < byteOffset) {
  393. throw new RangeError('\'offset\' is out of bounds')
  394. }
  395. if (array.byteLength < byteOffset + (length || 0)) {
  396. throw new RangeError('\'length\' is out of bounds')
  397. }
  398. if (byteOffset === undefined && length === undefined) {
  399. array = new Uint8Array(array)
  400. } else if (length === undefined) {
  401. array = new Uint8Array(array, byteOffset)
  402. } else {
  403. array = new Uint8Array(array, byteOffset, length)
  404. }
  405. if (Buffer.TYPED_ARRAY_SUPPORT) {
  406. // Return an augmented `Uint8Array` instance, for best performance
  407. that = array
  408. that.__proto__ = Buffer.prototype
  409. } else {
  410. // Fallback: Return an object instance of the Buffer class
  411. that = fromArrayLike(that, array)
  412. }
  413. return that
  414. }
  415. function fromObject (that, obj) {
  416. if (Buffer.isBuffer(obj)) {
  417. var len = checked(obj.length) | 0
  418. that = createBuffer(that, len)
  419. if (that.length === 0) {
  420. return that
  421. }
  422. obj.copy(that, 0, 0, len)
  423. return that
  424. }
  425. if (obj) {
  426. if ((typeof ArrayBuffer !== 'undefined' &&
  427. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  428. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  429. return createBuffer(that, 0)
  430. }
  431. return fromArrayLike(that, obj)
  432. }
  433. if (obj.type === 'Buffer' && isArray(obj.data)) {
  434. return fromArrayLike(that, obj.data)
  435. }
  436. }
  437. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  438. }
  439. function checked (length) {
  440. // Note: cannot use `length < kMaxLength()` here because that fails when
  441. // length is NaN (which is otherwise coerced to zero.)
  442. if (length >= kMaxLength()) {
  443. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  444. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  445. }
  446. return length | 0
  447. }
  448. function SlowBuffer (length) {
  449. if (+length != length) { // eslint-disable-line eqeqeq
  450. length = 0
  451. }
  452. return Buffer.alloc(+length)
  453. }
  454. Buffer.isBuffer = function isBuffer (b) {
  455. return !!(b != null && b._isBuffer)
  456. }
  457. Buffer.compare = function compare (a, b) {
  458. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  459. throw new TypeError('Arguments must be Buffers')
  460. }
  461. if (a === b) return 0
  462. var x = a.length
  463. var y = b.length
  464. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  465. if (a[i] !== b[i]) {
  466. x = a[i]
  467. y = b[i]
  468. break
  469. }
  470. }
  471. if (x < y) return -1
  472. if (y < x) return 1
  473. return 0
  474. }
  475. Buffer.isEncoding = function isEncoding (encoding) {
  476. switch (String(encoding).toLowerCase()) {
  477. case 'hex':
  478. case 'utf8':
  479. case 'utf-8':
  480. case 'ascii':
  481. case 'latin1':
  482. case 'binary':
  483. case 'base64':
  484. case 'ucs2':
  485. case 'ucs-2':
  486. case 'utf16le':
  487. case 'utf-16le':
  488. return true
  489. default:
  490. return false
  491. }
  492. }
  493. Buffer.concat = function concat (list, length) {
  494. if (!isArray(list)) {
  495. throw new TypeError('"list" argument must be an Array of Buffers')
  496. }
  497. if (list.length === 0) {
  498. return Buffer.alloc(0)
  499. }
  500. var i
  501. if (length === undefined) {
  502. length = 0
  503. for (i = 0; i < list.length; ++i) {
  504. length += list[i].length
  505. }
  506. }
  507. var buffer = Buffer.allocUnsafe(length)
  508. var pos = 0
  509. for (i = 0; i < list.length; ++i) {
  510. var buf = list[i]
  511. if (!Buffer.isBuffer(buf)) {
  512. throw new TypeError('"list" argument must be an Array of Buffers')
  513. }
  514. buf.copy(buffer, pos)
  515. pos += buf.length
  516. }
  517. return buffer
  518. }
  519. function byteLength (string, encoding) {
  520. if (Buffer.isBuffer(string)) {
  521. return string.length
  522. }
  523. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  524. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  525. return string.byteLength
  526. }
  527. if (typeof string !== 'string') {
  528. string = '' + string
  529. }
  530. var len = string.length
  531. if (len === 0) return 0
  532. // Use a for loop to avoid recursion
  533. var loweredCase = false
  534. for (;;) {
  535. switch (encoding) {
  536. case 'ascii':
  537. case 'latin1':
  538. case 'binary':
  539. return len
  540. case 'utf8':
  541. case 'utf-8':
  542. case undefined:
  543. return utf8ToBytes(string).length
  544. case 'ucs2':
  545. case 'ucs-2':
  546. case 'utf16le':
  547. case 'utf-16le':
  548. return len * 2
  549. case 'hex':
  550. return len >>> 1
  551. case 'base64':
  552. return base64ToBytes(string).length
  553. default:
  554. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  555. encoding = ('' + encoding).toLowerCase()
  556. loweredCase = true
  557. }
  558. }
  559. }
  560. Buffer.byteLength = byteLength
  561. function slowToString (encoding, start, end) {
  562. var loweredCase = false
  563. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  564. // property of a typed array.
  565. // This behaves neither like String nor Uint8Array in that we set start/end
  566. // to their upper/lower bounds if the value passed is out of range.
  567. // undefined is handled specially as per ECMA-262 6th Edition,
  568. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  569. if (start === undefined || start < 0) {
  570. start = 0
  571. }
  572. // Return early if start > this.length. Done here to prevent potential uint32
  573. // coercion fail below.
  574. if (start > this.length) {
  575. return ''
  576. }
  577. if (end === undefined || end > this.length) {
  578. end = this.length
  579. }
  580. if (end <= 0) {
  581. return ''
  582. }
  583. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  584. end >>>= 0
  585. start >>>= 0
  586. if (end <= start) {
  587. return ''
  588. }
  589. if (!encoding) encoding = 'utf8'
  590. while (true) {
  591. switch (encoding) {
  592. case 'hex':
  593. return hexSlice(this, start, end)
  594. case 'utf8':
  595. case 'utf-8':
  596. return utf8Slice(this, start, end)
  597. case 'ascii':
  598. return asciiSlice(this, start, end)
  599. case 'latin1':
  600. case 'binary':
  601. return latin1Slice(this, start, end)
  602. case 'base64':
  603. return base64Slice(this, start, end)
  604. case 'ucs2':
  605. case 'ucs-2':
  606. case 'utf16le':
  607. case 'utf-16le':
  608. return utf16leSlice(this, start, end)
  609. default:
  610. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  611. encoding = (encoding + '').toLowerCase()
  612. loweredCase = true
  613. }
  614. }
  615. }
  616. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  617. // Buffer instances.
  618. Buffer.prototype._isBuffer = true
  619. function swap (b, n, m) {
  620. var i = b[n]
  621. b[n] = b[m]
  622. b[m] = i
  623. }
  624. Buffer.prototype.swap16 = function swap16 () {
  625. var len = this.length
  626. if (len % 2 !== 0) {
  627. throw new RangeError('Buffer size must be a multiple of 16-bits')
  628. }
  629. for (var i = 0; i < len; i += 2) {
  630. swap(this, i, i + 1)
  631. }
  632. return this
  633. }
  634. Buffer.prototype.swap32 = function swap32 () {
  635. var len = this.length
  636. if (len % 4 !== 0) {
  637. throw new RangeError('Buffer size must be a multiple of 32-bits')
  638. }
  639. for (var i = 0; i < len; i += 4) {
  640. swap(this, i, i + 3)
  641. swap(this, i + 1, i + 2)
  642. }
  643. return this
  644. }
  645. Buffer.prototype.swap64 = function swap64 () {
  646. var len = this.length
  647. if (len % 8 !== 0) {
  648. throw new RangeError('Buffer size must be a multiple of 64-bits')
  649. }
  650. for (var i = 0; i < len; i += 8) {
  651. swap(this, i, i + 7)
  652. swap(this, i + 1, i + 6)
  653. swap(this, i + 2, i + 5)
  654. swap(this, i + 3, i + 4)
  655. }
  656. return this
  657. }
  658. Buffer.prototype.toString = function toString () {
  659. var length = this.length | 0
  660. if (length === 0) return ''
  661. if (arguments.length === 0) return utf8Slice(this, 0, length)
  662. return slowToString.apply(this, arguments)
  663. }
  664. Buffer.prototype.equals = function equals (b) {
  665. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  666. if (this === b) return true
  667. return Buffer.compare(this, b) === 0
  668. }
  669. Buffer.prototype.inspect = function inspect () {
  670. var str = ''
  671. var max = exports.INSPECT_MAX_BYTES
  672. if (this.length > 0) {
  673. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  674. if (this.length > max) str += ' ... '
  675. }
  676. return '<Buffer ' + str + '>'
  677. }
  678. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  679. if (!Buffer.isBuffer(target)) {
  680. throw new TypeError('Argument must be a Buffer')
  681. }
  682. if (start === undefined) {
  683. start = 0
  684. }
  685. if (end === undefined) {
  686. end = target ? target.length : 0
  687. }
  688. if (thisStart === undefined) {
  689. thisStart = 0
  690. }
  691. if (thisEnd === undefined) {
  692. thisEnd = this.length
  693. }
  694. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  695. throw new RangeError('out of range index')
  696. }
  697. if (thisStart >= thisEnd && start >= end) {
  698. return 0
  699. }
  700. if (thisStart >= thisEnd) {
  701. return -1
  702. }
  703. if (start >= end) {
  704. return 1
  705. }
  706. start >>>= 0
  707. end >>>= 0
  708. thisStart >>>= 0
  709. thisEnd >>>= 0
  710. if (this === target) return 0
  711. var x = thisEnd - thisStart
  712. var y = end - start
  713. var len = Math.min(x, y)
  714. var thisCopy = this.slice(thisStart, thisEnd)
  715. var targetCopy = target.slice(start, end)
  716. for (var i = 0; i < len; ++i) {
  717. if (thisCopy[i] !== targetCopy[i]) {
  718. x = thisCopy[i]
  719. y = targetCopy[i]
  720. break
  721. }
  722. }
  723. if (x < y) return -1
  724. if (y < x) return 1
  725. return 0
  726. }
  727. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  728. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  729. //
  730. // Arguments:
  731. // - buffer - a Buffer to search
  732. // - val - a string, Buffer, or number
  733. // - byteOffset - an index into `buffer`; will be clamped to an int32
  734. // - encoding - an optional encoding, relevant is val is a string
  735. // - dir - true for indexOf, false for lastIndexOf
  736. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  737. // Empty buffer means no match
  738. if (buffer.length === 0) return -1
  739. // Normalize byteOffset
  740. if (typeof byteOffset === 'string') {
  741. encoding = byteOffset
  742. byteOffset = 0
  743. } else if (byteOffset > 0x7fffffff) {
  744. byteOffset = 0x7fffffff
  745. } else if (byteOffset < -0x80000000) {
  746. byteOffset = -0x80000000
  747. }
  748. byteOffset = +byteOffset // Coerce to Number.
  749. if (isNaN(byteOffset)) {
  750. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  751. byteOffset = dir ? 0 : (buffer.length - 1)
  752. }
  753. // Normalize byteOffset: negative offsets start from the end of the buffer
  754. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  755. if (byteOffset >= buffer.length) {
  756. if (dir) return -1
  757. else byteOffset = buffer.length - 1
  758. } else if (byteOffset < 0) {
  759. if (dir) byteOffset = 0
  760. else return -1
  761. }
  762. // Normalize val
  763. if (typeof val === 'string') {
  764. val = Buffer.from(val, encoding)
  765. }
  766. // Finally, search either indexOf (if dir is true) or lastIndexOf
  767. if (Buffer.isBuffer(val)) {
  768. // Special case: looking for empty string/buffer always fails
  769. if (val.length === 0) {
  770. return -1
  771. }
  772. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  773. } else if (typeof val === 'number') {
  774. val = val & 0xFF // Search for a byte value [0-255]
  775. if (Buffer.TYPED_ARRAY_SUPPORT &&
  776. typeof Uint8Array.prototype.indexOf === 'function') {
  777. if (dir) {
  778. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  779. } else {
  780. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  781. }
  782. }
  783. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  784. }
  785. throw new TypeError('val must be string, number or Buffer')
  786. }
  787. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  788. var indexSize = 1
  789. var arrLength = arr.length
  790. var valLength = val.length
  791. if (encoding !== undefined) {
  792. encoding = String(encoding).toLowerCase()
  793. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  794. encoding === 'utf16le' || encoding === 'utf-16le') {
  795. if (arr.length < 2 || val.length < 2) {
  796. return -1
  797. }
  798. indexSize = 2
  799. arrLength /= 2
  800. valLength /= 2
  801. byteOffset /= 2
  802. }
  803. }
  804. function read (buf, i) {
  805. if (indexSize === 1) {
  806. return buf[i]
  807. } else {
  808. return buf.readUInt16BE(i * indexSize)
  809. }
  810. }
  811. var i
  812. if (dir) {
  813. var foundIndex = -1
  814. for (i = byteOffset; i < arrLength; i++) {
  815. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  816. if (foundIndex === -1) foundIndex = i
  817. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  818. } else {
  819. if (foundIndex !== -1) i -= i - foundIndex
  820. foundIndex = -1
  821. }
  822. }
  823. } else {
  824. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  825. for (i = byteOffset; i >= 0; i--) {
  826. var found = true
  827. for (var j = 0; j < valLength; j++) {
  828. if (read(arr, i + j) !== read(val, j)) {
  829. found = false
  830. break
  831. }
  832. }
  833. if (found) return i
  834. }
  835. }
  836. return -1
  837. }
  838. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  839. return this.indexOf(val, byteOffset, encoding) !== -1
  840. }
  841. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  842. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  843. }
  844. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  845. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  846. }
  847. function hexWrite (buf, string, offset, length) {
  848. offset = Number(offset) || 0
  849. var remaining = buf.length - offset
  850. if (!length) {
  851. length = remaining
  852. } else {
  853. length = Number(length)
  854. if (length > remaining) {
  855. length = remaining
  856. }
  857. }
  858. // must be an even number of digits
  859. var strLen = string.length
  860. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  861. if (length > strLen / 2) {
  862. length = strLen / 2
  863. }
  864. for (var i = 0; i < length; ++i) {
  865. var parsed = parseInt(string.substr(i * 2, 2), 16)
  866. if (isNaN(parsed)) return i
  867. buf[offset + i] = parsed
  868. }
  869. return i
  870. }
  871. function utf8Write (buf, string, offset, length) {
  872. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  873. }
  874. function asciiWrite (buf, string, offset, length) {
  875. return blitBuffer(asciiToBytes(string), buf, offset, length)
  876. }
  877. function latin1Write (buf, string, offset, length) {
  878. return asciiWrite(buf, string, offset, length)
  879. }
  880. function base64Write (buf, string, offset, length) {
  881. return blitBuffer(base64ToBytes(string), buf, offset, length)
  882. }
  883. function ucs2Write (buf, string, offset, length) {
  884. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  885. }
  886. Buffer.prototype.write = function write (string, offset, length, encoding) {
  887. // Buffer#write(string)
  888. if (offset === undefined) {
  889. encoding = 'utf8'
  890. length = this.length
  891. offset = 0
  892. // Buffer#write(string, encoding)
  893. } else if (length === undefined && typeof offset === 'string') {
  894. encoding = offset
  895. length = this.length
  896. offset = 0
  897. // Buffer#write(string, offset[, length][, encoding])
  898. } else if (isFinite(offset)) {
  899. offset = offset | 0
  900. if (isFinite(length)) {
  901. length = length | 0
  902. if (encoding === undefined) encoding = 'utf8'
  903. } else {
  904. encoding = length
  905. length = undefined
  906. }
  907. // legacy write(string, encoding, offset, length) - remove in v0.13
  908. } else {
  909. throw new Error(
  910. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  911. )
  912. }
  913. var remaining = this.length - offset
  914. if (length === undefined || length > remaining) length = remaining
  915. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  916. throw new RangeError('Attempt to write outside buffer bounds')
  917. }
  918. if (!encoding) encoding = 'utf8'
  919. var loweredCase = false
  920. for (;;) {
  921. switch (encoding) {
  922. case 'hex':
  923. return hexWrite(this, string, offset, length)
  924. case 'utf8':
  925. case 'utf-8':
  926. return utf8Write(this, string, offset, length)
  927. case 'ascii':
  928. return asciiWrite(this, string, offset, length)
  929. case 'latin1':
  930. case 'binary':
  931. return latin1Write(this, string, offset, length)
  932. case 'base64':
  933. // Warning: maxLength not taken into account in base64Write
  934. return base64Write(this, string, offset, length)
  935. case 'ucs2':
  936. case 'ucs-2':
  937. case 'utf16le':
  938. case 'utf-16le':
  939. return ucs2Write(this, string, offset, length)
  940. default:
  941. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  942. encoding = ('' + encoding).toLowerCase()
  943. loweredCase = true
  944. }
  945. }
  946. }
  947. Buffer.prototype.toJSON = function toJSON () {
  948. return {
  949. type: 'Buffer',
  950. data: Array.prototype.slice.call(this._arr || this, 0)
  951. }
  952. }
  953. function base64Slice (buf, start, end) {
  954. if (start === 0 && end === buf.length) {
  955. return base64.fromByteArray(buf)
  956. } else {
  957. return base64.fromByteArray(buf.slice(start, end))
  958. }
  959. }
  960. function utf8Slice (buf, start, end) {
  961. end = Math.min(buf.length, end)
  962. var res = []
  963. var i = start
  964. while (i < end) {
  965. var firstByte = buf[i]
  966. var codePoint = null
  967. var bytesPerSequence = (firstByte > 0xEF) ? 4
  968. : (firstByte > 0xDF) ? 3
  969. : (firstByte > 0xBF) ? 2
  970. : 1
  971. if (i + bytesPerSequence <= end) {
  972. var secondByte, thirdByte, fourthByte, tempCodePoint
  973. switch (bytesPerSequence) {
  974. case 1:
  975. if (firstByte < 0x80) {
  976. codePoint = firstByte
  977. }
  978. break
  979. case 2:
  980. secondByte = buf[i + 1]
  981. if ((secondByte & 0xC0) === 0x80) {
  982. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  983. if (tempCodePoint > 0x7F) {
  984. codePoint = tempCodePoint
  985. }
  986. }
  987. break
  988. case 3:
  989. secondByte = buf[i + 1]
  990. thirdByte = buf[i + 2]
  991. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  992. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  993. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  994. codePoint = tempCodePoint
  995. }
  996. }
  997. break
  998. case 4:
  999. secondByte = buf[i + 1]
  1000. thirdByte = buf[i + 2]
  1001. fourthByte = buf[i + 3]
  1002. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1003. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1004. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1005. codePoint = tempCodePoint
  1006. }
  1007. }
  1008. }
  1009. }
  1010. if (codePoint === null) {
  1011. // we did not generate a valid codePoint so insert a
  1012. // replacement char (U+FFFD) and advance only 1 byte
  1013. codePoint = 0xFFFD
  1014. bytesPerSequence = 1
  1015. } else if (codePoint > 0xFFFF) {
  1016. // encode to utf16 (surrogate pair dance)
  1017. codePoint -= 0x10000
  1018. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1019. codePoint = 0xDC00 | codePoint & 0x3FF
  1020. }
  1021. res.push(codePoint)
  1022. i += bytesPerSequence
  1023. }
  1024. return decodeCodePointsArray(res)
  1025. }
  1026. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1027. // the lowest limit is Chrome, with 0x10000 args.
  1028. // We go 1 magnitude less, for safety
  1029. var MAX_ARGUMENTS_LENGTH = 0x1000
  1030. function decodeCodePointsArray (codePoints) {
  1031. var len = codePoints.length
  1032. if (len <= MAX_ARGUMENTS_LENGTH) {
  1033. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1034. }
  1035. // Decode in chunks to avoid "call stack size exceeded".
  1036. var res = ''
  1037. var i = 0
  1038. while (i < len) {
  1039. res += String.fromCharCode.apply(
  1040. String,
  1041. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1042. )
  1043. }
  1044. return res
  1045. }
  1046. function asciiSlice (buf, start, end) {
  1047. var ret = ''
  1048. end = Math.min(buf.length, end)
  1049. for (var i = start; i < end; ++i) {
  1050. ret += String.fromCharCode(buf[i] & 0x7F)
  1051. }
  1052. return ret
  1053. }
  1054. function latin1Slice (buf, start, end) {
  1055. var ret = ''
  1056. end = Math.min(buf.length, end)
  1057. for (var i = start; i < end; ++i) {
  1058. ret += String.fromCharCode(buf[i])
  1059. }
  1060. return ret
  1061. }
  1062. function hexSlice (buf, start, end) {
  1063. var len = buf.length
  1064. if (!start || start < 0) start = 0
  1065. if (!end || end < 0 || end > len) end = len
  1066. var out = ''
  1067. for (var i = start; i < end; ++i) {
  1068. out += toHex(buf[i])
  1069. }
  1070. return out
  1071. }
  1072. function utf16leSlice (buf, start, end) {
  1073. var bytes = buf.slice(start, end)
  1074. var res = ''
  1075. for (var i = 0; i < bytes.length; i += 2) {
  1076. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1077. }
  1078. return res
  1079. }
  1080. Buffer.prototype.slice = function slice (start, end) {
  1081. var len = this.length
  1082. start = ~~start
  1083. end = end === undefined ? len : ~~end
  1084. if (start < 0) {
  1085. start += len
  1086. if (start < 0) start = 0
  1087. } else if (start > len) {
  1088. start = len
  1089. }
  1090. if (end < 0) {
  1091. end += len
  1092. if (end < 0) end = 0
  1093. } else if (end > len) {
  1094. end = len
  1095. }
  1096. if (end < start) end = start
  1097. var newBuf
  1098. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1099. newBuf = this.subarray(start, end)
  1100. newBuf.__proto__ = Buffer.prototype
  1101. } else {
  1102. var sliceLen = end - start
  1103. newBuf = new Buffer(sliceLen, undefined)
  1104. for (var i = 0; i < sliceLen; ++i) {
  1105. newBuf[i] = this[i + start]
  1106. }
  1107. }
  1108. return newBuf
  1109. }
  1110. /*
  1111. * Need to make sure that buffer isn't trying to write out of bounds.
  1112. */
  1113. function checkOffset (offset, ext, length) {
  1114. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1115. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1116. }
  1117. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1118. offset = offset | 0
  1119. byteLength = byteLength | 0
  1120. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1121. var val = this[offset]
  1122. var mul = 1
  1123. var i = 0
  1124. while (++i < byteLength && (mul *= 0x100)) {
  1125. val += this[offset + i] * mul
  1126. }
  1127. return val
  1128. }
  1129. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1130. offset = offset | 0
  1131. byteLength = byteLength | 0
  1132. if (!noAssert) {
  1133. checkOffset(offset, byteLength, this.length)
  1134. }
  1135. var val = this[offset + --byteLength]
  1136. var mul = 1
  1137. while (byteLength > 0 && (mul *= 0x100)) {
  1138. val += this[offset + --byteLength] * mul
  1139. }
  1140. return val
  1141. }
  1142. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1143. if (!noAssert) checkOffset(offset, 1, this.length)
  1144. return this[offset]
  1145. }
  1146. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1147. if (!noAssert) checkOffset(offset, 2, this.length)
  1148. return this[offset] | (this[offset + 1] << 8)
  1149. }
  1150. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1151. if (!noAssert) checkOffset(offset, 2, this.length)
  1152. return (this[offset] << 8) | this[offset + 1]
  1153. }
  1154. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1155. if (!noAssert) checkOffset(offset, 4, this.length)
  1156. return ((this[offset]) |
  1157. (this[offset + 1] << 8) |
  1158. (this[offset + 2] << 16)) +
  1159. (this[offset + 3] * 0x1000000)
  1160. }
  1161. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1162. if (!noAssert) checkOffset(offset, 4, this.length)
  1163. return (this[offset] * 0x1000000) +
  1164. ((this[offset + 1] << 16) |
  1165. (this[offset + 2] << 8) |
  1166. this[offset + 3])
  1167. }
  1168. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1169. offset = offset | 0
  1170. byteLength = byteLength | 0
  1171. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1172. var val = this[offset]
  1173. var mul = 1
  1174. var i = 0
  1175. while (++i < byteLength && (mul *= 0x100)) {
  1176. val += this[offset + i] * mul
  1177. }
  1178. mul *= 0x80
  1179. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1180. return val
  1181. }
  1182. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1183. offset = offset | 0
  1184. byteLength = byteLength | 0
  1185. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1186. var i = byteLength
  1187. var mul = 1
  1188. var val = this[offset + --i]
  1189. while (i > 0 && (mul *= 0x100)) {
  1190. val += this[offset + --i] * mul
  1191. }
  1192. mul *= 0x80
  1193. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1194. return val
  1195. }
  1196. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1197. if (!noAssert) checkOffset(offset, 1, this.length)
  1198. if (!(this[offset] & 0x80)) return (this[offset])
  1199. return ((0xff - this[offset] + 1) * -1)
  1200. }
  1201. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1202. if (!noAssert) checkOffset(offset, 2, this.length)
  1203. var val = this[offset] | (this[offset + 1] << 8)
  1204. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1205. }
  1206. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1207. if (!noAssert) checkOffset(offset, 2, this.length)
  1208. var val = this[offset + 1] | (this[offset] << 8)
  1209. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1210. }
  1211. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1212. if (!noAssert) checkOffset(offset, 4, this.length)
  1213. return (this[offset]) |
  1214. (this[offset + 1] << 8) |
  1215. (this[offset + 2] << 16) |
  1216. (this[offset + 3] << 24)
  1217. }
  1218. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1219. if (!noAssert) checkOffset(offset, 4, this.length)
  1220. return (this[offset] << 24) |
  1221. (this[offset + 1] << 16) |
  1222. (this[offset + 2] << 8) |
  1223. (this[offset + 3])
  1224. }
  1225. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1226. if (!noAssert) checkOffset(offset, 4, this.length)
  1227. return ieee754.read(this, offset, true, 23, 4)
  1228. }
  1229. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1230. if (!noAssert) checkOffset(offset, 4, this.length)
  1231. return ieee754.read(this, offset, false, 23, 4)
  1232. }
  1233. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1234. if (!noAssert) checkOffset(offset, 8, this.length)
  1235. return ieee754.read(this, offset, true, 52, 8)
  1236. }
  1237. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1238. if (!noAssert) checkOffset(offset, 8, this.length)
  1239. return ieee754.read(this, offset, false, 52, 8)
  1240. }
  1241. function checkInt (buf, value, offset, ext, max, min) {
  1242. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1243. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1244. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1245. }
  1246. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1247. value = +value
  1248. offset = offset | 0
  1249. byteLength = byteLength | 0
  1250. if (!noAssert) {
  1251. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1252. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1253. }
  1254. var mul = 1
  1255. var i = 0
  1256. this[offset] = value & 0xFF
  1257. while (++i < byteLength && (mul *= 0x100)) {
  1258. this[offset + i] = (value / mul) & 0xFF
  1259. }
  1260. return offset + byteLength
  1261. }
  1262. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1263. value = +value
  1264. offset = offset | 0
  1265. byteLength = byteLength | 0
  1266. if (!noAssert) {
  1267. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1268. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1269. }
  1270. var i = byteLength - 1
  1271. var mul = 1
  1272. this[offset + i] = value & 0xFF
  1273. while (--i >= 0 && (mul *= 0x100)) {
  1274. this[offset + i] = (value / mul) & 0xFF
  1275. }
  1276. return offset + byteLength
  1277. }
  1278. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1279. value = +value
  1280. offset = offset | 0
  1281. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1282. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1283. this[offset] = (value & 0xff)
  1284. return offset + 1
  1285. }
  1286. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1287. if (value < 0) value = 0xffff + value + 1
  1288. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1289. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1290. (littleEndian ? i : 1 - i) * 8
  1291. }
  1292. }
  1293. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1294. value = +value
  1295. offset = offset | 0
  1296. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1297. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1298. this[offset] = (value & 0xff)
  1299. this[offset + 1] = (value >>> 8)
  1300. } else {
  1301. objectWriteUInt16(this, value, offset, true)
  1302. }
  1303. return offset + 2
  1304. }
  1305. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1306. value = +value
  1307. offset = offset | 0
  1308. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1309. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1310. this[offset] = (value >>> 8)
  1311. this[offset + 1] = (value & 0xff)
  1312. } else {
  1313. objectWriteUInt16(this, value, offset, false)
  1314. }
  1315. return offset + 2
  1316. }
  1317. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1318. if (value < 0) value = 0xffffffff + value + 1
  1319. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1320. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1321. }
  1322. }
  1323. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1324. value = +value
  1325. offset = offset | 0
  1326. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1327. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1328. this[offset + 3] = (value >>> 24)
  1329. this[offset + 2] = (value >>> 16)
  1330. this[offset + 1] = (value >>> 8)
  1331. this[offset] = (value & 0xff)
  1332. } else {
  1333. objectWriteUInt32(this, value, offset, true)
  1334. }
  1335. return offset + 4
  1336. }
  1337. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1338. value = +value
  1339. offset = offset | 0
  1340. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1341. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1342. this[offset] = (value >>> 24)
  1343. this[offset + 1] = (value >>> 16)
  1344. this[offset + 2] = (value >>> 8)
  1345. this[offset + 3] = (value & 0xff)
  1346. } else {
  1347. objectWriteUInt32(this, value, offset, false)
  1348. }
  1349. return offset + 4
  1350. }
  1351. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1352. value = +value
  1353. offset = offset | 0
  1354. if (!noAssert) {
  1355. var limit = Math.pow(2, 8 * byteLength - 1)
  1356. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1357. }
  1358. var i = 0
  1359. var mul = 1
  1360. var sub = 0
  1361. this[offset] = value & 0xFF
  1362. while (++i < byteLength && (mul *= 0x100)) {
  1363. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1364. sub = 1
  1365. }
  1366. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1367. }
  1368. return offset + byteLength
  1369. }
  1370. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1371. value = +value
  1372. offset = offset | 0
  1373. if (!noAssert) {
  1374. var limit = Math.pow(2, 8 * byteLength - 1)
  1375. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1376. }
  1377. var i = byteLength - 1
  1378. var mul = 1
  1379. var sub = 0
  1380. this[offset + i] = value & 0xFF
  1381. while (--i >= 0 && (mul *= 0x100)) {
  1382. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1383. sub = 1
  1384. }
  1385. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1386. }
  1387. return offset + byteLength
  1388. }
  1389. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1390. value = +value
  1391. offset = offset | 0
  1392. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1393. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1394. if (value < 0) value = 0xff + value + 1
  1395. this[offset] = (value & 0xff)
  1396. return offset + 1
  1397. }
  1398. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1399. value = +value
  1400. offset = offset | 0
  1401. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1402. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1403. this[offset] = (value & 0xff)
  1404. this[offset + 1] = (value >>> 8)
  1405. } else {
  1406. objectWriteUInt16(this, value, offset, true)
  1407. }
  1408. return offset + 2
  1409. }
  1410. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1411. value = +value
  1412. offset = offset | 0
  1413. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1414. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1415. this[offset] = (value >>> 8)
  1416. this[offset + 1] = (value & 0xff)
  1417. } else {
  1418. objectWriteUInt16(this, value, offset, false)
  1419. }
  1420. return offset + 2
  1421. }
  1422. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1423. value = +value
  1424. offset = offset | 0
  1425. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1426. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1427. this[offset] = (value & 0xff)
  1428. this[offset + 1] = (value >>> 8)
  1429. this[offset + 2] = (value >>> 16)
  1430. this[offset + 3] = (value >>> 24)
  1431. } else {
  1432. objectWriteUInt32(this, value, offset, true)
  1433. }
  1434. return offset + 4
  1435. }
  1436. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1437. value = +value
  1438. offset = offset | 0
  1439. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1440. if (value < 0) value = 0xffffffff + value + 1
  1441. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1442. this[offset] = (value >>> 24)
  1443. this[offset + 1] = (value >>> 16)
  1444. this[offset + 2] = (value >>> 8)
  1445. this[offset + 3] = (value & 0xff)
  1446. } else {
  1447. objectWriteUInt32(this, value, offset, false)
  1448. }
  1449. return offset + 4
  1450. }
  1451. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1452. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1453. if (offset < 0) throw new RangeError('Index out of range')
  1454. }
  1455. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1456. if (!noAssert) {
  1457. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1458. }
  1459. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1460. return offset + 4
  1461. }
  1462. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1463. return writeFloat(this, value, offset, true, noAssert)
  1464. }
  1465. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1466. return writeFloat(this, value, offset, false, noAssert)
  1467. }
  1468. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1469. if (!noAssert) {
  1470. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1471. }
  1472. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1473. return offset + 8
  1474. }
  1475. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1476. return writeDouble(this, value, offset, true, noAssert)
  1477. }
  1478. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1479. return writeDouble(this, value, offset, false, noAssert)
  1480. }
  1481. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1482. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1483. if (!start) start = 0
  1484. if (!end && end !== 0) end = this.length
  1485. if (targetStart >= target.length) targetStart = target.length
  1486. if (!targetStart) targetStart = 0
  1487. if (end > 0 && end < start) end = start
  1488. // Copy 0 bytes; we're done
  1489. if (end === start) return 0
  1490. if (target.length === 0 || this.length === 0) return 0
  1491. // Fatal error conditions
  1492. if (targetStart < 0) {
  1493. throw new RangeError('targetStart out of bounds')
  1494. }
  1495. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1496. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1497. // Are we oob?
  1498. if (end > this.length) end = this.length
  1499. if (target.length - targetStart < end - start) {
  1500. end = target.length - targetStart + start
  1501. }
  1502. var len = end - start
  1503. var i
  1504. if (this === target && start < targetStart && targetStart < end) {
  1505. // descending copy from end
  1506. for (i = len - 1; i >= 0; --i) {
  1507. target[i + targetStart] = this[i + start]
  1508. }
  1509. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1510. // ascending copy from start
  1511. for (i = 0; i < len; ++i) {
  1512. target[i + targetStart] = this[i + start]
  1513. }
  1514. } else {
  1515. Uint8Array.prototype.set.call(
  1516. target,
  1517. this.subarray(start, start + len),
  1518. targetStart
  1519. )
  1520. }
  1521. return len
  1522. }
  1523. // Usage:
  1524. // buffer.fill(number[, offset[, end]])
  1525. // buffer.fill(buffer[, offset[, end]])
  1526. // buffer.fill(string[, offset[, end]][, encoding])
  1527. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1528. // Handle string cases:
  1529. if (typeof val === 'string') {
  1530. if (typeof start === 'string') {
  1531. encoding = start
  1532. start = 0
  1533. end = this.length
  1534. } else if (typeof end === 'string') {
  1535. encoding = end
  1536. end = this.length
  1537. }
  1538. if (val.length === 1) {
  1539. var code = val.charCodeAt(0)
  1540. if (code < 256) {
  1541. val = code
  1542. }
  1543. }
  1544. if (encoding !== undefined && typeof encoding !== 'string') {
  1545. throw new TypeError('encoding must be a string')
  1546. }
  1547. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1548. throw new TypeError('Unknown encoding: ' + encoding)
  1549. }
  1550. } else if (typeof val === 'number') {
  1551. val = val & 255
  1552. }
  1553. // Invalid ranges are not set to a default, so can range check early.
  1554. if (start < 0 || this.length < start || this.length < end) {
  1555. throw new RangeError('Out of range index')
  1556. }
  1557. if (end <= start) {
  1558. return this
  1559. }
  1560. start = start >>> 0
  1561. end = end === undefined ? this.length : end >>> 0
  1562. if (!val) val = 0
  1563. var i
  1564. if (typeof val === 'number') {
  1565. for (i = start; i < end; ++i) {
  1566. this[i] = val
  1567. }
  1568. } else {
  1569. var bytes = Buffer.isBuffer(val)
  1570. ? val
  1571. : utf8ToBytes(new Buffer(val, encoding).toString())
  1572. var len = bytes.length
  1573. for (i = 0; i < end - start; ++i) {
  1574. this[i + start] = bytes[i % len]
  1575. }
  1576. }
  1577. return this
  1578. }
  1579. // HELPER FUNCTIONS
  1580. // ================
  1581. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1582. function base64clean (str) {
  1583. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1584. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1585. // Node converts strings with length < 2 to ''
  1586. if (str.length < 2) return ''
  1587. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1588. while (str.length % 4 !== 0) {
  1589. str = str + '='
  1590. }
  1591. return str
  1592. }
  1593. function stringtrim (str) {
  1594. if (str.trim) return str.trim()
  1595. return str.replace(/^\s+|\s+$/g, '')
  1596. }
  1597. function toHex (n) {
  1598. if (n < 16) return '0' + n.toString(16)
  1599. return n.toString(16)
  1600. }
  1601. function utf8ToBytes (string, units) {
  1602. units = units || Infinity
  1603. var codePoint
  1604. var length = string.length
  1605. var leadSurrogate = null
  1606. var bytes = []
  1607. for (var i = 0; i < length; ++i) {
  1608. codePoint = string.charCodeAt(i)
  1609. // is surrogate component
  1610. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1611. // last char was a lead
  1612. if (!leadSurrogate) {
  1613. // no lead yet
  1614. if (codePoint > 0xDBFF) {
  1615. // unexpected trail
  1616. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1617. continue
  1618. } else if (i + 1 === length) {
  1619. // unpaired lead
  1620. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1621. continue
  1622. }
  1623. // valid lead
  1624. leadSurrogate = codePoint
  1625. continue
  1626. }
  1627. // 2 leads in a row
  1628. if (codePoint < 0xDC00) {
  1629. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1630. leadSurrogate = codePoint
  1631. continue
  1632. }
  1633. // valid surrogate pair
  1634. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1635. } else if (leadSurrogate) {
  1636. // valid bmp char, but last char was a lead
  1637. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1638. }
  1639. leadSurrogate = null
  1640. // encode utf8
  1641. if (codePoint < 0x80) {
  1642. if ((units -= 1) < 0) break
  1643. bytes.push(codePoint)
  1644. } else if (codePoint < 0x800) {
  1645. if ((units -= 2) < 0) break
  1646. bytes.push(
  1647. codePoint >> 0x6 | 0xC0,
  1648. codePoint & 0x3F | 0x80
  1649. )
  1650. } else if (codePoint < 0x10000) {
  1651. if ((units -= 3) < 0) break
  1652. bytes.push(
  1653. codePoint >> 0xC | 0xE0,
  1654. codePoint >> 0x6 & 0x3F | 0x80,
  1655. codePoint & 0x3F | 0x80
  1656. )
  1657. } else if (codePoint < 0x110000) {
  1658. if ((units -= 4) < 0) break
  1659. bytes.push(
  1660. codePoint >> 0x12 | 0xF0,
  1661. codePoint >> 0xC & 0x3F | 0x80,
  1662. codePoint >> 0x6 & 0x3F | 0x80,
  1663. codePoint & 0x3F | 0x80
  1664. )
  1665. } else {
  1666. throw new Error('Invalid code point')
  1667. }
  1668. }
  1669. return bytes
  1670. }
  1671. function asciiToBytes (str) {
  1672. var byteArray = []
  1673. for (var i = 0; i < str.length; ++i) {
  1674. // Node's code seems to be doing this and not & 0x7F..
  1675. byteArray.push(str.charCodeAt(i) & 0xFF)
  1676. }
  1677. return byteArray
  1678. }
  1679. function utf16leToBytes (str, units) {
  1680. var c, hi, lo
  1681. var byteArray = []
  1682. for (var i = 0; i < str.length; ++i) {
  1683. if ((units -= 2) < 0) break
  1684. c = str.charCodeAt(i)
  1685. hi = c >> 8
  1686. lo = c % 256
  1687. byteArray.push(lo)
  1688. byteArray.push(hi)
  1689. }
  1690. return byteArray
  1691. }
  1692. function base64ToBytes (str) {
  1693. return base64.toByteArray(base64clean(str))
  1694. }
  1695. function blitBuffer (src, dst, offset, length) {
  1696. for (var i = 0; i < length; ++i) {
  1697. if ((i + offset >= dst.length) || (i >= src.length)) break
  1698. dst[i + offset] = src[i]
  1699. }
  1700. return i
  1701. }
  1702. function isnan (val) {
  1703. return val !== val // eslint-disable-line no-self-compare
  1704. }
  1705. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1706. },{"base64-js":3,"ieee754":16,"isarray":21}],7:[function(_dereq_,module,exports){
  1707. // Polyfill for creating CustomEvents on IE9/10/11
  1708. // code pulled from:
  1709. // https://github.com/d4tocchini/customevent-polyfill
  1710. // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
  1711. (function() {
  1712. if (typeof window === 'undefined') {
  1713. return;
  1714. }
  1715. try {
  1716. var ce = new window.CustomEvent('test', { cancelable: true });
  1717. ce.preventDefault();
  1718. if (ce.defaultPrevented !== true) {
  1719. // IE has problems with .preventDefault() on custom events
  1720. // http://stackoverflow.com/questions/23349191
  1721. throw new Error('Could not prevent default');
  1722. }
  1723. } catch (e) {
  1724. var CustomEvent = function(event, params) {
  1725. var evt, origPrevent;
  1726. params = params || {
  1727. bubbles: false,
  1728. cancelable: false,
  1729. detail: undefined
  1730. };
  1731. evt = document.createEvent('CustomEvent');
  1732. evt.initCustomEvent(
  1733. event,
  1734. params.bubbles,
  1735. params.cancelable,
  1736. params.detail
  1737. );
  1738. origPrevent = evt.preventDefault;
  1739. evt.preventDefault = function() {
  1740. origPrevent.call(this);
  1741. try {
  1742. Object.defineProperty(this, 'defaultPrevented', {
  1743. get: function() {
  1744. return true;
  1745. }
  1746. });
  1747. } catch (e) {
  1748. this.defaultPrevented = true;
  1749. }
  1750. };
  1751. return evt;
  1752. };
  1753. CustomEvent.prototype = window.Event.prototype;
  1754. window.CustomEvent = CustomEvent; // expose definition to window
  1755. }
  1756. })();
  1757. },{}],8:[function(_dereq_,module,exports){
  1758. /**
  1759. * This is the web browser implementation of `debug()`.
  1760. *
  1761. * Expose `debug()` as the module.
  1762. */
  1763. exports = module.exports = _dereq_('./debug');
  1764. exports.log = log;
  1765. exports.formatArgs = formatArgs;
  1766. exports.save = save;
  1767. exports.load = load;
  1768. exports.useColors = useColors;
  1769. exports.storage = 'undefined' != typeof chrome
  1770. && 'undefined' != typeof chrome.storage
  1771. ? chrome.storage.local
  1772. : localstorage();
  1773. /**
  1774. * Colors.
  1775. */
  1776. exports.colors = [
  1777. 'lightseagreen',
  1778. 'forestgreen',
  1779. 'goldenrod',
  1780. 'dodgerblue',
  1781. 'darkorchid',
  1782. 'crimson'
  1783. ];
  1784. /**
  1785. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  1786. * and the Firebug extension (any Firefox version) are known
  1787. * to support "%c" CSS customizations.
  1788. *
  1789. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  1790. */
  1791. function useColors() {
  1792. // is webkit? http://stackoverflow.com/a/16459606/376773
  1793. return ('WebkitAppearance' in document.documentElement.style) ||
  1794. // is firebug? http://stackoverflow.com/a/398120/376773
  1795. (window.console && (console.firebug || (console.exception && console.table))) ||
  1796. // is firefox >= v31?
  1797. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  1798. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  1799. }
  1800. /**
  1801. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  1802. */
  1803. exports.formatters.j = function(v) {
  1804. return JSON.stringify(v);
  1805. };
  1806. /**
  1807. * Colorize log arguments if enabled.
  1808. *
  1809. * @api public
  1810. */
  1811. function formatArgs() {
  1812. var args = arguments;
  1813. var useColors = this.useColors;
  1814. args[0] = (useColors ? '%c' : '')
  1815. + this.namespace
  1816. + (useColors ? ' %c' : ' ')
  1817. + args[0]
  1818. + (useColors ? '%c ' : ' ');
  1819. if (!useColors) return args;
  1820. var c = 'color: ' + this.color;
  1821. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  1822. // the final "%c" is somewhat tricky, because there could be other
  1823. // arguments passed either before or after the %c, so we need to
  1824. // figure out the correct index to insert the CSS into
  1825. var index = 0;
  1826. var lastC = 0;
  1827. args[0].replace(/%[a-z%]/g, function(match) {
  1828. if ('%%' === match) return;
  1829. index++;
  1830. if ('%c' === match) {
  1831. // we only are interested in the *last* %c
  1832. // (the user may have provided their own)
  1833. lastC = index;
  1834. }
  1835. });
  1836. args.splice(lastC, 0, c);
  1837. return args;
  1838. }
  1839. /**
  1840. * Invokes `console.log()` when available.
  1841. * No-op when `console.log` is not a "function".
  1842. *
  1843. * @api public
  1844. */
  1845. function log() {
  1846. // this hackery is required for IE8/9, where
  1847. // the `console.log` function doesn't have 'apply'
  1848. return 'object' === typeof console
  1849. && console.log
  1850. && Function.prototype.apply.call(console.log, console, arguments);
  1851. }
  1852. /**
  1853. * Save `namespaces`.
  1854. *
  1855. * @param {String} namespaces
  1856. * @api private
  1857. */
  1858. function save(namespaces) {
  1859. try {
  1860. if (null == namespaces) {
  1861. exports.storage.removeItem('debug');
  1862. } else {
  1863. exports.storage.debug = namespaces;
  1864. }
  1865. } catch(e) {}
  1866. }
  1867. /**
  1868. * Load `namespaces`.
  1869. *
  1870. * @return {String} returns the previously persisted debug modes
  1871. * @api private
  1872. */
  1873. function load() {
  1874. var r;
  1875. try {
  1876. r = exports.storage.debug;
  1877. } catch(e) {}
  1878. return r;
  1879. }
  1880. /**
  1881. * Enable namespaces listed in `localStorage.debug` initially.
  1882. */
  1883. exports.enable(load());
  1884. /**
  1885. * Localstorage attempts to return the localstorage.
  1886. *
  1887. * This is necessary because safari throws
  1888. * when a user disables cookies/localstorage
  1889. * and you attempt to access it.
  1890. *
  1891. * @return {LocalStorage}
  1892. * @api private
  1893. */
  1894. function localstorage(){
  1895. try {
  1896. return window.localStorage;
  1897. } catch (e) {}
  1898. }
  1899. },{"./debug":9}],9:[function(_dereq_,module,exports){
  1900. /**
  1901. * This is the common logic for both the Node.js and web browser
  1902. * implementations of `debug()`.
  1903. *
  1904. * Expose `debug()` as the module.
  1905. */
  1906. exports = module.exports = debug;
  1907. exports.coerce = coerce;
  1908. exports.disable = disable;
  1909. exports.enable = enable;
  1910. exports.enabled = enabled;
  1911. /**
  1912. * The currently active debug mode names, and names to skip.
  1913. */
  1914. exports.names = [];
  1915. exports.skips = [];
  1916. /**
  1917. * Map of special "%n" handling functions, for the debug "format" argument.
  1918. *
  1919. * Valid key names are a single, lowercased letter, i.e. "n".
  1920. */
  1921. exports.formatters = {};
  1922. /**
  1923. * Previously assigned color.
  1924. */
  1925. var prevColor = 0;
  1926. /**
  1927. * Select a color.
  1928. *
  1929. * @return {Number}
  1930. * @api private
  1931. */
  1932. function selectColor() {
  1933. return exports.colors[prevColor++ % exports.colors.length];
  1934. }
  1935. /**
  1936. * Create a debugger with the given `namespace`.
  1937. *
  1938. * @param {String} namespace
  1939. * @return {Function}
  1940. * @api public
  1941. */
  1942. function debug(namespace) {
  1943. // define the `disabled` version
  1944. function disabled() {
  1945. }
  1946. disabled.enabled = false;
  1947. // define the `enabled` version
  1948. function enabled() {
  1949. var self = enabled;
  1950. // add the `color` if not set
  1951. if (null == self.useColors) self.useColors = exports.useColors();
  1952. if (null == self.color && self.useColors) self.color = selectColor();
  1953. var args = Array.prototype.slice.call(arguments);
  1954. args[0] = exports.coerce(args[0]);
  1955. if ('string' !== typeof args[0]) {
  1956. // anything else let's inspect with %o
  1957. args = ['%o'].concat(args);
  1958. }
  1959. // apply any `formatters` transformations
  1960. var index = 0;
  1961. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  1962. // if we encounter an escaped % then don't increase the array index
  1963. if (match === '%%') return match;
  1964. index++;
  1965. var formatter = exports.formatters[format];
  1966. if ('function' === typeof formatter) {
  1967. var val = args[index];
  1968. match = formatter.call(self, val);
  1969. // now we need to remove `args[index]` since it's inlined in the `format`
  1970. args.splice(index, 1);
  1971. index--;
  1972. }
  1973. return match;
  1974. });
  1975. if ('function' === typeof exports.formatArgs) {
  1976. args = exports.formatArgs.apply(self, args);
  1977. }
  1978. var logFn = enabled.log || exports.log || console.log.bind(console);
  1979. logFn.apply(self, args);
  1980. }
  1981. enabled.enabled = true;
  1982. var fn = exports.enabled(namespace) ? enabled : disabled;
  1983. fn.namespace = namespace;
  1984. return fn;
  1985. }
  1986. /**
  1987. * Enables a debug mode by namespaces. This can include modes
  1988. * separated by a colon and wildcards.
  1989. *
  1990. * @param {String} namespaces
  1991. * @api public
  1992. */
  1993. function enable(namespaces) {
  1994. exports.save(namespaces);
  1995. var split = (namespaces || '').split(/[\s,]+/);
  1996. var len = split.length;
  1997. for (var i = 0; i < len; i++) {
  1998. if (!split[i]) continue; // ignore empty strings
  1999. namespaces = split[i].replace(/\*/g, '.*?');
  2000. if (namespaces[0] === '-') {
  2001. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2002. } else {
  2003. exports.names.push(new RegExp('^' + namespaces + '$'));
  2004. }
  2005. }
  2006. }
  2007. /**
  2008. * Disable debug output.
  2009. *
  2010. * @api public
  2011. */
  2012. function disable() {
  2013. exports.enable('');
  2014. }
  2015. /**
  2016. * Returns true if the given mode name is enabled, false otherwise.
  2017. *
  2018. * @param {String} name
  2019. * @return {Boolean}
  2020. * @api public
  2021. */
  2022. function enabled(name) {
  2023. var i, len;
  2024. for (i = 0, len = exports.skips.length; i < len; i++) {
  2025. if (exports.skips[i].test(name)) {
  2026. return false;
  2027. }
  2028. }
  2029. for (i = 0, len = exports.names.length; i < len; i++) {
  2030. if (exports.names[i].test(name)) {
  2031. return true;
  2032. }
  2033. }
  2034. return false;
  2035. }
  2036. /**
  2037. * Coerce `val`.
  2038. *
  2039. * @param {Mixed} val
  2040. * @return {Mixed}
  2041. * @api private
  2042. */
  2043. function coerce(val) {
  2044. if (val instanceof Error) return val.stack || val.message;
  2045. return val;
  2046. }
  2047. },{}],10:[function(_dereq_,module,exports){
  2048. 'use strict';
  2049. var isObj = _dereq_('is-obj');
  2050. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2051. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2052. function toObject(val) {
  2053. if (val === null || val === undefined) {
  2054. throw new TypeError('Sources cannot be null or undefined');
  2055. }
  2056. return Object(val);
  2057. }
  2058. function assignKey(to, from, key) {
  2059. var val = from[key];
  2060. if (val === undefined || val === null) {
  2061. return;
  2062. }
  2063. if (hasOwnProperty.call(to, key)) {
  2064. if (to[key] === undefined || to[key] === null) {
  2065. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2066. }
  2067. }
  2068. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2069. to[key] = val;
  2070. } else {
  2071. to[key] = assign(Object(to[key]), from[key]);
  2072. }
  2073. }
  2074. function assign(to, from) {
  2075. if (to === from) {
  2076. return to;
  2077. }
  2078. from = Object(from);
  2079. for (var key in from) {
  2080. if (hasOwnProperty.call(from, key)) {
  2081. assignKey(to, from, key);
  2082. }
  2083. }
  2084. if (Object.getOwnPropertySymbols) {
  2085. var symbols = Object.getOwnPropertySymbols(from);
  2086. for (var i = 0; i < symbols.length; i++) {
  2087. if (propIsEnumerable.call(from, symbols[i])) {
  2088. assignKey(to, from, symbols[i]);
  2089. }
  2090. }
  2091. }
  2092. return to;
  2093. }
  2094. module.exports = function deepAssign(target) {
  2095. target = toObject(target);
  2096. for (var s = 1; s < arguments.length; s++) {
  2097. assign(target, arguments[s]);
  2098. }
  2099. return target;
  2100. };
  2101. },{"is-obj":20}],11:[function(_dereq_,module,exports){
  2102. /*! (C) WebReflection Mit Style License */
  2103. (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");
  2104. },{}],12:[function(_dereq_,module,exports){
  2105. module.exports = function(dtype) {
  2106. switch (dtype) {
  2107. case 'int8':
  2108. return Int8Array
  2109. case 'int16':
  2110. return Int16Array
  2111. case 'int32':
  2112. return Int32Array
  2113. case 'uint8':
  2114. return Uint8Array
  2115. case 'uint16':
  2116. return Uint16Array
  2117. case 'uint32':
  2118. return Uint32Array
  2119. case 'float32':
  2120. return Float32Array
  2121. case 'float64':
  2122. return Float64Array
  2123. case 'array':
  2124. return Array
  2125. case 'uint8_clamped':
  2126. return Uint8ClampedArray
  2127. }
  2128. }
  2129. },{}],13:[function(_dereq_,module,exports){
  2130. /*eslint new-cap:0*/
  2131. var dtype = _dereq_('dtype')
  2132. module.exports = flattenVertexData
  2133. function flattenVertexData (data, output, offset) {
  2134. if (!data) throw new TypeError('must specify data as first parameter')
  2135. offset = +(offset || 0) | 0
  2136. if (Array.isArray(data) && Array.isArray(data[0])) {
  2137. var dim = data[0].length
  2138. var length = data.length * dim
  2139. // no output specified, create a new typed array
  2140. if (!output || typeof output === 'string') {
  2141. output = new (dtype(output || 'float32'))(length + offset)
  2142. }
  2143. var dstLength = output.length - offset
  2144. if (length !== dstLength) {
  2145. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2146. ' does not match destination length ' + dstLength)
  2147. }
  2148. for (var i = 0, k = offset; i < data.length; i++) {
  2149. for (var j = 0; j < dim; j++) {
  2150. output[k++] = data[i][j]
  2151. }
  2152. }
  2153. } else {
  2154. if (!output || typeof output === 'string') {
  2155. // no output, create a new one
  2156. var Ctor = dtype(output || 'float32')
  2157. if (offset === 0) {
  2158. output = new Ctor(data)
  2159. } else {
  2160. output = new Ctor(data.length + offset)
  2161. output.set(data, offset)
  2162. }
  2163. } else {
  2164. // store output in existing array
  2165. output.set(data, offset)
  2166. }
  2167. }
  2168. return output
  2169. }
  2170. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2171. var isFunction = _dereq_('is-function')
  2172. module.exports = forEach
  2173. var toString = Object.prototype.toString
  2174. var hasOwnProperty = Object.prototype.hasOwnProperty
  2175. function forEach(list, iterator, context) {
  2176. if (!isFunction(iterator)) {
  2177. throw new TypeError('iterator must be a function')
  2178. }
  2179. if (arguments.length < 3) {
  2180. context = this
  2181. }
  2182. if (toString.call(list) === '[object Array]')
  2183. forEachArray(list, iterator, context)
  2184. else if (typeof list === 'string')
  2185. forEachString(list, iterator, context)
  2186. else
  2187. forEachObject(list, iterator, context)
  2188. }
  2189. function forEachArray(array, iterator, context) {
  2190. for (var i = 0, len = array.length; i < len; i++) {
  2191. if (hasOwnProperty.call(array, i)) {
  2192. iterator.call(context, array[i], i, array)
  2193. }
  2194. }
  2195. }
  2196. function forEachString(string, iterator, context) {
  2197. for (var i = 0, len = string.length; i < len; i++) {
  2198. // no such thing as a sparse string.
  2199. iterator.call(context, string.charAt(i), i, string)
  2200. }
  2201. }
  2202. function forEachObject(object, iterator, context) {
  2203. for (var k in object) {
  2204. if (hasOwnProperty.call(object, k)) {
  2205. iterator.call(context, object[k], k, object)
  2206. }
  2207. }
  2208. }
  2209. },{"is-function":19}],15:[function(_dereq_,module,exports){
  2210. (function (global){
  2211. var win;
  2212. if (typeof window !== "undefined") {
  2213. win = window;
  2214. } else if (typeof global !== "undefined") {
  2215. win = global;
  2216. } else if (typeof self !== "undefined"){
  2217. win = self;
  2218. } else {
  2219. win = {};
  2220. }
  2221. module.exports = win;
  2222. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2223. },{}],16:[function(_dereq_,module,exports){
  2224. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2225. var e, m
  2226. var eLen = nBytes * 8 - mLen - 1
  2227. var eMax = (1 << eLen) - 1
  2228. var eBias = eMax >> 1
  2229. var nBits = -7
  2230. var i = isLE ? (nBytes - 1) : 0
  2231. var d = isLE ? -1 : 1
  2232. var s = buffer[offset + i]
  2233. i += d
  2234. e = s & ((1 << (-nBits)) - 1)
  2235. s >>= (-nBits)
  2236. nBits += eLen
  2237. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2238. m = e & ((1 << (-nBits)) - 1)
  2239. e >>= (-nBits)
  2240. nBits += mLen
  2241. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2242. if (e === 0) {
  2243. e = 1 - eBias
  2244. } else if (e === eMax) {
  2245. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2246. } else {
  2247. m = m + Math.pow(2, mLen)
  2248. e = e - eBias
  2249. }
  2250. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2251. }
  2252. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2253. var e, m, c
  2254. var eLen = nBytes * 8 - mLen - 1
  2255. var eMax = (1 << eLen) - 1
  2256. var eBias = eMax >> 1
  2257. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2258. var i = isLE ? 0 : (nBytes - 1)
  2259. var d = isLE ? 1 : -1
  2260. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2261. value = Math.abs(value)
  2262. if (isNaN(value) || value === Infinity) {
  2263. m = isNaN(value) ? 1 : 0
  2264. e = eMax
  2265. } else {
  2266. e = Math.floor(Math.log(value) / Math.LN2)
  2267. if (value * (c = Math.pow(2, -e)) < 1) {
  2268. e--
  2269. c *= 2
  2270. }
  2271. if (e + eBias >= 1) {
  2272. value += rt / c
  2273. } else {
  2274. value += rt * Math.pow(2, 1 - eBias)
  2275. }
  2276. if (value * c >= 2) {
  2277. e++
  2278. c /= 2
  2279. }
  2280. if (e + eBias >= eMax) {
  2281. m = 0
  2282. e = eMax
  2283. } else if (e + eBias >= 1) {
  2284. m = (value * c - 1) * Math.pow(2, mLen)
  2285. e = e + eBias
  2286. } else {
  2287. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2288. e = 0
  2289. }
  2290. }
  2291. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2292. e = (e << mLen) | m
  2293. eLen += mLen
  2294. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2295. buffer[offset + i - d] |= s * 128
  2296. }
  2297. },{}],17:[function(_dereq_,module,exports){
  2298. if (typeof Object.create === 'function') {
  2299. // implementation from standard node.js 'util' module
  2300. module.exports = function inherits(ctor, superCtor) {
  2301. ctor.super_ = superCtor
  2302. ctor.prototype = Object.create(superCtor.prototype, {
  2303. constructor: {
  2304. value: ctor,
  2305. enumerable: false,
  2306. writable: true,
  2307. configurable: true
  2308. }
  2309. });
  2310. };
  2311. } else {
  2312. // old school shim for old browsers
  2313. module.exports = function inherits(ctor, superCtor) {
  2314. ctor.super_ = superCtor
  2315. var TempCtor = function () {}
  2316. TempCtor.prototype = superCtor.prototype
  2317. ctor.prototype = new TempCtor()
  2318. ctor.prototype.constructor = ctor
  2319. }
  2320. }
  2321. },{}],18:[function(_dereq_,module,exports){
  2322. /*!
  2323. * Determine if an object is a Buffer
  2324. *
  2325. * @author Feross Aboukhadijeh <https://feross.org>
  2326. * @license MIT
  2327. */
  2328. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2329. // Object.prototype.constructor. Remove this eventually
  2330. module.exports = function (obj) {
  2331. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2332. }
  2333. function isBuffer (obj) {
  2334. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2335. }
  2336. // For Node v0.10 support. Remove this eventually.
  2337. function isSlowBuffer (obj) {
  2338. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2339. }
  2340. },{}],19:[function(_dereq_,module,exports){
  2341. module.exports = isFunction
  2342. var toString = Object.prototype.toString
  2343. function isFunction (fn) {
  2344. var string = toString.call(fn)
  2345. return string === '[object Function]' ||
  2346. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2347. (typeof window !== 'undefined' &&
  2348. // IE8 and below
  2349. (fn === window.setTimeout ||
  2350. fn === window.alert ||
  2351. fn === window.confirm ||
  2352. fn === window.prompt))
  2353. };
  2354. },{}],20:[function(_dereq_,module,exports){
  2355. 'use strict';
  2356. module.exports = function (x) {
  2357. var type = typeof x;
  2358. return x !== null && (type === 'object' || type === 'function');
  2359. };
  2360. },{}],21:[function(_dereq_,module,exports){
  2361. var toString = {}.toString;
  2362. module.exports = Array.isArray || function (arr) {
  2363. return toString.call(arr) == '[object Array]';
  2364. };
  2365. },{}],22:[function(_dereq_,module,exports){
  2366. var wordWrap = _dereq_('word-wrapper')
  2367. var xtend = _dereq_('xtend')
  2368. var number = _dereq_('as-number')
  2369. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2370. var M_WIDTHS = ['m', 'w']
  2371. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2372. var TAB_ID = '\t'.charCodeAt(0)
  2373. var SPACE_ID = ' '.charCodeAt(0)
  2374. var ALIGN_LEFT = 0,
  2375. ALIGN_CENTER = 1,
  2376. ALIGN_RIGHT = 2
  2377. module.exports = function createLayout(opt) {
  2378. return new TextLayout(opt)
  2379. }
  2380. function TextLayout(opt) {
  2381. this.glyphs = []
  2382. this._measure = this.computeMetrics.bind(this)
  2383. this.update(opt)
  2384. }
  2385. TextLayout.prototype.update = function(opt) {
  2386. opt = xtend({
  2387. measure: this._measure
  2388. }, opt)
  2389. this._opt = opt
  2390. this._opt.tabSize = number(this._opt.tabSize, 4)
  2391. if (!opt.font)
  2392. throw new Error('must provide a valid bitmap font')
  2393. var glyphs = this.glyphs
  2394. var text = opt.text||''
  2395. var font = opt.font
  2396. this._setupSpaceGlyphs(font)
  2397. var lines = wordWrap.lines(text, opt)
  2398. var minWidth = opt.width || 0
  2399. //clear glyphs
  2400. glyphs.length = 0
  2401. //get max line width
  2402. var maxLineWidth = lines.reduce(function(prev, line) {
  2403. return Math.max(prev, line.width, minWidth)
  2404. }, 0)
  2405. //the pen position
  2406. var x = 0
  2407. var y = 0
  2408. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2409. var baseline = font.common.base
  2410. var descender = lineHeight-baseline
  2411. var letterSpacing = opt.letterSpacing || 0
  2412. var height = lineHeight * lines.length - descender
  2413. var align = getAlignType(this._opt.align)
  2414. //draw text along baseline
  2415. y -= height
  2416. //the metrics for this text layout
  2417. this._width = maxLineWidth
  2418. this._height = height
  2419. this._descender = lineHeight - baseline
  2420. this._baseline = baseline
  2421. this._xHeight = getXHeight(font)
  2422. this._capHeight = getCapHeight(font)
  2423. this._lineHeight = lineHeight
  2424. this._ascender = lineHeight - descender - this._xHeight
  2425. //layout each glyph
  2426. var self = this
  2427. lines.forEach(function(line, lineIndex) {
  2428. var start = line.start
  2429. var end = line.end
  2430. var lineWidth = line.width
  2431. var lastGlyph
  2432. //for each glyph in that line...
  2433. for (var i=start; i<end; i++) {
  2434. var id = text.charCodeAt(i)
  2435. var glyph = self.getGlyph(font, id)
  2436. if (glyph) {
  2437. if (lastGlyph)
  2438. x += getKerning(font, lastGlyph.id, glyph.id)
  2439. var tx = x
  2440. if (align === ALIGN_CENTER)
  2441. tx += (maxLineWidth-lineWidth)/2
  2442. else if (align === ALIGN_RIGHT)
  2443. tx += (maxLineWidth-lineWidth)
  2444. glyphs.push({
  2445. position: [tx, y],
  2446. data: glyph,
  2447. index: i,
  2448. line: lineIndex
  2449. })
  2450. //move pen forward
  2451. x += glyph.xadvance + letterSpacing
  2452. lastGlyph = glyph
  2453. }
  2454. }
  2455. //next line down
  2456. y += lineHeight
  2457. x = 0
  2458. })
  2459. this._linesTotal = lines.length;
  2460. }
  2461. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2462. //These are fallbacks, when the font doesn't include
  2463. //' ' or '\t' glyphs
  2464. this._fallbackSpaceGlyph = null
  2465. this._fallbackTabGlyph = null
  2466. if (!font.chars || font.chars.length === 0)
  2467. return
  2468. //try to get space glyph
  2469. //then fall back to the 'm' or 'w' glyphs
  2470. //then fall back to the first glyph available
  2471. var space = getGlyphById(font, SPACE_ID)
  2472. || getMGlyph(font)
  2473. || font.chars[0]
  2474. //and create a fallback for tab
  2475. var tabWidth = this._opt.tabSize * space.xadvance
  2476. this._fallbackSpaceGlyph = space
  2477. this._fallbackTabGlyph = xtend(space, {
  2478. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2479. xoffset: 0, yoffset: 0, width: 0, height: 0
  2480. })
  2481. }
  2482. TextLayout.prototype.getGlyph = function(font, id) {
  2483. var glyph = getGlyphById(font, id)
  2484. if (glyph)
  2485. return glyph
  2486. else if (id === TAB_ID)
  2487. return this._fallbackTabGlyph
  2488. else if (id === SPACE_ID)
  2489. return this._fallbackSpaceGlyph
  2490. return null
  2491. }
  2492. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  2493. var letterSpacing = this._opt.letterSpacing || 0
  2494. var font = this._opt.font
  2495. var curPen = 0
  2496. var curWidth = 0
  2497. var count = 0
  2498. var glyph
  2499. var lastGlyph
  2500. if (!font.chars || font.chars.length === 0) {
  2501. return {
  2502. start: start,
  2503. end: start,
  2504. width: 0
  2505. }
  2506. }
  2507. end = Math.min(text.length, end)
  2508. for (var i=start; i < end; i++) {
  2509. var id = text.charCodeAt(i)
  2510. var glyph = this.getGlyph(font, id)
  2511. if (glyph) {
  2512. //move pen forward
  2513. var xoff = glyph.xoffset
  2514. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  2515. curPen += kern
  2516. var nextPen = curPen + glyph.xadvance + letterSpacing
  2517. var nextWidth = curPen + glyph.width
  2518. //we've hit our limit; we can't move onto the next glyph
  2519. if (nextWidth >= width || nextPen >= width)
  2520. break
  2521. //otherwise continue along our line
  2522. curPen = nextPen
  2523. curWidth = nextWidth
  2524. lastGlyph = glyph
  2525. }
  2526. count++
  2527. }
  2528. //make sure rightmost edge lines up with rendered glyphs
  2529. if (lastGlyph)
  2530. curWidth += lastGlyph.xoffset
  2531. return {
  2532. start: start,
  2533. end: start + count,
  2534. width: curWidth
  2535. }
  2536. }
  2537. //getters for the private vars
  2538. ;['width', 'height',
  2539. 'descender', 'ascender',
  2540. 'xHeight', 'baseline',
  2541. 'capHeight',
  2542. 'lineHeight' ].forEach(addGetter)
  2543. function addGetter(name) {
  2544. Object.defineProperty(TextLayout.prototype, name, {
  2545. get: wrapper(name),
  2546. configurable: true
  2547. })
  2548. }
  2549. //create lookups for private vars
  2550. function wrapper(name) {
  2551. return (new Function([
  2552. 'return function '+name+'() {',
  2553. ' return this._'+name,
  2554. '}'
  2555. ].join('\n')))()
  2556. }
  2557. function getGlyphById(font, id) {
  2558. if (!font.chars || font.chars.length === 0)
  2559. return null
  2560. var glyphIdx = findChar(font.chars, id)
  2561. if (glyphIdx >= 0)
  2562. return font.chars[glyphIdx]
  2563. return null
  2564. }
  2565. function getXHeight(font) {
  2566. for (var i=0; i<X_HEIGHTS.length; i++) {
  2567. var id = X_HEIGHTS[i].charCodeAt(0)
  2568. var idx = findChar(font.chars, id)
  2569. if (idx >= 0)
  2570. return font.chars[idx].height
  2571. }
  2572. return 0
  2573. }
  2574. function getMGlyph(font) {
  2575. for (var i=0; i<M_WIDTHS.length; i++) {
  2576. var id = M_WIDTHS[i].charCodeAt(0)
  2577. var idx = findChar(font.chars, id)
  2578. if (idx >= 0)
  2579. return font.chars[idx]
  2580. }
  2581. return 0
  2582. }
  2583. function getCapHeight(font) {
  2584. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  2585. var id = CAP_HEIGHTS[i].charCodeAt(0)
  2586. var idx = findChar(font.chars, id)
  2587. if (idx >= 0)
  2588. return font.chars[idx].height
  2589. }
  2590. return 0
  2591. }
  2592. function getKerning(font, left, right) {
  2593. if (!font.kernings || font.kernings.length === 0)
  2594. return 0
  2595. var table = font.kernings
  2596. for (var i=0; i<table.length; i++) {
  2597. var kern = table[i]
  2598. if (kern.first === left && kern.second === right)
  2599. return kern.amount
  2600. }
  2601. return 0
  2602. }
  2603. function getAlignType(align) {
  2604. if (align === 'center')
  2605. return ALIGN_CENTER
  2606. else if (align === 'right')
  2607. return ALIGN_RIGHT
  2608. return ALIGN_LEFT
  2609. }
  2610. function findChar (array, value, start) {
  2611. start = start || 0
  2612. for (var i = start; i < array.length; i++) {
  2613. if (array[i].id === value) {
  2614. return i
  2615. }
  2616. }
  2617. return -1
  2618. }
  2619. },{"as-number":2,"word-wrapper":47,"xtend":50}],23:[function(_dereq_,module,exports){
  2620. (function (Buffer){
  2621. var xhr = _dereq_('xhr')
  2622. var noop = function(){}
  2623. var parseASCII = _dereq_('parse-bmfont-ascii')
  2624. var parseXML = _dereq_('parse-bmfont-xml')
  2625. var readBinary = _dereq_('parse-bmfont-binary')
  2626. var isBinaryFormat = _dereq_('./lib/is-binary')
  2627. var xtend = _dereq_('xtend')
  2628. var xml2 = (function hasXML2() {
  2629. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  2630. })()
  2631. module.exports = function(opt, cb) {
  2632. cb = typeof cb === 'function' ? cb : noop
  2633. if (typeof opt === 'string')
  2634. opt = { uri: opt }
  2635. else if (!opt)
  2636. opt = {}
  2637. var expectBinary = opt.binary
  2638. if (expectBinary)
  2639. opt = getBinaryOpts(opt)
  2640. xhr(opt, function(err, res, body) {
  2641. if (err)
  2642. return cb(err)
  2643. if (!/^2/.test(res.statusCode))
  2644. return cb(new Error('http status code: '+res.statusCode))
  2645. if (!body)
  2646. return cb(new Error('no body result'))
  2647. var binary = false
  2648. //if the response type is an array buffer,
  2649. //we need to convert it into a regular Buffer object
  2650. if (isArrayBuffer(body)) {
  2651. var array = new Uint8Array(body)
  2652. body = new Buffer(array, 'binary')
  2653. }
  2654. //now check the string/Buffer response
  2655. //and see if it has a binary BMF header
  2656. if (isBinaryFormat(body)) {
  2657. binary = true
  2658. //if we have a string, turn it into a Buffer
  2659. if (typeof body === 'string')
  2660. body = new Buffer(body, 'binary')
  2661. }
  2662. //we are not parsing a binary format, just ASCII/XML/etc
  2663. if (!binary) {
  2664. //might still be a buffer if responseType is 'arraybuffer'
  2665. if (Buffer.isBuffer(body))
  2666. body = body.toString(opt.encoding)
  2667. body = body.trim()
  2668. }
  2669. var result
  2670. try {
  2671. var type = res.headers['content-type']
  2672. if (binary)
  2673. result = readBinary(body)
  2674. else if (/json/.test(type) || body.charAt(0) === '{')
  2675. result = JSON.parse(body)
  2676. else if (/xml/.test(type) || body.charAt(0) === '<')
  2677. result = parseXML(body)
  2678. else
  2679. result = parseASCII(body)
  2680. } catch (e) {
  2681. cb(new Error('error parsing font '+e.message))
  2682. cb = noop
  2683. }
  2684. cb(null, result)
  2685. })
  2686. }
  2687. function isArrayBuffer(arr) {
  2688. var str = Object.prototype.toString
  2689. return str.call(arr) === '[object ArrayBuffer]'
  2690. }
  2691. function getBinaryOpts(opt) {
  2692. //IE10+ and other modern browsers support array buffers
  2693. if (xml2)
  2694. return xtend(opt, { responseType: 'arraybuffer' })
  2695. if (typeof self.XMLHttpRequest === 'undefined')
  2696. throw new Error('your browser does not support XHR loading')
  2697. //IE9 and XML1 browsers could still use an override
  2698. var req = new self.XMLHttpRequest()
  2699. req.overrideMimeType('text/plain; charset=x-user-defined')
  2700. return xtend({
  2701. xhr: req
  2702. }, opt)
  2703. }
  2704. }).call(this,_dereq_("buffer").Buffer)
  2705. },{"./lib/is-binary":24,"buffer":6,"parse-bmfont-ascii":26,"parse-bmfont-binary":27,"parse-bmfont-xml":28,"xhr":48,"xtend":50}],24:[function(_dereq_,module,exports){
  2706. (function (Buffer){
  2707. var equal = _dereq_('buffer-equal')
  2708. var HEADER = new Buffer([66, 77, 70, 3])
  2709. module.exports = function(buf) {
  2710. if (typeof buf === 'string')
  2711. return buf.substring(0, 3) === 'BMF'
  2712. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  2713. }
  2714. }).call(this,_dereq_("buffer").Buffer)
  2715. },{"buffer":6,"buffer-equal":5}],25:[function(_dereq_,module,exports){
  2716. /*
  2717. object-assign
  2718. (c) Sindre Sorhus
  2719. @license MIT
  2720. */
  2721. 'use strict';
  2722. /* eslint-disable no-unused-vars */
  2723. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  2724. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2725. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2726. function toObject(val) {
  2727. if (val === null || val === undefined) {
  2728. throw new TypeError('Object.assign cannot be called with null or undefined');
  2729. }
  2730. return Object(val);
  2731. }
  2732. function shouldUseNative() {
  2733. try {
  2734. if (!Object.assign) {
  2735. return false;
  2736. }
  2737. // Detect buggy property enumeration order in older V8 versions.
  2738. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  2739. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  2740. test1[5] = 'de';
  2741. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  2742. return false;
  2743. }
  2744. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2745. var test2 = {};
  2746. for (var i = 0; i < 10; i++) {
  2747. test2['_' + String.fromCharCode(i)] = i;
  2748. }
  2749. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  2750. return test2[n];
  2751. });
  2752. if (order2.join('') !== '0123456789') {
  2753. return false;
  2754. }
  2755. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  2756. var test3 = {};
  2757. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  2758. test3[letter] = letter;
  2759. });
  2760. if (Object.keys(Object.assign({}, test3)).join('') !==
  2761. 'abcdefghijklmnopqrst') {
  2762. return false;
  2763. }
  2764. return true;
  2765. } catch (err) {
  2766. // We don't expect any of the above to throw, but better to be safe.
  2767. return false;
  2768. }
  2769. }
  2770. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  2771. var from;
  2772. var to = toObject(target);
  2773. var symbols;
  2774. for (var s = 1; s < arguments.length; s++) {
  2775. from = Object(arguments[s]);
  2776. for (var key in from) {
  2777. if (hasOwnProperty.call(from, key)) {
  2778. to[key] = from[key];
  2779. }
  2780. }
  2781. if (getOwnPropertySymbols) {
  2782. symbols = getOwnPropertySymbols(from);
  2783. for (var i = 0; i < symbols.length; i++) {
  2784. if (propIsEnumerable.call(from, symbols[i])) {
  2785. to[symbols[i]] = from[symbols[i]];
  2786. }
  2787. }
  2788. }
  2789. }
  2790. return to;
  2791. };
  2792. },{}],26:[function(_dereq_,module,exports){
  2793. module.exports = function parseBMFontAscii(data) {
  2794. if (!data)
  2795. throw new Error('no data provided')
  2796. data = data.toString().trim()
  2797. var output = {
  2798. pages: [],
  2799. chars: [],
  2800. kernings: []
  2801. }
  2802. var lines = data.split(/\r\n?|\n/g)
  2803. if (lines.length === 0)
  2804. throw new Error('no data in BMFont file')
  2805. for (var i = 0; i < lines.length; i++) {
  2806. var lineData = splitLine(lines[i], i)
  2807. if (!lineData) //skip empty lines
  2808. continue
  2809. if (lineData.key === 'page') {
  2810. if (typeof lineData.data.id !== 'number')
  2811. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  2812. if (typeof lineData.data.file !== 'string')
  2813. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  2814. output.pages[lineData.data.id] = lineData.data.file
  2815. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  2816. //... do nothing for these two ...
  2817. } else if (lineData.key === 'char') {
  2818. output.chars.push(lineData.data)
  2819. } else if (lineData.key === 'kerning') {
  2820. output.kernings.push(lineData.data)
  2821. } else {
  2822. output[lineData.key] = lineData.data
  2823. }
  2824. }
  2825. return output
  2826. }
  2827. function splitLine(line, idx) {
  2828. line = line.replace(/\t+/g, ' ').trim()
  2829. if (!line)
  2830. return null
  2831. var space = line.indexOf(' ')
  2832. if (space === -1)
  2833. throw new Error("no named row at line " + idx)
  2834. var key = line.substring(0, space)
  2835. line = line.substring(space + 1)
  2836. //clear "letter" field as it is non-standard and
  2837. //requires additional complexity to parse " / = symbols
  2838. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  2839. line = line.split("=")
  2840. line = line.map(function(str) {
  2841. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  2842. })
  2843. var data = []
  2844. for (var i = 0; i < line.length; i++) {
  2845. var dt = line[i]
  2846. if (i === 0) {
  2847. data.push({
  2848. key: dt[0],
  2849. data: ""
  2850. })
  2851. } else if (i === line.length - 1) {
  2852. data[data.length - 1].data = parseData(dt[0])
  2853. } else {
  2854. data[data.length - 1].data = parseData(dt[0])
  2855. data.push({
  2856. key: dt[1],
  2857. data: ""
  2858. })
  2859. }
  2860. }
  2861. var out = {
  2862. key: key,
  2863. data: {}
  2864. }
  2865. data.forEach(function(v) {
  2866. out.data[v.key] = v.data;
  2867. })
  2868. return out
  2869. }
  2870. function parseData(data) {
  2871. if (!data || data.length === 0)
  2872. return ""
  2873. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  2874. return data.substring(1, data.length - 1)
  2875. if (data.indexOf(',') !== -1)
  2876. return parseIntList(data)
  2877. return parseInt(data, 10)
  2878. }
  2879. function parseIntList(data) {
  2880. return data.split(',').map(function(val) {
  2881. return parseInt(val, 10)
  2882. })
  2883. }
  2884. },{}],27:[function(_dereq_,module,exports){
  2885. var HEADER = [66, 77, 70]
  2886. module.exports = function readBMFontBinary(buf) {
  2887. if (buf.length < 6)
  2888. throw new Error('invalid buffer length for BMFont')
  2889. var header = HEADER.every(function(byte, i) {
  2890. return buf.readUInt8(i) === byte
  2891. })
  2892. if (!header)
  2893. throw new Error('BMFont missing BMF byte header')
  2894. var i = 3
  2895. var vers = buf.readUInt8(i++)
  2896. if (vers > 3)
  2897. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  2898. var target = { kernings: [], chars: [] }
  2899. for (var b=0; b<5; b++)
  2900. i += readBlock(target, buf, i)
  2901. return target
  2902. }
  2903. function readBlock(target, buf, i) {
  2904. if (i > buf.length-1)
  2905. return 0
  2906. var blockID = buf.readUInt8(i++)
  2907. var blockSize = buf.readInt32LE(i)
  2908. i += 4
  2909. switch(blockID) {
  2910. case 1:
  2911. target.info = readInfo(buf, i)
  2912. break
  2913. case 2:
  2914. target.common = readCommon(buf, i)
  2915. break
  2916. case 3:
  2917. target.pages = readPages(buf, i, blockSize)
  2918. break
  2919. case 4:
  2920. target.chars = readChars(buf, i, blockSize)
  2921. break
  2922. case 5:
  2923. target.kernings = readKernings(buf, i, blockSize)
  2924. break
  2925. }
  2926. return 5 + blockSize
  2927. }
  2928. function readInfo(buf, i) {
  2929. var info = {}
  2930. info.size = buf.readInt16LE(i)
  2931. var bitField = buf.readUInt8(i+2)
  2932. info.smooth = (bitField >> 7) & 1
  2933. info.unicode = (bitField >> 6) & 1
  2934. info.italic = (bitField >> 5) & 1
  2935. info.bold = (bitField >> 4) & 1
  2936. //fixedHeight is only mentioned in binary spec
  2937. if ((bitField >> 3) & 1)
  2938. info.fixedHeight = 1
  2939. info.charset = buf.readUInt8(i+3) || ''
  2940. info.stretchH = buf.readUInt16LE(i+4)
  2941. info.aa = buf.readUInt8(i+6)
  2942. info.padding = [
  2943. buf.readInt8(i+7),
  2944. buf.readInt8(i+8),
  2945. buf.readInt8(i+9),
  2946. buf.readInt8(i+10)
  2947. ]
  2948. info.spacing = [
  2949. buf.readInt8(i+11),
  2950. buf.readInt8(i+12)
  2951. ]
  2952. info.outline = buf.readUInt8(i+13)
  2953. info.face = readStringNT(buf, i+14)
  2954. return info
  2955. }
  2956. function readCommon(buf, i) {
  2957. var common = {}
  2958. common.lineHeight = buf.readUInt16LE(i)
  2959. common.base = buf.readUInt16LE(i+2)
  2960. common.scaleW = buf.readUInt16LE(i+4)
  2961. common.scaleH = buf.readUInt16LE(i+6)
  2962. common.pages = buf.readUInt16LE(i+8)
  2963. var bitField = buf.readUInt8(i+10)
  2964. common.packed = 0
  2965. common.alphaChnl = buf.readUInt8(i+11)
  2966. common.redChnl = buf.readUInt8(i+12)
  2967. common.greenChnl = buf.readUInt8(i+13)
  2968. common.blueChnl = buf.readUInt8(i+14)
  2969. return common
  2970. }
  2971. function readPages(buf, i, size) {
  2972. var pages = []
  2973. var text = readNameNT(buf, i)
  2974. var len = text.length+1
  2975. var count = size / len
  2976. for (var c=0; c<count; c++) {
  2977. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  2978. i += len
  2979. }
  2980. return pages
  2981. }
  2982. function readChars(buf, i, blockSize) {
  2983. var chars = []
  2984. var count = blockSize / 20
  2985. for (var c=0; c<count; c++) {
  2986. var char = {}
  2987. var off = c*20
  2988. char.id = buf.readUInt32LE(i + 0 + off)
  2989. char.x = buf.readUInt16LE(i + 4 + off)
  2990. char.y = buf.readUInt16LE(i + 6 + off)
  2991. char.width = buf.readUInt16LE(i + 8 + off)
  2992. char.height = buf.readUInt16LE(i + 10 + off)
  2993. char.xoffset = buf.readInt16LE(i + 12 + off)
  2994. char.yoffset = buf.readInt16LE(i + 14 + off)
  2995. char.xadvance = buf.readInt16LE(i + 16 + off)
  2996. char.page = buf.readUInt8(i + 18 + off)
  2997. char.chnl = buf.readUInt8(i + 19 + off)
  2998. chars[c] = char
  2999. }
  3000. return chars
  3001. }
  3002. function readKernings(buf, i, blockSize) {
  3003. var kernings = []
  3004. var count = blockSize / 10
  3005. for (var c=0; c<count; c++) {
  3006. var kern = {}
  3007. var off = c*10
  3008. kern.first = buf.readUInt32LE(i + 0 + off)
  3009. kern.second = buf.readUInt32LE(i + 4 + off)
  3010. kern.amount = buf.readInt16LE(i + 8 + off)
  3011. kernings[c] = kern
  3012. }
  3013. return kernings
  3014. }
  3015. function readNameNT(buf, offset) {
  3016. var pos=offset
  3017. for (; pos<buf.length; pos++) {
  3018. if (buf[pos] === 0x00)
  3019. break
  3020. }
  3021. return buf.slice(offset, pos)
  3022. }
  3023. function readStringNT(buf, offset) {
  3024. return readNameNT(buf, offset).toString('utf8')
  3025. }
  3026. },{}],28:[function(_dereq_,module,exports){
  3027. var parseAttributes = _dereq_('./parse-attribs')
  3028. var parseFromString = _dereq_('xml-parse-from-string')
  3029. //In some cases element.attribute.nodeName can return
  3030. //all lowercase values.. so we need to map them to the correct
  3031. //case
  3032. var NAME_MAP = {
  3033. scaleh: 'scaleH',
  3034. scalew: 'scaleW',
  3035. stretchh: 'stretchH',
  3036. lineheight: 'lineHeight',
  3037. alphachnl: 'alphaChnl',
  3038. redchnl: 'redChnl',
  3039. greenchnl: 'greenChnl',
  3040. bluechnl: 'blueChnl'
  3041. }
  3042. module.exports = function parse(data) {
  3043. data = data.toString()
  3044. var xmlRoot = parseFromString(data)
  3045. var output = {
  3046. pages: [],
  3047. chars: [],
  3048. kernings: []
  3049. }
  3050. //get config settings
  3051. ;['info', 'common'].forEach(function(key) {
  3052. var element = xmlRoot.getElementsByTagName(key)[0]
  3053. if (element)
  3054. output[key] = parseAttributes(getAttribs(element))
  3055. })
  3056. //get page info
  3057. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3058. if (!pageRoot)
  3059. throw new Error('malformed file -- no <pages> element')
  3060. var pages = pageRoot.getElementsByTagName('page')
  3061. for (var i=0; i<pages.length; i++) {
  3062. var p = pages[i]
  3063. var id = parseInt(p.getAttribute('id'), 10)
  3064. var file = p.getAttribute('file')
  3065. if (isNaN(id))
  3066. throw new Error('malformed file -- page "id" attribute is NaN')
  3067. if (!file)
  3068. throw new Error('malformed file -- needs page "file" attribute')
  3069. output.pages[parseInt(id, 10)] = file
  3070. }
  3071. //get kernings / chars
  3072. ;['chars', 'kernings'].forEach(function(key) {
  3073. var element = xmlRoot.getElementsByTagName(key)[0]
  3074. if (!element)
  3075. return
  3076. var childTag = key.substring(0, key.length-1)
  3077. var children = element.getElementsByTagName(childTag)
  3078. for (var i=0; i<children.length; i++) {
  3079. var child = children[i]
  3080. output[key].push(parseAttributes(getAttribs(child)))
  3081. }
  3082. })
  3083. return output
  3084. }
  3085. function getAttribs(element) {
  3086. var attribs = getAttribList(element)
  3087. return attribs.reduce(function(dict, attrib) {
  3088. var key = mapName(attrib.nodeName)
  3089. dict[key] = attrib.nodeValue
  3090. return dict
  3091. }, {})
  3092. }
  3093. function getAttribList(element) {
  3094. //IE8+ and modern browsers
  3095. var attribs = []
  3096. for (var i=0; i<element.attributes.length; i++)
  3097. attribs.push(element.attributes[i])
  3098. return attribs
  3099. }
  3100. function mapName(nodeName) {
  3101. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3102. }
  3103. },{"./parse-attribs":29,"xml-parse-from-string":49}],29:[function(_dereq_,module,exports){
  3104. //Some versions of GlyphDesigner have a typo
  3105. //that causes some bugs with parsing.
  3106. //Need to confirm with recent version of the software
  3107. //to see whether this is still an issue or not.
  3108. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3109. module.exports = function parseAttributes(obj) {
  3110. if (GLYPH_DESIGNER_ERROR in obj) {
  3111. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3112. delete obj[GLYPH_DESIGNER_ERROR]
  3113. }
  3114. for (var k in obj) {
  3115. if (k === 'face' || k === 'charset')
  3116. continue
  3117. else if (k === 'padding' || k === 'spacing')
  3118. obj[k] = parseIntList(obj[k])
  3119. else
  3120. obj[k] = parseInt(obj[k], 10)
  3121. }
  3122. return obj
  3123. }
  3124. function parseIntList(data) {
  3125. return data.split(',').map(function(val) {
  3126. return parseInt(val, 10)
  3127. })
  3128. }
  3129. },{}],30:[function(_dereq_,module,exports){
  3130. var trim = _dereq_('trim')
  3131. , forEach = _dereq_('for-each')
  3132. , isArray = function(arg) {
  3133. return Object.prototype.toString.call(arg) === '[object Array]';
  3134. }
  3135. module.exports = function (headers) {
  3136. if (!headers)
  3137. return {}
  3138. var result = {}
  3139. forEach(
  3140. trim(headers).split('\n')
  3141. , function (row) {
  3142. var index = row.indexOf(':')
  3143. , key = trim(row.slice(0, index)).toLowerCase()
  3144. , value = trim(row.slice(index + 1))
  3145. if (typeof(result[key]) === 'undefined') {
  3146. result[key] = value
  3147. } else if (isArray(result[key])) {
  3148. result[key].push(value)
  3149. } else {
  3150. result[key] = [ result[key], value ]
  3151. }
  3152. }
  3153. )
  3154. return result
  3155. }
  3156. },{"for-each":14,"trim":45}],31:[function(_dereq_,module,exports){
  3157. (function (global){
  3158. var performance = global.performance || {};
  3159. var present = (function () {
  3160. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3161. while (names.length) {
  3162. var name = names.shift();
  3163. if (name in performance) {
  3164. return performance[name].bind(performance);
  3165. }
  3166. }
  3167. var dateNow = Date.now || function () { return new Date().getTime(); };
  3168. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3169. return function () {
  3170. return dateNow() - navigationStart;
  3171. };
  3172. }());
  3173. present.performanceNow = performance.now;
  3174. present.noConflict = function () {
  3175. performance.now = present.performanceNow;
  3176. };
  3177. present.conflict = function () {
  3178. performance.now = present;
  3179. };
  3180. present.conflict();
  3181. module.exports = present;
  3182. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3183. },{}],32:[function(_dereq_,module,exports){
  3184. // shim for using process in browser
  3185. var process = module.exports = {};
  3186. // cached from whatever global is present so that test runners that stub it
  3187. // don't break things. But we need to wrap it in a try catch in case it is
  3188. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3189. // function because try/catches deoptimize in certain engines.
  3190. var cachedSetTimeout;
  3191. var cachedClearTimeout;
  3192. function defaultSetTimout() {
  3193. throw new Error('setTimeout has not been defined');
  3194. }
  3195. function defaultClearTimeout () {
  3196. throw new Error('clearTimeout has not been defined');
  3197. }
  3198. (function () {
  3199. try {
  3200. if (typeof setTimeout === 'function') {
  3201. cachedSetTimeout = setTimeout;
  3202. } else {
  3203. cachedSetTimeout = defaultSetTimout;
  3204. }
  3205. } catch (e) {
  3206. cachedSetTimeout = defaultSetTimout;
  3207. }
  3208. try {
  3209. if (typeof clearTimeout === 'function') {
  3210. cachedClearTimeout = clearTimeout;
  3211. } else {
  3212. cachedClearTimeout = defaultClearTimeout;
  3213. }
  3214. } catch (e) {
  3215. cachedClearTimeout = defaultClearTimeout;
  3216. }
  3217. } ())
  3218. function runTimeout(fun) {
  3219. if (cachedSetTimeout === setTimeout) {
  3220. //normal enviroments in sane situations
  3221. return setTimeout(fun, 0);
  3222. }
  3223. // if setTimeout wasn't available but was latter defined
  3224. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3225. cachedSetTimeout = setTimeout;
  3226. return setTimeout(fun, 0);
  3227. }
  3228. try {
  3229. // when when somebody has screwed with setTimeout but no I.E. maddness
  3230. return cachedSetTimeout(fun, 0);
  3231. } catch(e){
  3232. try {
  3233. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3234. return cachedSetTimeout.call(null, fun, 0);
  3235. } catch(e){
  3236. // 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
  3237. return cachedSetTimeout.call(this, fun, 0);
  3238. }
  3239. }
  3240. }
  3241. function runClearTimeout(marker) {
  3242. if (cachedClearTimeout === clearTimeout) {
  3243. //normal enviroments in sane situations
  3244. return clearTimeout(marker);
  3245. }
  3246. // if clearTimeout wasn't available but was latter defined
  3247. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3248. cachedClearTimeout = clearTimeout;
  3249. return clearTimeout(marker);
  3250. }
  3251. try {
  3252. // when when somebody has screwed with setTimeout but no I.E. maddness
  3253. return cachedClearTimeout(marker);
  3254. } catch (e){
  3255. try {
  3256. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3257. return cachedClearTimeout.call(null, marker);
  3258. } catch (e){
  3259. // 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.
  3260. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3261. return cachedClearTimeout.call(this, marker);
  3262. }
  3263. }
  3264. }
  3265. var queue = [];
  3266. var draining = false;
  3267. var currentQueue;
  3268. var queueIndex = -1;
  3269. function cleanUpNextTick() {
  3270. if (!draining || !currentQueue) {
  3271. return;
  3272. }
  3273. draining = false;
  3274. if (currentQueue.length) {
  3275. queue = currentQueue.concat(queue);
  3276. } else {
  3277. queueIndex = -1;
  3278. }
  3279. if (queue.length) {
  3280. drainQueue();
  3281. }
  3282. }
  3283. function drainQueue() {
  3284. if (draining) {
  3285. return;
  3286. }
  3287. var timeout = runTimeout(cleanUpNextTick);
  3288. draining = true;
  3289. var len = queue.length;
  3290. while(len) {
  3291. currentQueue = queue;
  3292. queue = [];
  3293. while (++queueIndex < len) {
  3294. if (currentQueue) {
  3295. currentQueue[queueIndex].run();
  3296. }
  3297. }
  3298. queueIndex = -1;
  3299. len = queue.length;
  3300. }
  3301. currentQueue = null;
  3302. draining = false;
  3303. runClearTimeout(timeout);
  3304. }
  3305. process.nextTick = function (fun) {
  3306. var args = new Array(arguments.length - 1);
  3307. if (arguments.length > 1) {
  3308. for (var i = 1; i < arguments.length; i++) {
  3309. args[i - 1] = arguments[i];
  3310. }
  3311. }
  3312. queue.push(new Item(fun, args));
  3313. if (queue.length === 1 && !draining) {
  3314. runTimeout(drainQueue);
  3315. }
  3316. };
  3317. // v8 likes predictible objects
  3318. function Item(fun, array) {
  3319. this.fun = fun;
  3320. this.array = array;
  3321. }
  3322. Item.prototype.run = function () {
  3323. this.fun.apply(null, this.array);
  3324. };
  3325. process.title = 'browser';
  3326. process.browser = true;
  3327. process.env = {};
  3328. process.argv = [];
  3329. process.version = ''; // empty string to avoid regexp issues
  3330. process.versions = {};
  3331. function noop() {}
  3332. process.on = noop;
  3333. process.addListener = noop;
  3334. process.once = noop;
  3335. process.off = noop;
  3336. process.removeListener = noop;
  3337. process.removeAllListeners = noop;
  3338. process.emit = noop;
  3339. process.prependListener = noop;
  3340. process.prependOnceListener = noop;
  3341. process.listeners = function (name) { return [] }
  3342. process.binding = function (name) {
  3343. throw new Error('process.binding is not supported');
  3344. };
  3345. process.cwd = function () { return '/' };
  3346. process.chdir = function (dir) {
  3347. throw new Error('process.chdir is not supported');
  3348. };
  3349. process.umask = function() { return 0; };
  3350. },{}],33:[function(_dereq_,module,exports){
  3351. (function(root) {
  3352. // Store setTimeout reference so promise-polyfill will be unaffected by
  3353. // other code modifying setTimeout (like sinon.useFakeTimers())
  3354. var setTimeoutFunc = setTimeout;
  3355. // Use polyfill for setImmediate for performance gains
  3356. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3357. function(fn) { setTimeoutFunc(fn, 1); };
  3358. // Polyfill for Function.prototype.bind
  3359. function bind(fn, thisArg) {
  3360. return function() {
  3361. fn.apply(thisArg, arguments);
  3362. }
  3363. }
  3364. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3365. function Promise(fn) {
  3366. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3367. if (typeof fn !== 'function') throw new TypeError('not a function');
  3368. this._state = null;
  3369. this._value = null;
  3370. this._deferreds = []
  3371. doResolve(fn, bind(resolve, this), bind(reject, this))
  3372. }
  3373. function handle(deferred) {
  3374. var me = this;
  3375. if (this._state === null) {
  3376. this._deferreds.push(deferred);
  3377. return
  3378. }
  3379. asap(function() {
  3380. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3381. if (cb === null) {
  3382. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3383. return;
  3384. }
  3385. var ret;
  3386. try {
  3387. ret = cb(me._value);
  3388. }
  3389. catch (e) {
  3390. deferred.reject(e);
  3391. return;
  3392. }
  3393. deferred.resolve(ret);
  3394. })
  3395. }
  3396. function resolve(newValue) {
  3397. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3398. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3399. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3400. var then = newValue.then;
  3401. if (typeof then === 'function') {
  3402. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3403. return;
  3404. }
  3405. }
  3406. this._state = true;
  3407. this._value = newValue;
  3408. finale.call(this);
  3409. } catch (e) { reject.call(this, e); }
  3410. }
  3411. function reject(newValue) {
  3412. this._state = false;
  3413. this._value = newValue;
  3414. finale.call(this);
  3415. }
  3416. function finale() {
  3417. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3418. handle.call(this, this._deferreds[i]);
  3419. }
  3420. this._deferreds = null;
  3421. }
  3422. function Handler(onFulfilled, onRejected, resolve, reject){
  3423. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3424. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3425. this.resolve = resolve;
  3426. this.reject = reject;
  3427. }
  3428. /**
  3429. * Take a potentially misbehaving resolver function and make sure
  3430. * onFulfilled and onRejected are only called once.
  3431. *
  3432. * Makes no guarantees about asynchrony.
  3433. */
  3434. function doResolve(fn, onFulfilled, onRejected) {
  3435. var done = false;
  3436. try {
  3437. fn(function (value) {
  3438. if (done) return;
  3439. done = true;
  3440. onFulfilled(value);
  3441. }, function (reason) {
  3442. if (done) return;
  3443. done = true;
  3444. onRejected(reason);
  3445. })
  3446. } catch (ex) {
  3447. if (done) return;
  3448. done = true;
  3449. onRejected(ex);
  3450. }
  3451. }
  3452. Promise.prototype['catch'] = function (onRejected) {
  3453. return this.then(null, onRejected);
  3454. };
  3455. Promise.prototype.then = function(onFulfilled, onRejected) {
  3456. var me = this;
  3457. return new Promise(function(resolve, reject) {
  3458. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3459. })
  3460. };
  3461. Promise.all = function () {
  3462. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3463. return new Promise(function (resolve, reject) {
  3464. if (args.length === 0) return resolve([]);
  3465. var remaining = args.length;
  3466. function res(i, val) {
  3467. try {
  3468. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3469. var then = val.then;
  3470. if (typeof then === 'function') {
  3471. then.call(val, function (val) { res(i, val) }, reject);
  3472. return;
  3473. }
  3474. }
  3475. args[i] = val;
  3476. if (--remaining === 0) {
  3477. resolve(args);
  3478. }
  3479. } catch (ex) {
  3480. reject(ex);
  3481. }
  3482. }
  3483. for (var i = 0; i < args.length; i++) {
  3484. res(i, args[i]);
  3485. }
  3486. });
  3487. };
  3488. Promise.resolve = function (value) {
  3489. if (value && typeof value === 'object' && value.constructor === Promise) {
  3490. return value;
  3491. }
  3492. return new Promise(function (resolve) {
  3493. resolve(value);
  3494. });
  3495. };
  3496. Promise.reject = function (value) {
  3497. return new Promise(function (resolve, reject) {
  3498. reject(value);
  3499. });
  3500. };
  3501. Promise.race = function (values) {
  3502. return new Promise(function (resolve, reject) {
  3503. for(var i = 0, len = values.length; i < len; i++) {
  3504. values[i].then(resolve, reject);
  3505. }
  3506. });
  3507. };
  3508. /**
  3509. * Set the immediate function to execute callbacks
  3510. * @param fn {function} Function to execute
  3511. * @private
  3512. */
  3513. Promise._setImmediateFn = function _setImmediateFn(fn) {
  3514. asap = fn;
  3515. };
  3516. if (typeof module !== 'undefined' && module.exports) {
  3517. module.exports = Promise;
  3518. } else if (!root.Promise) {
  3519. root.Promise = Promise;
  3520. }
  3521. })(this);
  3522. },{}],34:[function(_dereq_,module,exports){
  3523. var dtype = _dereq_('dtype')
  3524. var anArray = _dereq_('an-array')
  3525. var isBuffer = _dereq_('is-buffer')
  3526. var CW = [0, 2, 3]
  3527. var CCW = [2, 1, 3]
  3528. module.exports = function createQuadElements(array, opt) {
  3529. //if user didn't specify an output array
  3530. if (!array || !(anArray(array) || isBuffer(array))) {
  3531. opt = array || {}
  3532. array = null
  3533. }
  3534. if (typeof opt === 'number') //backwards-compatible
  3535. opt = { count: opt }
  3536. else
  3537. opt = opt || {}
  3538. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  3539. var count = typeof opt.count === 'number' ? opt.count : 1
  3540. var start = (opt.start || 0)
  3541. var dir = opt.clockwise !== false ? CW : CCW,
  3542. a = dir[0],
  3543. b = dir[1],
  3544. c = dir[2]
  3545. var numIndices = count * 6
  3546. var indices = array || new (dtype(type))(numIndices)
  3547. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  3548. var x = i + start
  3549. indices[x + 0] = j + 0
  3550. indices[x + 1] = j + 1
  3551. indices[x + 2] = j + 2
  3552. indices[x + 3] = j + a
  3553. indices[x + 4] = j + b
  3554. indices[x + 5] = j + c
  3555. }
  3556. return indices
  3557. }
  3558. },{"an-array":1,"dtype":12,"is-buffer":18}],35:[function(_dereq_,module,exports){
  3559. /*
  3560. * anime.js v3.0.0
  3561. * (c) 2019 Julian Garnier
  3562. * Released under the MIT license
  3563. * animejs.com
  3564. */
  3565. 'use strict';
  3566. // Defaults
  3567. var defaultInstanceSettings = {
  3568. update: null,
  3569. begin: null,
  3570. loopBegin: null,
  3571. changeBegin: null,
  3572. change: null,
  3573. changeComplete: null,
  3574. loopComplete: null,
  3575. complete: null,
  3576. loop: 1,
  3577. direction: 'normal',
  3578. autoplay: true,
  3579. timelineOffset: 0
  3580. };
  3581. var defaultTweenSettings = {
  3582. duration: 1000,
  3583. delay: 0,
  3584. endDelay: 0,
  3585. easing: 'easeOutElastic(1, .5)',
  3586. round: 0
  3587. };
  3588. var validTransforms = ['translateX', 'translateY', 'translateZ', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'scale', 'scaleX', 'scaleY', 'scaleZ', 'skew', 'skewX', 'skewY', 'perspective'];
  3589. // Caching
  3590. var cache = {
  3591. CSS: {},
  3592. springs: {}
  3593. };
  3594. // Utils
  3595. function minMax(val, min, max) {
  3596. return Math.min(Math.max(val, min), max);
  3597. }
  3598. function stringContains(str, text) {
  3599. return str.indexOf(text) > -1;
  3600. }
  3601. function applyArguments(func, args) {
  3602. return func.apply(null, args);
  3603. }
  3604. var hexRegex = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;
  3605. var rgbPrefixRegex = /^rgb/;
  3606. var hslRegex = /^hsl/;
  3607. var is = {
  3608. arr: function (a) { return Array.isArray(a); },
  3609. obj: function (a) { return stringContains(Object.prototype.toString.call(a), 'Object'); },
  3610. pth: function (a) { return is.obj(a) && a.hasOwnProperty('totalLength'); },
  3611. svg: function (a) { return a instanceof SVGElement; },
  3612. inp: function (a) { return a instanceof HTMLInputElement; },
  3613. dom: function (a) { return a.nodeType || is.svg(a); },
  3614. str: function (a) { return typeof a === 'string'; },
  3615. fnc: function (a) { return typeof a === 'function'; },
  3616. und: function (a) { return typeof a === 'undefined'; },
  3617. hex: function (a) { return hexRegex.test(a); },
  3618. rgb: function (a) { return rgbPrefixRegex.test(a); },
  3619. hsl: function (a) { return hslRegex.test(a); },
  3620. col: function (a) { return (is.hex(a) || is.rgb(a) || is.hsl(a)); },
  3621. key: function (a) { return !defaultInstanceSettings.hasOwnProperty(a) && !defaultTweenSettings.hasOwnProperty(a) && a !== 'targets' && a !== 'keyframes'; }
  3622. };
  3623. // Easings
  3624. var easingFunctionRegex = /\(([^)]+)\)/;
  3625. function parseEasingParameters(string) {
  3626. var match = easingFunctionRegex.exec(string);
  3627. return match ? match[1].split(',').map(function (p) { return parseFloat(p); }) : [];
  3628. }
  3629. // Spring solver inspired by Webkit Copyright © 2016 Apple Inc. All rights reserved. https://webkit.org/demos/spring/spring.js
  3630. function spring(string, duration) {
  3631. var params = parseEasingParameters(string);
  3632. var mass = minMax(is.und(params[0]) ? 1 : params[0], .1, 100);
  3633. var stiffness = minMax(is.und(params[1]) ? 100 : params[1], .1, 100);
  3634. var damping = minMax(is.und(params[2]) ? 10 : params[2], .1, 100);
  3635. var velocity = minMax(is.und(params[3]) ? 0 : params[3], .1, 100);
  3636. var w0 = Math.sqrt(stiffness / mass);
  3637. var zeta = damping / (2 * Math.sqrt(stiffness * mass));
  3638. var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
  3639. var a = 1;
  3640. var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
  3641. function solver(t) {
  3642. var progress = duration ? (duration * t) / 1000 : t;
  3643. if (zeta < 1) {
  3644. progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
  3645. } else {
  3646. progress = (a + b * progress) * Math.exp(-progress * w0);
  3647. }
  3648. if (t === 0 || t === 1) { return t; }
  3649. return 1 - progress;
  3650. }
  3651. function getDuration() {
  3652. var cached = cache.springs[string];
  3653. if (cached) { return cached; }
  3654. var frame = 1/6;
  3655. var elapsed = 0;
  3656. var rest = 0;
  3657. while(true) {
  3658. elapsed += frame;
  3659. if (solver(elapsed) === 1) {
  3660. rest++;
  3661. if (rest >= 16) { break; }
  3662. } else {
  3663. rest = 0;
  3664. }
  3665. }
  3666. var duration = elapsed * frame * 1000;
  3667. cache.springs[string] = duration;
  3668. return duration;
  3669. }
  3670. return duration ? solver : getDuration;
  3671. }
  3672. // Elastic easing adapted from jQueryUI http://api.jqueryui.com/easings/
  3673. function elastic(amplitude, period) {
  3674. if ( amplitude === void 0 ) amplitude = 1;
  3675. if ( period === void 0 ) period = .5;
  3676. var a = minMax(amplitude, 1, 10);
  3677. var p = minMax(period, .1, 2);
  3678. return function (t) {
  3679. return (t === 0 || t === 1) ? t :
  3680. -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);
  3681. }
  3682. }
  3683. // Basic steps easing implementation https://developer.mozilla.org/fr/docs/Web/CSS/transition-timing-function
  3684. function steps(steps) {
  3685. if ( steps === void 0 ) steps = 10;
  3686. return function (t) { return Math.round(t * steps) * (1 / steps); };
  3687. }
  3688. // BezierEasing https://github.com/gre/bezier-easing
  3689. var bezier = (function () {
  3690. var kSplineTableSize = 11;
  3691. var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  3692. function A(aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1 }
  3693. function B(aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1 }
  3694. function C(aA1) { return 3.0 * aA1 }
  3695. function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT }
  3696. function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1) }
  3697. function binarySubdivide(aX, aA, aB, mX1, mX2) {
  3698. var currentX, currentT, i = 0;
  3699. do {
  3700. currentT = aA + (aB - aA) / 2.0;
  3701. currentX = calcBezier(currentT, mX1, mX2) - aX;
  3702. if (currentX > 0.0) { aB = currentT; } else { aA = currentT; }
  3703. } while (Math.abs(currentX) > 0.0000001 && ++i < 10);
  3704. return currentT;
  3705. }
  3706. function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  3707. for (var i = 0; i < 4; ++i) {
  3708. var currentSlope = getSlope(aGuessT, mX1, mX2);
  3709. if (currentSlope === 0.0) { return aGuessT; }
  3710. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  3711. aGuessT -= currentX / currentSlope;
  3712. }
  3713. return aGuessT;
  3714. }
  3715. function bezier(mX1, mY1, mX2, mY2) {
  3716. if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) { return; }
  3717. var sampleValues = new Float32Array(kSplineTableSize);
  3718. if (mX1 !== mY1 || mX2 !== mY2) {
  3719. for (var i = 0; i < kSplineTableSize; ++i) {
  3720. sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
  3721. }
  3722. }
  3723. function getTForX(aX) {
  3724. var intervalStart = 0;
  3725. var currentSample = 1;
  3726. var lastSample = kSplineTableSize - 1;
  3727. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
  3728. intervalStart += kSampleStepSize;
  3729. }
  3730. --currentSample;
  3731. var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  3732. var guessForT = intervalStart + dist * kSampleStepSize;
  3733. var initialSlope = getSlope(guessForT, mX1, mX2);
  3734. if (initialSlope >= 0.001) {
  3735. return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
  3736. } else if (initialSlope === 0.0) {
  3737. return guessForT;
  3738. } else {
  3739. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
  3740. }
  3741. }
  3742. return function (x) {
  3743. if (mX1 === mY1 && mX2 === mY2) { return x; }
  3744. if (x === 0 || x === 1) { return x; }
  3745. return calcBezier(getTForX(x), mY1, mY2);
  3746. }
  3747. }
  3748. return bezier;
  3749. })();
  3750. var penner = (function () {
  3751. var names = ['Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Expo', 'Circ', 'Back', 'Elastic'];
  3752. // Approximated Penner equations http://matthewlein.com/ceaser/
  3753. var curves = {
  3754. In: [
  3755. [0.550, 0.085, 0.680, 0.530], /* inQuad */
  3756. [0.550, 0.055, 0.675, 0.190], /* inCubic */
  3757. [0.895, 0.030, 0.685, 0.220], /* inQuart */
  3758. [0.755, 0.050, 0.855, 0.060], /* inQuint */
  3759. [0.470, 0.000, 0.745, 0.715], /* inSine */
  3760. [0.950, 0.050, 0.795, 0.035], /* inExpo */
  3761. [0.600, 0.040, 0.980, 0.335], /* inCirc */
  3762. [0.600,-0.280, 0.735, 0.045], /* inBack */
  3763. elastic /* inElastic */
  3764. ],
  3765. Out: [
  3766. [0.250, 0.460, 0.450, 0.940], /* outQuad */
  3767. [0.215, 0.610, 0.355, 1.000], /* outCubic */
  3768. [0.165, 0.840, 0.440, 1.000], /* outQuart */
  3769. [0.230, 1.000, 0.320, 1.000], /* outQuint */
  3770. [0.390, 0.575, 0.565, 1.000], /* outSine */
  3771. [0.190, 1.000, 0.220, 1.000], /* outExpo */
  3772. [0.075, 0.820, 0.165, 1.000], /* outCirc */
  3773. [0.175, 0.885, 0.320, 1.275], /* outBack */
  3774. function (a, p) { return function (t) { return 1 - elastic(a, p)(1 - t); }; } /* outElastic */
  3775. ],
  3776. InOut: [
  3777. [0.455, 0.030, 0.515, 0.955], /* inOutQuad */
  3778. [0.645, 0.045, 0.355, 1.000], /* inOutCubic */
  3779. [0.770, 0.000, 0.175, 1.000], /* inOutQuart */
  3780. [0.860, 0.000, 0.070, 1.000], /* inOutQuint */
  3781. [0.445, 0.050, 0.550, 0.950], /* inOutSine */
  3782. [1.000, 0.000, 0.000, 1.000], /* inOutExpo */
  3783. [0.785, 0.135, 0.150, 0.860], /* inOutCirc */
  3784. [0.680,-0.550, 0.265, 1.550], /* inOutBack */
  3785. function (a, p) { return function (t) { return t < .5 ? elastic(a, p)(t * 2) / 2 : 1 - elastic(a, p)(t * -2 + 2) / 2; }; } /* inOutElastic */
  3786. ]
  3787. };
  3788. var eases = {
  3789. linear: [0.250, 0.250, 0.750, 0.750]
  3790. };
  3791. for (var coords in curves) {
  3792. for (var i = 0, len = curves[coords].length; i < len; i++) {
  3793. eases['ease'+coords+names[i]] = curves[coords][i];
  3794. }
  3795. }
  3796. return eases;
  3797. })();
  3798. function parseEasings(easing, duration) {
  3799. if (is.fnc(easing)) { return easing; }
  3800. var name = easing.split('(')[0];
  3801. var ease = penner[name];
  3802. var args = parseEasingParameters(easing);
  3803. switch (name) {
  3804. case 'spring' : return spring(easing, duration);
  3805. case 'cubicBezier' : return applyArguments(bezier, args);
  3806. case 'steps' : return applyArguments(steps, args);
  3807. default : return is.fnc(ease) ? applyArguments(ease, args) : applyArguments(bezier, ease);
  3808. }
  3809. }
  3810. // Strings
  3811. function selectString(str) {
  3812. try {
  3813. var nodes = document.querySelectorAll(str);
  3814. return nodes;
  3815. } catch(e) {
  3816. return;
  3817. }
  3818. }
  3819. // Arrays
  3820. var auxArrayFilter = [];
  3821. function filterArray(arr, callback) {
  3822. var result = auxArrayFilter;
  3823. var len = arr.length;
  3824. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  3825. for (var i = 0; i < len; i++) {
  3826. if (i in arr) {
  3827. var val = arr[i];
  3828. if (callback.call(thisArg, val, i, arr)) {
  3829. result.push(val);
  3830. }
  3831. }
  3832. }
  3833. // arr turns into the auxArray and we return the previously aux array.
  3834. auxArrayFilter = arr;
  3835. auxArrayFilter.length = 0;
  3836. return result;
  3837. }
  3838. var auxArrayFlatten = [];
  3839. function flattenArray(arr) {
  3840. if (!arr.length) { return arr; }
  3841. var result = auxArrayFlatten;
  3842. var node = arr.pop();
  3843. do {
  3844. if (node.constructor === Array) {
  3845. for (var i = 0; i < node.length; i++) {
  3846. arr.push(node[i]);
  3847. }
  3848. } else {
  3849. result.push(node);
  3850. }
  3851. } while (arr.length && (node = arr.pop()) !== undefined);
  3852. result.reverse(); // Reverse result to restore the original order.
  3853. // arr turns into the auxArray and we return the previously aux array.
  3854. auxArrayFlatten = arr;
  3855. auxArrayFilter.length = 0;
  3856. return result;
  3857. }
  3858. function toArray(o) {
  3859. if (is.arr(o)) { return o; }
  3860. if (is.str(o)) { o = selectString(o) || o; }
  3861. if (o instanceof NodeList || o instanceof HTMLCollection) { return [].slice.call(o); }
  3862. return [o];
  3863. }
  3864. function arrayContains(arr, val) {
  3865. return arr.some(function (a) { return a === val; });
  3866. }
  3867. // Objects
  3868. function cloneObject(o) {
  3869. var clone = {};
  3870. for (var p in o) { clone[p] = o[p]; }
  3871. return clone;
  3872. }
  3873. function replaceObjectProps(o1, o2) {
  3874. var o = cloneObject(o1);
  3875. for (var p in o1) { o[p] = o2.hasOwnProperty(p) ? o2[p] : o1[p]; }
  3876. return o;
  3877. }
  3878. function mergeObjects(o1, o2) {
  3879. var o = cloneObject(o1);
  3880. for (var p in o2) { o[p] = is.und(o1[p]) ? o2[p] : o1[p]; }
  3881. return o;
  3882. }
  3883. // Colors
  3884. var rgbRegex = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g;
  3885. function rgbToRgba(rgbValue) {
  3886. var rgb = rgbRegex.exec(rgbValue);
  3887. return rgb ? ("rgba(" + (rgb[1]) + ",1)") : rgbValue;
  3888. }
  3889. var hexToRgbaHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  3890. var hexToRgbaRgbRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  3891. function hexToRgba(hexValue) {
  3892. var hex = hexValue.replace(hexToRgbaHexRegex, function (m, r, g, b) { return r + r + g + g + b + b; } );
  3893. var rgb = hexToRgbaRgbRegex.exec(hex);
  3894. var r = parseInt(rgb[1], 16);
  3895. var g = parseInt(rgb[2], 16);
  3896. var b = parseInt(rgb[3], 16);
  3897. return ("rgba(" + r + "," + g + "," + b + ",1)");
  3898. }
  3899. var hslToRgbaHsl1Regex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g;
  3900. var hslToRgbaHsl2Regex = /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g;
  3901. function hslToRgba(hslValue) {
  3902. var hsl = hslToRgbaHsl1Regex.exec(hslValue) || hslToRgbaHsl2Regex.exec(hslValue);
  3903. var h = parseInt(hsl[1], 10) / 360;
  3904. var s = parseInt(hsl[2], 10) / 100;
  3905. var l = parseInt(hsl[3], 10) / 100;
  3906. var a = hsl[4] || 1;
  3907. function hue2rgb(p, q, t) {
  3908. if (t < 0) { t += 1; }
  3909. if (t > 1) { t -= 1; }
  3910. if (t < 1/6) { return p + (q - p) * 6 * t; }
  3911. if (t < 1/2) { return q; }
  3912. if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
  3913. return p;
  3914. }
  3915. var r, g, b;
  3916. if (s == 0) {
  3917. r = g = b = l;
  3918. } else {
  3919. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  3920. var p = 2 * l - q;
  3921. r = hue2rgb(p, q, h + 1/3);
  3922. g = hue2rgb(p, q, h);
  3923. b = hue2rgb(p, q, h - 1/3);
  3924. }
  3925. return ("rgba(" + (r * 255) + "," + (g * 255) + "," + (b * 255) + "," + a + ")");
  3926. }
  3927. function colorToRgb(val) {
  3928. if (is.rgb(val)) { return rgbToRgba(val); }
  3929. if (is.hex(val)) { return hexToRgba(val); }
  3930. if (is.hsl(val)) { return hslToRgba(val); }
  3931. }
  3932. // Units
  3933. var unitRegex = /([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/;
  3934. function getUnit(val) {
  3935. var split = unitRegex.exec(val);
  3936. if (split) { return split[2]; }
  3937. }
  3938. function getTransformUnit(propName) {
  3939. if (stringContains(propName, 'translate') || propName === 'perspective') { return 'px'; }
  3940. if (stringContains(propName, 'rotate') || stringContains(propName, 'skew')) { return 'deg'; }
  3941. }
  3942. // Values
  3943. function getFunctionValue(val, animatable) {
  3944. if (!is.fnc(val)) { return val; }
  3945. return val(animatable.target, animatable.id, animatable.total);
  3946. }
  3947. function getAttribute(el, prop) {
  3948. return el.getAttribute(prop);
  3949. }
  3950. function convertPxToUnit(el, value, unit) {
  3951. var valueUnit = getUnit(value);
  3952. if (arrayContains([unit, 'deg', 'rad', 'turn'], valueUnit)) { return value; }
  3953. var cached = cache.CSS[value + unit];
  3954. if (!is.und(cached)) { return cached; }
  3955. var baseline = 100;
  3956. var tempEl = document.createElement(el.tagName);
  3957. var parentEl = (el.parentNode && (el.parentNode !== document)) ? el.parentNode : document.body;
  3958. parentEl.appendChild(tempEl);
  3959. tempEl.style.position = 'absolute';
  3960. tempEl.style.width = baseline + unit;
  3961. var factor = baseline / tempEl.offsetWidth;
  3962. parentEl.removeChild(tempEl);
  3963. var convertedUnit = factor * parseFloat(value);
  3964. cache.CSS[value + unit] = convertedUnit;
  3965. return convertedUnit;
  3966. }
  3967. function getCSSValue(el, prop, unit) {
  3968. if (prop in el.style) {
  3969. var uppercasePropName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  3970. var value = el.style[prop] || getComputedStyle(el).getPropertyValue(uppercasePropName) || '0';
  3971. return unit ? convertPxToUnit(el, value, unit) : value;
  3972. }
  3973. }
  3974. function getAnimationType(el, prop) {
  3975. if (is.dom(el) && !is.inp(el) && (getAttribute(el, prop) || (is.svg(el) && el[prop]))) { return 'attribute'; }
  3976. if (is.dom(el) && arrayContains(validTransforms, prop)) { return 'transform'; }
  3977. if (is.dom(el) && (prop !== 'transform' && getCSSValue(el, prop))) { return 'css'; }
  3978. if (el[prop] != null) { return 'object'; }
  3979. }
  3980. var transformRegex = /(\w+)\(([^)]*)\)/g;
  3981. function getElementTransforms(el) {
  3982. if (!is.dom(el)) { return; }
  3983. var str = el.style.transform || '';
  3984. var transforms = new Map();
  3985. var m; while (m = transformRegex.exec(str)) { transforms.set(m[1], m[2]); }
  3986. return transforms;
  3987. }
  3988. function getTransformValue(el, propName, animatable, unit) {
  3989. var defaultVal = stringContains(propName, 'scale') ? 1 : 0 + getTransformUnit(propName);
  3990. var value = getElementTransforms(el).get(propName) || defaultVal;
  3991. if (animatable) {
  3992. animatable.transforms.list.set(propName, value);
  3993. animatable.transforms['last'] = propName;
  3994. }
  3995. return unit ? convertPxToUnit(el, value, unit) : value;
  3996. }
  3997. function getOriginalTargetValue(target, propName, unit, animatable) {
  3998. switch (getAnimationType(target, propName)) {
  3999. case 'transform': return getTransformValue(target, propName, animatable, unit);
  4000. case 'css': return getCSSValue(target, propName, unit);
  4001. case 'attribute': return getAttribute(target, propName);
  4002. default: return target[propName] || 0;
  4003. }
  4004. }
  4005. var operatorRegex = /^(\*=|\+=|-=)/;
  4006. function getRelativeValue(to, from) {
  4007. var operator = operatorRegex.exec(to);
  4008. if (!operator) { return to; }
  4009. var u = getUnit(to) || 0;
  4010. var x = parseFloat(from);
  4011. var y = parseFloat(to.replace(operator[0], ''));
  4012. switch (operator[0][0]) {
  4013. case '+': return x + y + u;
  4014. case '-': return x - y + u;
  4015. case '*': return x * y + u;
  4016. }
  4017. }
  4018. var whitespaceRegex = /\s/g;
  4019. function validateValue(val, unit) {
  4020. if (is.col(val)) { return colorToRgb(val); }
  4021. var originalUnit = getUnit(val);
  4022. var unitLess = originalUnit ? val.substr(0, val.length - originalUnit.length) : val;
  4023. return unit && !whitespaceRegex.test(val) ? unitLess + unit : unitLess;
  4024. }
  4025. // getTotalLength() equivalent for circle, rect, polyline, polygon and line shapes
  4026. // adapted from https://gist.github.com/SebLambla/3e0550c496c236709744
  4027. function getDistance(p1, p2) {
  4028. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  4029. }
  4030. function getCircleLength(el) {
  4031. return Math.PI * 2 * getAttribute(el, 'r');
  4032. }
  4033. function getRectLength(el) {
  4034. return (getAttribute(el, 'width') * 2) + (getAttribute(el, 'height') * 2);
  4035. }
  4036. function getLineLength(el) {
  4037. return getDistance(
  4038. {x: getAttribute(el, 'x1'), y: getAttribute(el, 'y1')},
  4039. {x: getAttribute(el, 'x2'), y: getAttribute(el, 'y2')}
  4040. );
  4041. }
  4042. function getPolylineLength(el) {
  4043. var points = el.points;
  4044. var totalLength = 0;
  4045. var previousPos;
  4046. for (var i = 0 ; i < points.numberOfItems; i++) {
  4047. var currentPos = points.getItem(i);
  4048. if (i > 0) { totalLength += getDistance(previousPos, currentPos); }
  4049. previousPos = currentPos;
  4050. }
  4051. return totalLength;
  4052. }
  4053. function getPolygonLength(el) {
  4054. var points = el.points;
  4055. return getPolylineLength(el) + getDistance(points.getItem(points.numberOfItems - 1), points.getItem(0));
  4056. }
  4057. // Path animation
  4058. function getTotalLength(el) {
  4059. if (el.getTotalLength) { return el.getTotalLength(); }
  4060. switch(el.tagName.toLowerCase()) {
  4061. case 'circle': return getCircleLength(el);
  4062. case 'rect': return getRectLength(el);
  4063. case 'line': return getLineLength(el);
  4064. case 'polyline': return getPolylineLength(el);
  4065. case 'polygon': return getPolygonLength(el);
  4066. }
  4067. }
  4068. function setDashoffset(el) {
  4069. var pathLength = getTotalLength(el);
  4070. el.setAttribute('stroke-dasharray', pathLength);
  4071. return pathLength;
  4072. }
  4073. // Motion path
  4074. function getParentSvgEl(el) {
  4075. var parentEl = el.parentNode;
  4076. while (is.svg(parentEl)) {
  4077. parentEl = parentEl.parentNode;
  4078. if (!is.svg(parentEl.parentNode)) { break; }
  4079. }
  4080. return parentEl;
  4081. }
  4082. function getParentSvg(pathEl, svgData) {
  4083. var svg = svgData || {};
  4084. var parentSvgEl = svg.el || getParentSvgEl(pathEl);
  4085. var rect = parentSvgEl.getBoundingClientRect();
  4086. var viewBoxAttr = getAttribute(parentSvgEl, 'viewBox');
  4087. var width = rect.width;
  4088. var height = rect.height;
  4089. var viewBox = svg.viewBox || (viewBoxAttr ? viewBoxAttr.split(' ') : [0, 0, width, height]);
  4090. return {
  4091. el: parentSvgEl,
  4092. viewBox: viewBox,
  4093. x: viewBox[0] / 1,
  4094. y: viewBox[1] / 1,
  4095. w: width / viewBox[2],
  4096. h: height / viewBox[3]
  4097. }
  4098. }
  4099. function getPath(path, percent) {
  4100. var pathEl = is.str(path) ? selectString(path)[0] : path;
  4101. var p = percent || 100;
  4102. return function(property) {
  4103. return {
  4104. property: property,
  4105. el: pathEl,
  4106. svg: getParentSvg(pathEl),
  4107. totalLength: getTotalLength(pathEl) * (p / 100)
  4108. }
  4109. }
  4110. }
  4111. function getPathProgress(path, progress) {
  4112. function point(offset) {
  4113. if ( offset === void 0 ) offset = 0;
  4114. var l = progress + offset >= 1 ? progress + offset : 0;
  4115. return path.el.getPointAtLength(l);
  4116. }
  4117. var svg = getParentSvg(path.el, path.svg);
  4118. var p = point();
  4119. var p0 = point(-1);
  4120. var p1 = point(+1);
  4121. switch (path.property) {
  4122. case 'x': return (p.x - svg.x) * svg.w;
  4123. case 'y': return (p.y - svg.y) * svg.h;
  4124. case 'angle': return Math.atan2(p1.y - p0.y, p1.x - p0.x) * 180 / Math.PI;
  4125. }
  4126. }
  4127. // Decompose value
  4128. var valueRegex = /-?\d*\.?\d+/g;
  4129. function decomposeValue(val, unit) {
  4130. var value = validateValue((is.pth(val) ? val.totalLength : val), unit) + '';
  4131. return {
  4132. original: value,
  4133. numbers: value.match(valueRegex) ? value.match(valueRegex).map(Number) : [0],
  4134. strings: (is.str(val) || unit) ? value.split(valueRegex) : []
  4135. }
  4136. }
  4137. // Animatables
  4138. function parseTargets(targets) {
  4139. var targetsArray = targets ? (flattenArray(is.arr(targets) ? targets.map(toArray) : toArray(targets))) : [];
  4140. return filterArray(targetsArray, function (item, pos, self) { return self.indexOf(item) === pos; });
  4141. }
  4142. function getAnimatables(targets) {
  4143. var parsed = parseTargets(targets);
  4144. return parsed.map(function (t, i) {
  4145. return {target: t, id: i, total: parsed.length, transforms: { list: getElementTransforms(t) } };
  4146. });
  4147. }
  4148. // Properties
  4149. var springRegex = /^spring/;
  4150. function normalizePropertyTweens(prop, tweenSettings) {
  4151. var settings = cloneObject(tweenSettings);
  4152. // Override duration if easing is a spring
  4153. if (springRegex.test(settings.easing)) { settings.duration = spring(settings.easing); }
  4154. if (is.arr(prop)) {
  4155. var l = prop.length;
  4156. var isFromTo = (l === 2 && !is.obj(prop[0]));
  4157. if (!isFromTo) {
  4158. // Duration divided by the number of tweens
  4159. if (!is.fnc(tweenSettings.duration)) { settings.duration = tweenSettings.duration / l; }
  4160. } else {
  4161. // Transform [from, to] values shorthand to a valid tween value
  4162. prop = {value: prop};
  4163. }
  4164. }
  4165. var propArray = is.arr(prop) ? prop : [prop];
  4166. return propArray.map(function (v, i) {
  4167. var obj = (is.obj(v) && !is.pth(v)) ? v : {value: v};
  4168. // Default delay value should only be applied to the first tween
  4169. if (is.und(obj.delay)) { obj.delay = !i ? tweenSettings.delay : 0; }
  4170. // Default endDelay value should only be applied to the last tween
  4171. if (is.und(obj.endDelay)) { obj.endDelay = i === propArray.length - 1 ? tweenSettings.endDelay : 0; }
  4172. return obj;
  4173. }).map(function (k) { return mergeObjects(k, settings); });
  4174. }
  4175. function flattenKeyframes(keyframes) {
  4176. var propertyNames = filterArray(flattenArray(keyframes.map(function (key) { return Object.keys(key); })), function (p) { return is.key(p); })
  4177. .reduce(function (a,b) { if (a.indexOf(b) < 0) { a.push(b); } return a; }, []);
  4178. var properties = {};
  4179. var loop = function ( i ) {
  4180. var propName = propertyNames[i];
  4181. properties[propName] = keyframes.map(function (key) {
  4182. var newKey = {};
  4183. for (var p in key) {
  4184. if (is.key(p)) {
  4185. if (p == propName) { newKey.value = key[p]; }
  4186. } else {
  4187. newKey[p] = key[p];
  4188. }
  4189. }
  4190. return newKey;
  4191. });
  4192. };
  4193. for (var i = 0; i < propertyNames.length; i++) loop( i );
  4194. return properties;
  4195. }
  4196. function getProperties(tweenSettings, params) {
  4197. var properties = [];
  4198. var keyframes = params.keyframes;
  4199. if (keyframes) { params = mergeObjects(flattenKeyframes(keyframes), params); }
  4200. for (var p in params) {
  4201. if (is.key(p)) {
  4202. properties.push({
  4203. name: p,
  4204. tweens: normalizePropertyTweens(params[p], tweenSettings)
  4205. });
  4206. }
  4207. }
  4208. return properties;
  4209. }
  4210. // Tweens
  4211. function normalizeTweenValues(tween, animatable) {
  4212. var t = {};
  4213. for (var p in tween) {
  4214. var value = getFunctionValue(tween[p], animatable);
  4215. if (is.arr(value)) {
  4216. value = value.map(function (v) { return getFunctionValue(v, animatable); });
  4217. if (value.length === 1) { value = value[0]; }
  4218. }
  4219. t[p] = value;
  4220. }
  4221. t.duration = parseFloat(t.duration);
  4222. t.delay = parseFloat(t.delay);
  4223. return t;
  4224. }
  4225. function normalizeTweens(prop, animatable) {
  4226. var previousTween;
  4227. return prop.tweens.map(function (t) {
  4228. var tween = normalizeTweenValues(t, animatable);
  4229. var tweenValue = tween.value;
  4230. var to = is.arr(tweenValue) ? tweenValue[1] : tweenValue;
  4231. var toUnit = getUnit(to);
  4232. var originalValue = getOriginalTargetValue(animatable.target, prop.name, toUnit, animatable);
  4233. var previousValue = previousTween ? previousTween.to.original : originalValue;
  4234. var from = is.arr(tweenValue) ? tweenValue[0] : previousValue;
  4235. var fromUnit = getUnit(from) || getUnit(originalValue);
  4236. var unit = toUnit || fromUnit;
  4237. if (is.und(to)) { to = previousValue; }
  4238. tween.from = decomposeValue(from, unit);
  4239. tween.to = decomposeValue(getRelativeValue(to, from), unit);
  4240. tween.start = previousTween ? previousTween.end : 0;
  4241. tween.end = tween.start + tween.delay + tween.duration + tween.endDelay;
  4242. tween.easing = parseEasings(tween.easing, tween.duration);
  4243. tween.isPath = is.pth(tweenValue);
  4244. tween.isColor = is.col(tween.from.original);
  4245. if (tween.isColor) { tween.round = 1; }
  4246. previousTween = tween;
  4247. return tween;
  4248. });
  4249. }
  4250. // Tween progress
  4251. var setProgressValue = {
  4252. css: function (t, p, v) { return t.style[p] = v; },
  4253. attribute: function (t, p, v) { return t.setAttribute(p, v); },
  4254. object: function (t, p, v) { return t[p] = v; },
  4255. transform: function (t, p, v, transforms, manual) {
  4256. transforms.list.set(p, v);
  4257. if (p === transforms.last || manual) {
  4258. var str = '';
  4259. transforms.list.forEach(function (value, prop) { str += prop + "(" + value + ") "; });
  4260. t.style.transform = str;
  4261. }
  4262. }
  4263. };
  4264. // Set Value helper
  4265. function setTargetsValue(targets, properties) {
  4266. var animatables = getAnimatables(targets);
  4267. for (var i = 0, len = animatables.length; i < len; i++) {
  4268. var animatable = animatables[i];
  4269. for (var property in properties) {
  4270. var value = getFunctionValue(properties[property], animatable);
  4271. var target = animatable.target;
  4272. var valueUnit = getUnit(value);
  4273. var originalValue = getOriginalTargetValue(target, property, valueUnit, animatable);
  4274. var unit = valueUnit || getUnit(originalValue);
  4275. var to = getRelativeValue(validateValue(value, unit), originalValue);
  4276. var animType = getAnimationType(target, property);
  4277. setProgressValue[animType](target, property, to, animatable.transforms, true);
  4278. }
  4279. }
  4280. }
  4281. // Animations
  4282. function createAnimation(animatable, prop) {
  4283. var animType = getAnimationType(animatable.target, prop.name);
  4284. if (animType) {
  4285. var tweens = normalizeTweens(prop, animatable);
  4286. var lastTween = tweens[tweens.length - 1];
  4287. return {
  4288. type: animType,
  4289. property: prop.name,
  4290. animatable: animatable,
  4291. tweens: tweens,
  4292. duration: lastTween.end,
  4293. delay: tweens[0].delay,
  4294. endDelay: lastTween.endDelay
  4295. }
  4296. }
  4297. }
  4298. function getAnimations(animatables, properties) {
  4299. return filterArray(flattenArray(animatables.map(function (animatable) {
  4300. return properties.map(function (prop) {
  4301. return createAnimation(animatable, prop);
  4302. });
  4303. })), function (a) { return !is.und(a); });
  4304. }
  4305. // Create Instance
  4306. function getInstanceTimings(animations, tweenSettings) {
  4307. var animLength = animations.length;
  4308. var getTlOffset = function (anim) { return anim.timelineOffset ? anim.timelineOffset : 0; };
  4309. var timings = {};
  4310. timings.duration = animLength ? Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration; })) : tweenSettings.duration;
  4311. timings.delay = animLength ? Math.min.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.delay; })) : tweenSettings.delay;
  4312. timings.endDelay = animLength ? timings.duration - Math.max.apply(Math, animations.map(function (anim) { return getTlOffset(anim) + anim.duration - anim.endDelay; })) : tweenSettings.endDelay;
  4313. return timings;
  4314. }
  4315. var instanceID = 0;
  4316. function createNewInstance(params) {
  4317. var instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
  4318. var tweenSettings = replaceObjectProps(defaultTweenSettings, params);
  4319. var properties = getProperties(tweenSettings, params);
  4320. var animatables = getAnimatables(params.targets);
  4321. var animations = getAnimations(animatables, properties);
  4322. var timings = getInstanceTimings(animations, tweenSettings);
  4323. var id = instanceID;
  4324. instanceID++;
  4325. return mergeObjects(instanceSettings, {
  4326. id: id,
  4327. children: [],
  4328. animatables: animatables,
  4329. animations: animations,
  4330. duration: timings.duration,
  4331. delay: timings.delay,
  4332. endDelay: timings.endDelay
  4333. });
  4334. }
  4335. // Core
  4336. var activeInstances = [];
  4337. var pausedInstances = [];
  4338. var raf;
  4339. var engine = (function () {
  4340. function play() {
  4341. raf = requestAnimationFrame(step);
  4342. }
  4343. function step(t) {
  4344. var activeInstancesLength = activeInstances.length;
  4345. if (activeInstancesLength) {
  4346. var i = 0;
  4347. while (i < activeInstancesLength) {
  4348. var activeInstance = activeInstances[i];
  4349. if (!activeInstance.paused) {
  4350. activeInstance.tick(t);
  4351. } else {
  4352. var instanceIndex = activeInstances.indexOf(activeInstance);
  4353. if (instanceIndex > -1) {
  4354. activeInstances.splice(instanceIndex, 1);
  4355. activeInstancesLength = activeInstances.length;
  4356. }
  4357. }
  4358. i++;
  4359. }
  4360. play();
  4361. } else {
  4362. raf = cancelAnimationFrame(raf);
  4363. }
  4364. }
  4365. return play;
  4366. })();
  4367. function handleVisibilityChange() {
  4368. if (document.hidden) {
  4369. for (var i = 0, len = activeInstances.length; i < len; i++) {
  4370. activeInstance[i].pause();
  4371. }
  4372. pausedInstances = activeInstances.slice(0);
  4373. activeInstances = [];
  4374. } else {
  4375. for (var i$1 = 0, len$1 = pausedInstances.length; i$1 < len$1; i$1++) {
  4376. pausedInstances[i$1].play();
  4377. }
  4378. }
  4379. }
  4380. document.addEventListener('visibilitychange', handleVisibilityChange);
  4381. // Public Instance
  4382. function anime(params) {
  4383. if ( params === void 0 ) params = {};
  4384. var startTime = 0, lastTime = 0, now = 0;
  4385. var children, childrenLength = 0;
  4386. var resolve = null;
  4387. function makePromise() {
  4388. return window.Promise && new Promise(function (_resolve) { return resolve = _resolve; });
  4389. }
  4390. var promise = makePromise();
  4391. var instance = createNewInstance(params);
  4392. function toggleInstanceDirection() {
  4393. instance.reversed = !instance.reversed;
  4394. for (var i = 0, len = children.length; i < len; i++) {
  4395. children[i].reversed = instance.reversed;
  4396. }
  4397. }
  4398. function adjustTime(time) {
  4399. return instance.reversed ? instance.duration - time : time;
  4400. }
  4401. function resetTime() {
  4402. startTime = 0;
  4403. lastTime = adjustTime(instance.currentTime) * (1 / anime.speed);
  4404. }
  4405. function seekCild(time, child) {
  4406. if (child) { child.seek(time - child.timelineOffset); }
  4407. }
  4408. function syncInstanceChildren(time) {
  4409. if (!instance.reversePlayback) {
  4410. for (var i = 0; i < childrenLength; i++) { seekCild(time, children[i]); }
  4411. } else {
  4412. for (var i$1 = childrenLength; i$1--;) { seekCild(time, children[i$1]); }
  4413. }
  4414. }
  4415. function setAnimationsProgress(insTime) {
  4416. var i = 0;
  4417. var animations = instance.animations;
  4418. var animationsLength = animations.length;
  4419. while (i < animationsLength) {
  4420. var anim = animations[i];
  4421. var animatable = anim.animatable;
  4422. var tweens = anim.tweens;
  4423. var tweenLength = tweens.length - 1;
  4424. var tween = tweens[tweenLength];
  4425. // Only check for keyframes if there is more than one tween
  4426. if (tweenLength) { tween = filterArray(tweens, function (t) { return (insTime < t.end); })[0] || tween; }
  4427. var elapsed = minMax(insTime - tween.start - tween.delay, 0, tween.duration) / tween.duration;
  4428. var eased = isNaN(elapsed) ? 1 : tween.easing(elapsed);
  4429. var strings = tween.to.strings;
  4430. var round = tween.round;
  4431. var numbers = [];
  4432. var toNumbersLength = tween.to.numbers.length;
  4433. var progress = (void 0);
  4434. for (var n = 0; n < toNumbersLength; n++) {
  4435. var value = (void 0);
  4436. var toNumber = tween.to.numbers[n];
  4437. var fromNumber = tween.from.numbers[n] || 0;
  4438. if (!tween.isPath) {
  4439. value = fromNumber + (eased * (toNumber - fromNumber));
  4440. } else {
  4441. value = getPathProgress(tween.value, eased * toNumber);
  4442. }
  4443. if (round) {
  4444. if (!(tween.isColor && n > 2)) {
  4445. value = Math.round(value * round) / round;
  4446. }
  4447. }
  4448. numbers.push(value);
  4449. }
  4450. // Manual Array.reduce for better performances
  4451. var stringsLength = strings.length;
  4452. if (!stringsLength) {
  4453. progress = numbers[0];
  4454. } else {
  4455. progress = strings[0];
  4456. for (var s = 0; s < stringsLength; s++) {
  4457. var a = strings[s];
  4458. var b = strings[s + 1];
  4459. var n$1 = numbers[s];
  4460. if (!isNaN(n$1)) {
  4461. if (!b) {
  4462. progress += n$1 + ' ';
  4463. } else {
  4464. progress += n$1 + b;
  4465. }
  4466. }
  4467. }
  4468. }
  4469. setProgressValue[anim.type](animatable.target, anim.property, progress, animatable.transforms);
  4470. anim.currentValue = progress;
  4471. i++;
  4472. }
  4473. }
  4474. function setCallback(cb) {
  4475. if (instance[cb] && !instance.passThrough) { instance[cb](instance); }
  4476. }
  4477. function countIteration() {
  4478. if (instance.remaining && instance.remaining !== true) {
  4479. instance.remaining--;
  4480. }
  4481. }
  4482. function setInstanceProgress(engineTime) {
  4483. var insDuration = instance.duration;
  4484. var insDelay = instance.delay;
  4485. var insEndDelay = insDuration - instance.endDelay;
  4486. var insTime = adjustTime(engineTime);
  4487. instance.progress = minMax((insTime / insDuration) * 100, 0, 100);
  4488. instance.reversePlayback = insTime < instance.currentTime;
  4489. if (children) { syncInstanceChildren(insTime); }
  4490. if (!instance.began && instance.currentTime > 0) {
  4491. instance.began = true;
  4492. setCallback('begin');
  4493. setCallback('loopBegin');
  4494. }
  4495. if (insTime <= insDelay && instance.currentTime !== 0) {
  4496. setAnimationsProgress(0);
  4497. }
  4498. if ((insTime >= insEndDelay && instance.currentTime !== insDuration) || !insDuration) {
  4499. setAnimationsProgress(insDuration);
  4500. }
  4501. if (insTime > insDelay && insTime < insEndDelay) {
  4502. if (!instance.changeBegan) {
  4503. instance.changeBegan = true;
  4504. instance.changeCompleted = false;
  4505. setCallback('changeBegin');
  4506. }
  4507. setCallback('change');
  4508. setAnimationsProgress(insTime);
  4509. } else {
  4510. if (instance.changeBegan) {
  4511. instance.changeCompleted = true;
  4512. instance.changeBegan = false;
  4513. setCallback('changeComplete');
  4514. }
  4515. }
  4516. instance.currentTime = minMax(insTime, 0, insDuration);
  4517. if (instance.began) { setCallback('update'); }
  4518. if (engineTime >= insDuration) {
  4519. lastTime = 0;
  4520. countIteration();
  4521. if (instance.remaining) {
  4522. startTime = now;
  4523. setCallback('loopComplete');
  4524. setCallback('loopBegin');
  4525. if (instance.direction === 'alternate') { toggleInstanceDirection(); }
  4526. } else {
  4527. instance.paused = true;
  4528. if (!instance.completed) {
  4529. instance.completed = true;
  4530. setCallback('loopComplete');
  4531. setCallback('complete');
  4532. if ('Promise' in window) {
  4533. resolve();
  4534. promise = makePromise();
  4535. }
  4536. }
  4537. }
  4538. }
  4539. }
  4540. instance.reset = function() {
  4541. var direction = instance.direction;
  4542. instance.passThrough = false;
  4543. instance.currentTime = 0;
  4544. instance.progress = 0;
  4545. instance.paused = true;
  4546. instance.began = false;
  4547. instance.changeBegan = false;
  4548. instance.completed = false;
  4549. instance.changeCompleted = false;
  4550. instance.reversePlayback = false;
  4551. instance.reversed = direction === 'reverse';
  4552. instance.remaining = instance.loop;
  4553. children = instance.children;
  4554. childrenLength = children.length;
  4555. for (var i = childrenLength; i--;) { instance.children[i].reset(); }
  4556. if (instance.reversed && instance.loop !== true || (direction === 'alternate' && instance.loop === 1)) { instance.remaining++; }
  4557. setAnimationsProgress(0);
  4558. };
  4559. // Set Value helper
  4560. instance.set = function(targets, properties) {
  4561. setTargetsValue(targets, properties);
  4562. return instance;
  4563. };
  4564. instance.tick = function(t) {
  4565. now = t;
  4566. if (!startTime) { startTime = now; }
  4567. setInstanceProgress((now + (lastTime - startTime)) * anime.speed);
  4568. };
  4569. instance.seek = function(time) {
  4570. setInstanceProgress(adjustTime(time));
  4571. };
  4572. instance.pause = function() {
  4573. instance.paused = true;
  4574. resetTime();
  4575. };
  4576. instance.play = function() {
  4577. if (!instance.paused) { return; }
  4578. instance.paused = false;
  4579. activeInstances.push(instance);
  4580. resetTime();
  4581. if (!raf) { engine(); }
  4582. };
  4583. instance.reverse = function() {
  4584. toggleInstanceDirection();
  4585. resetTime();
  4586. };
  4587. instance.restart = function() {
  4588. instance.reset();
  4589. instance.play();
  4590. };
  4591. instance.finished = promise;
  4592. instance.reset();
  4593. if (instance.autoplay) { instance.play(); }
  4594. return instance;
  4595. }
  4596. // Remove targets from animation
  4597. function removeTargetsFromAnimations(targetsArray, animations) {
  4598. for (var a = animations.length; a--;) {
  4599. if (arrayContains(targetsArray, animations[a].animatable.target)) {
  4600. animations.splice(a, 1);
  4601. }
  4602. }
  4603. }
  4604. function removeTargets(targets) {
  4605. var targetsArray = parseTargets(targets);
  4606. for (var i = activeInstances.length; i--;) {
  4607. var instance = activeInstances[i];
  4608. var animations = instance.animations;
  4609. var children = instance.children;
  4610. removeTargetsFromAnimations(targetsArray, animations);
  4611. for (var c = children.length; c--;) {
  4612. var child = children[c];
  4613. var childAnimations = child.animations;
  4614. removeTargetsFromAnimations(targetsArray, childAnimations);
  4615. if (!childAnimations.length && !child.children.length) { children.splice(c, 1); }
  4616. }
  4617. if (!animations.length && !children.length) { instance.pause(); }
  4618. }
  4619. }
  4620. // Stagger helpers
  4621. function stagger(val, params) {
  4622. if ( params === void 0 ) params = {};
  4623. var direction = params.direction || 'normal';
  4624. var easing = params.easing ? parseEasings(params.easing) : null;
  4625. var grid = params.grid;
  4626. var axis = params.axis;
  4627. var fromIndex = params.from || 0;
  4628. var fromFirst = fromIndex === 'first';
  4629. var fromCenter = fromIndex === 'center';
  4630. var fromLast = fromIndex === 'last';
  4631. var isRange = is.arr(val);
  4632. var val1 = isRange ? parseFloat(val[0]) : parseFloat(val);
  4633. var val2 = isRange ? parseFloat(val[1]) : 0;
  4634. var unit = getUnit(isRange ? val[1] : val) || 0;
  4635. var start = params.start || 0 + (isRange ? val1 : 0);
  4636. var values = [];
  4637. var maxValue = 0;
  4638. return function (el, i, t) {
  4639. if (fromFirst) { fromIndex = 0; }
  4640. if (fromCenter) { fromIndex = (t - 1) / 2; }
  4641. if (fromLast) { fromIndex = t - 1; }
  4642. if (!values.length) {
  4643. for (var index = 0; index < t; index++) {
  4644. if (!grid) {
  4645. values.push(Math.abs(fromIndex - index));
  4646. } else {
  4647. var fromX = !fromCenter ? fromIndex%grid[0] : (grid[0]-1)/2;
  4648. var fromY = !fromCenter ? Math.floor(fromIndex/grid[0]) : (grid[1]-1)/2;
  4649. var toX = index%grid[0];
  4650. var toY = Math.floor(index/grid[0]);
  4651. var distanceX = fromX - toX;
  4652. var distanceY = fromY - toY;
  4653. var value = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
  4654. if (axis === 'x') { value = -distanceX; }
  4655. if (axis === 'y') { value = -distanceY; }
  4656. values.push(value);
  4657. }
  4658. maxValue = Math.max.apply(Math, values);
  4659. }
  4660. if (easing) { values = values.map(function (val) { return easing(val / maxValue) * maxValue; }); }
  4661. if (direction === 'reverse') { values = values.map(function (val) { return axis ? (val < 0) ? val * -1 : -val : Math.abs(maxValue - val); }); }
  4662. }
  4663. var spacing = isRange ? (val2 - val1) / maxValue : val1;
  4664. return start + (spacing * (Math.round(values[i] * 100) / 100)) + unit;
  4665. }
  4666. }
  4667. // Timeline
  4668. function timeline(params) {
  4669. if ( params === void 0 ) params = {};
  4670. var tl = anime(params);
  4671. tl.duration = 0;
  4672. tl.add = function(instanceParams, timelineOffset) {
  4673. var tlIndex = activeInstances.indexOf(tl);
  4674. var children = tl.children;
  4675. if (tlIndex > -1) { activeInstances.splice(tlIndex, 1); }
  4676. function passThrough(ins) { ins.passThrough = true; }
  4677. for (var i = 0; i < children.length; i++) { passThrough(children[i]); }
  4678. var insParams = mergeObjects(instanceParams, replaceObjectProps(defaultTweenSettings, params));
  4679. insParams.targets = insParams.targets || params.targets;
  4680. var tlDuration = tl.duration;
  4681. insParams.autoplay = false;
  4682. insParams.direction = tl.direction;
  4683. insParams.timelineOffset = is.und(timelineOffset) ? tlDuration : getRelativeValue(timelineOffset, tlDuration);
  4684. passThrough(tl);
  4685. tl.seek(insParams.timelineOffset);
  4686. var ins = anime(insParams);
  4687. passThrough(ins);
  4688. children.push(ins);
  4689. var timings = getInstanceTimings(children, params);
  4690. tl.delay = timings.delay;
  4691. tl.endDelay = timings.endDelay;
  4692. tl.duration = timings.duration;
  4693. tl.seek(0);
  4694. tl.reset();
  4695. if (tl.autoplay) { tl.play(); }
  4696. return tl;
  4697. };
  4698. return tl;
  4699. }
  4700. anime.version = '3.0.0';
  4701. anime.speed = 1;
  4702. anime.running = activeInstances;
  4703. anime.remove = removeTargets;
  4704. anime.get = getOriginalTargetValue;
  4705. anime.set = setTargetsValue;
  4706. anime.convertPx = convertPxToUnit;
  4707. anime.path = getPath;
  4708. anime.setDashoffset = setDashoffset;
  4709. anime.stagger = stagger;
  4710. anime.timeline = timeline;
  4711. anime.easing = parseEasings;
  4712. anime.penner = penner;
  4713. anime.random = function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; };
  4714. module.exports = anime;
  4715. },{}],36:[function(_dereq_,module,exports){
  4716. (function (global, factory) {
  4717. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4718. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4719. (global = global || self, factory(global.THREE = {}));
  4720. }(this, function (exports) { 'use strict';
  4721. // Polyfills
  4722. if ( Number.EPSILON === undefined ) {
  4723. Number.EPSILON = Math.pow( 2, - 52 );
  4724. }
  4725. if ( Number.isInteger === undefined ) {
  4726. // Missing in IE
  4727. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  4728. Number.isInteger = function ( value ) {
  4729. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  4730. };
  4731. }
  4732. //
  4733. if ( Math.sign === undefined ) {
  4734. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4735. Math.sign = function ( x ) {
  4736. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4737. };
  4738. }
  4739. if ( 'name' in Function.prototype === false ) {
  4740. // Missing in IE
  4741. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4742. Object.defineProperty( Function.prototype, 'name', {
  4743. get: function () {
  4744. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4745. }
  4746. } );
  4747. }
  4748. if ( Object.assign === undefined ) {
  4749. // Missing in IE
  4750. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4751. ( function () {
  4752. Object.assign = function ( target ) {
  4753. if ( target === undefined || target === null ) {
  4754. throw new TypeError( 'Cannot convert undefined or null to object' );
  4755. }
  4756. var output = Object( target );
  4757. for ( var index = 1; index < arguments.length; index ++ ) {
  4758. var source = arguments[ index ];
  4759. if ( source !== undefined && source !== null ) {
  4760. for ( var nextKey in source ) {
  4761. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4762. output[ nextKey ] = source[ nextKey ];
  4763. }
  4764. }
  4765. }
  4766. }
  4767. return output;
  4768. };
  4769. } )();
  4770. }
  4771. /**
  4772. * https://github.com/mrdoob/eventdispatcher.js/
  4773. */
  4774. function EventDispatcher() {}
  4775. Object.assign( EventDispatcher.prototype, {
  4776. addEventListener: function ( type, listener ) {
  4777. if ( this._listeners === undefined ) this._listeners = {};
  4778. var listeners = this._listeners;
  4779. if ( listeners[ type ] === undefined ) {
  4780. listeners[ type ] = [];
  4781. }
  4782. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4783. listeners[ type ].push( listener );
  4784. }
  4785. },
  4786. hasEventListener: function ( type, listener ) {
  4787. if ( this._listeners === undefined ) return false;
  4788. var listeners = this._listeners;
  4789. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4790. },
  4791. removeEventListener: function ( type, listener ) {
  4792. if ( this._listeners === undefined ) return;
  4793. var listeners = this._listeners;
  4794. var listenerArray = listeners[ type ];
  4795. if ( listenerArray !== undefined ) {
  4796. var index = listenerArray.indexOf( listener );
  4797. if ( index !== - 1 ) {
  4798. listenerArray.splice( index, 1 );
  4799. }
  4800. }
  4801. },
  4802. dispatchEvent: function ( event ) {
  4803. if ( this._listeners === undefined ) return;
  4804. var listeners = this._listeners;
  4805. var listenerArray = listeners[ event.type ];
  4806. if ( listenerArray !== undefined ) {
  4807. event.target = this;
  4808. var array = listenerArray.slice( 0 );
  4809. for ( var i = 0, l = array.length; i < l; i ++ ) {
  4810. array[ i ].call( this, event );
  4811. }
  4812. }
  4813. }
  4814. } );
  4815. var REVISION = '103dev';
  4816. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4817. var CullFaceNone = 0;
  4818. var CullFaceBack = 1;
  4819. var CullFaceFront = 2;
  4820. var CullFaceFrontBack = 3;
  4821. var FrontFaceDirectionCW = 0;
  4822. var FrontFaceDirectionCCW = 1;
  4823. var BasicShadowMap = 0;
  4824. var PCFShadowMap = 1;
  4825. var PCFSoftShadowMap = 2;
  4826. var FrontSide = 0;
  4827. var BackSide = 1;
  4828. var DoubleSide = 2;
  4829. var FlatShading = 1;
  4830. var SmoothShading = 2;
  4831. var NoColors = 0;
  4832. var FaceColors = 1;
  4833. var VertexColors = 2;
  4834. var NoBlending = 0;
  4835. var NormalBlending = 1;
  4836. var AdditiveBlending = 2;
  4837. var SubtractiveBlending = 3;
  4838. var MultiplyBlending = 4;
  4839. var CustomBlending = 5;
  4840. var AddEquation = 100;
  4841. var SubtractEquation = 101;
  4842. var ReverseSubtractEquation = 102;
  4843. var MinEquation = 103;
  4844. var MaxEquation = 104;
  4845. var ZeroFactor = 200;
  4846. var OneFactor = 201;
  4847. var SrcColorFactor = 202;
  4848. var OneMinusSrcColorFactor = 203;
  4849. var SrcAlphaFactor = 204;
  4850. var OneMinusSrcAlphaFactor = 205;
  4851. var DstAlphaFactor = 206;
  4852. var OneMinusDstAlphaFactor = 207;
  4853. var DstColorFactor = 208;
  4854. var OneMinusDstColorFactor = 209;
  4855. var SrcAlphaSaturateFactor = 210;
  4856. var NeverDepth = 0;
  4857. var AlwaysDepth = 1;
  4858. var LessDepth = 2;
  4859. var LessEqualDepth = 3;
  4860. var EqualDepth = 4;
  4861. var GreaterEqualDepth = 5;
  4862. var GreaterDepth = 6;
  4863. var NotEqualDepth = 7;
  4864. var MultiplyOperation = 0;
  4865. var MixOperation = 1;
  4866. var AddOperation = 2;
  4867. var NoToneMapping = 0;
  4868. var LinearToneMapping = 1;
  4869. var ReinhardToneMapping = 2;
  4870. var Uncharted2ToneMapping = 3;
  4871. var CineonToneMapping = 4;
  4872. var ACESFilmicToneMapping = 5;
  4873. var UVMapping = 300;
  4874. var CubeReflectionMapping = 301;
  4875. var CubeRefractionMapping = 302;
  4876. var EquirectangularReflectionMapping = 303;
  4877. var EquirectangularRefractionMapping = 304;
  4878. var SphericalReflectionMapping = 305;
  4879. var CubeUVReflectionMapping = 306;
  4880. var CubeUVRefractionMapping = 307;
  4881. var RepeatWrapping = 1000;
  4882. var ClampToEdgeWrapping = 1001;
  4883. var MirroredRepeatWrapping = 1002;
  4884. var NearestFilter = 1003;
  4885. var NearestMipMapNearestFilter = 1004;
  4886. var NearestMipMapLinearFilter = 1005;
  4887. var LinearFilter = 1006;
  4888. var LinearMipMapNearestFilter = 1007;
  4889. var LinearMipMapLinearFilter = 1008;
  4890. var UnsignedByteType = 1009;
  4891. var ByteType = 1010;
  4892. var ShortType = 1011;
  4893. var UnsignedShortType = 1012;
  4894. var IntType = 1013;
  4895. var UnsignedIntType = 1014;
  4896. var FloatType = 1015;
  4897. var HalfFloatType = 1016;
  4898. var UnsignedShort4444Type = 1017;
  4899. var UnsignedShort5551Type = 1018;
  4900. var UnsignedShort565Type = 1019;
  4901. var UnsignedInt248Type = 1020;
  4902. var AlphaFormat = 1021;
  4903. var RGBFormat = 1022;
  4904. var RGBAFormat = 1023;
  4905. var LuminanceFormat = 1024;
  4906. var LuminanceAlphaFormat = 1025;
  4907. var RGBEFormat = RGBAFormat;
  4908. var DepthFormat = 1026;
  4909. var DepthStencilFormat = 1027;
  4910. var RedFormat = 1028;
  4911. var RGB_S3TC_DXT1_Format = 33776;
  4912. var RGBA_S3TC_DXT1_Format = 33777;
  4913. var RGBA_S3TC_DXT3_Format = 33778;
  4914. var RGBA_S3TC_DXT5_Format = 33779;
  4915. var RGB_PVRTC_4BPPV1_Format = 35840;
  4916. var RGB_PVRTC_2BPPV1_Format = 35841;
  4917. var RGBA_PVRTC_4BPPV1_Format = 35842;
  4918. var RGBA_PVRTC_2BPPV1_Format = 35843;
  4919. var RGB_ETC1_Format = 36196;
  4920. var RGBA_ASTC_4x4_Format = 37808;
  4921. var RGBA_ASTC_5x4_Format = 37809;
  4922. var RGBA_ASTC_5x5_Format = 37810;
  4923. var RGBA_ASTC_6x5_Format = 37811;
  4924. var RGBA_ASTC_6x6_Format = 37812;
  4925. var RGBA_ASTC_8x5_Format = 37813;
  4926. var RGBA_ASTC_8x6_Format = 37814;
  4927. var RGBA_ASTC_8x8_Format = 37815;
  4928. var RGBA_ASTC_10x5_Format = 37816;
  4929. var RGBA_ASTC_10x6_Format = 37817;
  4930. var RGBA_ASTC_10x8_Format = 37818;
  4931. var RGBA_ASTC_10x10_Format = 37819;
  4932. var RGBA_ASTC_12x10_Format = 37820;
  4933. var RGBA_ASTC_12x12_Format = 37821;
  4934. var LoopOnce = 2200;
  4935. var LoopRepeat = 2201;
  4936. var LoopPingPong = 2202;
  4937. var InterpolateDiscrete = 2300;
  4938. var InterpolateLinear = 2301;
  4939. var InterpolateSmooth = 2302;
  4940. var ZeroCurvatureEnding = 2400;
  4941. var ZeroSlopeEnding = 2401;
  4942. var WrapAroundEnding = 2402;
  4943. var TrianglesDrawMode = 0;
  4944. var TriangleStripDrawMode = 1;
  4945. var TriangleFanDrawMode = 2;
  4946. var LinearEncoding = 3000;
  4947. var sRGBEncoding = 3001;
  4948. var GammaEncoding = 3007;
  4949. var RGBEEncoding = 3002;
  4950. var LogLuvEncoding = 3003;
  4951. var RGBM7Encoding = 3004;
  4952. var RGBM16Encoding = 3005;
  4953. var RGBDEncoding = 3006;
  4954. var BasicDepthPacking = 3200;
  4955. var RGBADepthPacking = 3201;
  4956. var TangentSpaceNormalMap = 0;
  4957. var ObjectSpaceNormalMap = 1;
  4958. /**
  4959. * @author alteredq / http://alteredqualia.com/
  4960. * @author mrdoob / http://mrdoob.com/
  4961. */
  4962. var _Math = {
  4963. DEG2RAD: Math.PI / 180,
  4964. RAD2DEG: 180 / Math.PI,
  4965. generateUUID: ( function () {
  4966. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  4967. var lut = [];
  4968. for ( var i = 0; i < 256; i ++ ) {
  4969. lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  4970. }
  4971. return function generateUUID() {
  4972. var d0 = Math.random() * 0xffffffff | 0;
  4973. var d1 = Math.random() * 0xffffffff | 0;
  4974. var d2 = Math.random() * 0xffffffff | 0;
  4975. var d3 = Math.random() * 0xffffffff | 0;
  4976. var uuid = lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' +
  4977. lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' +
  4978. lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] +
  4979. lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ];
  4980. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  4981. return uuid.toUpperCase();
  4982. };
  4983. } )(),
  4984. clamp: function ( value, min, max ) {
  4985. return Math.max( min, Math.min( max, value ) );
  4986. },
  4987. // compute euclidian modulo of m % n
  4988. // https://en.wikipedia.org/wiki/Modulo_operation
  4989. euclideanModulo: function ( n, m ) {
  4990. return ( ( n % m ) + m ) % m;
  4991. },
  4992. // Linear mapping from range <a1, a2> to range <b1, b2>
  4993. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4994. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4995. },
  4996. // https://en.wikipedia.org/wiki/Linear_interpolation
  4997. lerp: function ( x, y, t ) {
  4998. return ( 1 - t ) * x + t * y;
  4999. },
  5000. // http://en.wikipedia.org/wiki/Smoothstep
  5001. smoothstep: function ( x, min, max ) {
  5002. if ( x <= min ) return 0;
  5003. if ( x >= max ) return 1;
  5004. x = ( x - min ) / ( max - min );
  5005. return x * x * ( 3 - 2 * x );
  5006. },
  5007. smootherstep: function ( x, min, max ) {
  5008. if ( x <= min ) return 0;
  5009. if ( x >= max ) return 1;
  5010. x = ( x - min ) / ( max - min );
  5011. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  5012. },
  5013. // Random integer from <low, high> interval
  5014. randInt: function ( low, high ) {
  5015. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  5016. },
  5017. // Random float from <low, high> interval
  5018. randFloat: function ( low, high ) {
  5019. return low + Math.random() * ( high - low );
  5020. },
  5021. // Random float from <-range/2, range/2> interval
  5022. randFloatSpread: function ( range ) {
  5023. return range * ( 0.5 - Math.random() );
  5024. },
  5025. degToRad: function ( degrees ) {
  5026. return degrees * _Math.DEG2RAD;
  5027. },
  5028. radToDeg: function ( radians ) {
  5029. return radians * _Math.RAD2DEG;
  5030. },
  5031. isPowerOfTwo: function ( value ) {
  5032. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  5033. },
  5034. ceilPowerOfTwo: function ( value ) {
  5035. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  5036. },
  5037. floorPowerOfTwo: function ( value ) {
  5038. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  5039. }
  5040. };
  5041. /**
  5042. * @author mrdoob / http://mrdoob.com/
  5043. * @author philogb / http://blog.thejit.org/
  5044. * @author egraether / http://egraether.com/
  5045. * @author zz85 / http://www.lab4games.net/zz85/blog
  5046. */
  5047. function Vector2( x, y ) {
  5048. this.x = x || 0;
  5049. this.y = y || 0;
  5050. }
  5051. Object.defineProperties( Vector2.prototype, {
  5052. "width": {
  5053. get: function () {
  5054. return this.x;
  5055. },
  5056. set: function ( value ) {
  5057. this.x = value;
  5058. }
  5059. },
  5060. "height": {
  5061. get: function () {
  5062. return this.y;
  5063. },
  5064. set: function ( value ) {
  5065. this.y = value;
  5066. }
  5067. }
  5068. } );
  5069. Object.assign( Vector2.prototype, {
  5070. isVector2: true,
  5071. set: function ( x, y ) {
  5072. this.x = x;
  5073. this.y = y;
  5074. return this;
  5075. },
  5076. setScalar: function ( scalar ) {
  5077. this.x = scalar;
  5078. this.y = scalar;
  5079. return this;
  5080. },
  5081. setX: function ( x ) {
  5082. this.x = x;
  5083. return this;
  5084. },
  5085. setY: function ( y ) {
  5086. this.y = y;
  5087. return this;
  5088. },
  5089. setComponent: function ( index, value ) {
  5090. switch ( index ) {
  5091. case 0: this.x = value; break;
  5092. case 1: this.y = value; break;
  5093. default: throw new Error( 'index is out of range: ' + index );
  5094. }
  5095. return this;
  5096. },
  5097. getComponent: function ( index ) {
  5098. switch ( index ) {
  5099. case 0: return this.x;
  5100. case 1: return this.y;
  5101. default: throw new Error( 'index is out of range: ' + index );
  5102. }
  5103. },
  5104. clone: function () {
  5105. return new this.constructor( this.x, this.y );
  5106. },
  5107. copy: function ( v ) {
  5108. this.x = v.x;
  5109. this.y = v.y;
  5110. return this;
  5111. },
  5112. add: function ( v, w ) {
  5113. if ( w !== undefined ) {
  5114. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5115. return this.addVectors( v, w );
  5116. }
  5117. this.x += v.x;
  5118. this.y += v.y;
  5119. return this;
  5120. },
  5121. addScalar: function ( s ) {
  5122. this.x += s;
  5123. this.y += s;
  5124. return this;
  5125. },
  5126. addVectors: function ( a, b ) {
  5127. this.x = a.x + b.x;
  5128. this.y = a.y + b.y;
  5129. return this;
  5130. },
  5131. addScaledVector: function ( v, s ) {
  5132. this.x += v.x * s;
  5133. this.y += v.y * s;
  5134. return this;
  5135. },
  5136. sub: function ( v, w ) {
  5137. if ( w !== undefined ) {
  5138. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5139. return this.subVectors( v, w );
  5140. }
  5141. this.x -= v.x;
  5142. this.y -= v.y;
  5143. return this;
  5144. },
  5145. subScalar: function ( s ) {
  5146. this.x -= s;
  5147. this.y -= s;
  5148. return this;
  5149. },
  5150. subVectors: function ( a, b ) {
  5151. this.x = a.x - b.x;
  5152. this.y = a.y - b.y;
  5153. return this;
  5154. },
  5155. multiply: function ( v ) {
  5156. this.x *= v.x;
  5157. this.y *= v.y;
  5158. return this;
  5159. },
  5160. multiplyScalar: function ( scalar ) {
  5161. this.x *= scalar;
  5162. this.y *= scalar;
  5163. return this;
  5164. },
  5165. divide: function ( v ) {
  5166. this.x /= v.x;
  5167. this.y /= v.y;
  5168. return this;
  5169. },
  5170. divideScalar: function ( scalar ) {
  5171. return this.multiplyScalar( 1 / scalar );
  5172. },
  5173. applyMatrix3: function ( m ) {
  5174. var x = this.x, y = this.y;
  5175. var e = m.elements;
  5176. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  5177. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  5178. return this;
  5179. },
  5180. min: function ( v ) {
  5181. this.x = Math.min( this.x, v.x );
  5182. this.y = Math.min( this.y, v.y );
  5183. return this;
  5184. },
  5185. max: function ( v ) {
  5186. this.x = Math.max( this.x, v.x );
  5187. this.y = Math.max( this.y, v.y );
  5188. return this;
  5189. },
  5190. clamp: function ( min, max ) {
  5191. // assumes min < max, componentwise
  5192. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5193. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5194. return this;
  5195. },
  5196. clampScalar: function () {
  5197. var min = new Vector2();
  5198. var max = new Vector2();
  5199. return function clampScalar( minVal, maxVal ) {
  5200. min.set( minVal, minVal );
  5201. max.set( maxVal, maxVal );
  5202. return this.clamp( min, max );
  5203. };
  5204. }(),
  5205. clampLength: function ( min, max ) {
  5206. var length = this.length();
  5207. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  5208. },
  5209. floor: function () {
  5210. this.x = Math.floor( this.x );
  5211. this.y = Math.floor( this.y );
  5212. return this;
  5213. },
  5214. ceil: function () {
  5215. this.x = Math.ceil( this.x );
  5216. this.y = Math.ceil( this.y );
  5217. return this;
  5218. },
  5219. round: function () {
  5220. this.x = Math.round( this.x );
  5221. this.y = Math.round( this.y );
  5222. return this;
  5223. },
  5224. roundToZero: function () {
  5225. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5226. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5227. return this;
  5228. },
  5229. negate: function () {
  5230. this.x = - this.x;
  5231. this.y = - this.y;
  5232. return this;
  5233. },
  5234. dot: function ( v ) {
  5235. return this.x * v.x + this.y * v.y;
  5236. },
  5237. cross: function ( v ) {
  5238. return this.x * v.y - this.y * v.x;
  5239. },
  5240. lengthSq: function () {
  5241. return this.x * this.x + this.y * this.y;
  5242. },
  5243. length: function () {
  5244. return Math.sqrt( this.x * this.x + this.y * this.y );
  5245. },
  5246. manhattanLength: function () {
  5247. return Math.abs( this.x ) + Math.abs( this.y );
  5248. },
  5249. normalize: function () {
  5250. return this.divideScalar( this.length() || 1 );
  5251. },
  5252. angle: function () {
  5253. // computes the angle in radians with respect to the positive x-axis
  5254. var angle = Math.atan2( this.y, this.x );
  5255. if ( angle < 0 ) angle += 2 * Math.PI;
  5256. return angle;
  5257. },
  5258. distanceTo: function ( v ) {
  5259. return Math.sqrt( this.distanceToSquared( v ) );
  5260. },
  5261. distanceToSquared: function ( v ) {
  5262. var dx = this.x - v.x, dy = this.y - v.y;
  5263. return dx * dx + dy * dy;
  5264. },
  5265. manhattanDistanceTo: function ( v ) {
  5266. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  5267. },
  5268. setLength: function ( length ) {
  5269. return this.normalize().multiplyScalar( length );
  5270. },
  5271. lerp: function ( v, alpha ) {
  5272. this.x += ( v.x - this.x ) * alpha;
  5273. this.y += ( v.y - this.y ) * alpha;
  5274. return this;
  5275. },
  5276. lerpVectors: function ( v1, v2, alpha ) {
  5277. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5278. },
  5279. equals: function ( v ) {
  5280. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  5281. },
  5282. fromArray: function ( array, offset ) {
  5283. if ( offset === undefined ) offset = 0;
  5284. this.x = array[ offset ];
  5285. this.y = array[ offset + 1 ];
  5286. return this;
  5287. },
  5288. toArray: function ( array, offset ) {
  5289. if ( array === undefined ) array = [];
  5290. if ( offset === undefined ) offset = 0;
  5291. array[ offset ] = this.x;
  5292. array[ offset + 1 ] = this.y;
  5293. return array;
  5294. },
  5295. fromBufferAttribute: function ( attribute, index, offset ) {
  5296. if ( offset !== undefined ) {
  5297. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  5298. }
  5299. this.x = attribute.getX( index );
  5300. this.y = attribute.getY( index );
  5301. return this;
  5302. },
  5303. rotateAround: function ( center, angle ) {
  5304. var c = Math.cos( angle ), s = Math.sin( angle );
  5305. var x = this.x - center.x;
  5306. var y = this.y - center.y;
  5307. this.x = x * c - y * s + center.x;
  5308. this.y = x * s + y * c + center.y;
  5309. return this;
  5310. }
  5311. } );
  5312. /**
  5313. * @author mrdoob / http://mrdoob.com/
  5314. * @author supereggbert / http://www.paulbrunt.co.uk/
  5315. * @author philogb / http://blog.thejit.org/
  5316. * @author jordi_ros / http://plattsoft.com
  5317. * @author D1plo1d / http://github.com/D1plo1d
  5318. * @author alteredq / http://alteredqualia.com/
  5319. * @author mikael emtinger / http://gomo.se/
  5320. * @author timknip / http://www.floorplanner.com/
  5321. * @author bhouston / http://clara.io
  5322. * @author WestLangley / http://github.com/WestLangley
  5323. */
  5324. function Matrix4() {
  5325. this.elements = [
  5326. 1, 0, 0, 0,
  5327. 0, 1, 0, 0,
  5328. 0, 0, 1, 0,
  5329. 0, 0, 0, 1
  5330. ];
  5331. if ( arguments.length > 0 ) {
  5332. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  5333. }
  5334. }
  5335. Object.assign( Matrix4.prototype, {
  5336. isMatrix4: true,
  5337. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  5338. var te = this.elements;
  5339. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  5340. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  5341. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  5342. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  5343. return this;
  5344. },
  5345. identity: function () {
  5346. this.set(
  5347. 1, 0, 0, 0,
  5348. 0, 1, 0, 0,
  5349. 0, 0, 1, 0,
  5350. 0, 0, 0, 1
  5351. );
  5352. return this;
  5353. },
  5354. clone: function () {
  5355. return new Matrix4().fromArray( this.elements );
  5356. },
  5357. copy: function ( m ) {
  5358. var te = this.elements;
  5359. var me = m.elements;
  5360. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  5361. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  5362. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  5363. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  5364. return this;
  5365. },
  5366. copyPosition: function ( m ) {
  5367. var te = this.elements, me = m.elements;
  5368. te[ 12 ] = me[ 12 ];
  5369. te[ 13 ] = me[ 13 ];
  5370. te[ 14 ] = me[ 14 ];
  5371. return this;
  5372. },
  5373. extractBasis: function ( xAxis, yAxis, zAxis ) {
  5374. xAxis.setFromMatrixColumn( this, 0 );
  5375. yAxis.setFromMatrixColumn( this, 1 );
  5376. zAxis.setFromMatrixColumn( this, 2 );
  5377. return this;
  5378. },
  5379. makeBasis: function ( xAxis, yAxis, zAxis ) {
  5380. this.set(
  5381. xAxis.x, yAxis.x, zAxis.x, 0,
  5382. xAxis.y, yAxis.y, zAxis.y, 0,
  5383. xAxis.z, yAxis.z, zAxis.z, 0,
  5384. 0, 0, 0, 1
  5385. );
  5386. return this;
  5387. },
  5388. extractRotation: function () {
  5389. var v1 = new Vector3();
  5390. return function extractRotation( m ) {
  5391. // this method does not support reflection matrices
  5392. var te = this.elements;
  5393. var me = m.elements;
  5394. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  5395. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  5396. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  5397. te[ 0 ] = me[ 0 ] * scaleX;
  5398. te[ 1 ] = me[ 1 ] * scaleX;
  5399. te[ 2 ] = me[ 2 ] * scaleX;
  5400. te[ 3 ] = 0;
  5401. te[ 4 ] = me[ 4 ] * scaleY;
  5402. te[ 5 ] = me[ 5 ] * scaleY;
  5403. te[ 6 ] = me[ 6 ] * scaleY;
  5404. te[ 7 ] = 0;
  5405. te[ 8 ] = me[ 8 ] * scaleZ;
  5406. te[ 9 ] = me[ 9 ] * scaleZ;
  5407. te[ 10 ] = me[ 10 ] * scaleZ;
  5408. te[ 11 ] = 0;
  5409. te[ 12 ] = 0;
  5410. te[ 13 ] = 0;
  5411. te[ 14 ] = 0;
  5412. te[ 15 ] = 1;
  5413. return this;
  5414. };
  5415. }(),
  5416. makeRotationFromEuler: function ( euler ) {
  5417. if ( ! ( euler && euler.isEuler ) ) {
  5418. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  5419. }
  5420. var te = this.elements;
  5421. var x = euler.x, y = euler.y, z = euler.z;
  5422. var a = Math.cos( x ), b = Math.sin( x );
  5423. var c = Math.cos( y ), d = Math.sin( y );
  5424. var e = Math.cos( z ), f = Math.sin( z );
  5425. if ( euler.order === 'XYZ' ) {
  5426. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5427. te[ 0 ] = c * e;
  5428. te[ 4 ] = - c * f;
  5429. te[ 8 ] = d;
  5430. te[ 1 ] = af + be * d;
  5431. te[ 5 ] = ae - bf * d;
  5432. te[ 9 ] = - b * c;
  5433. te[ 2 ] = bf - ae * d;
  5434. te[ 6 ] = be + af * d;
  5435. te[ 10 ] = a * c;
  5436. } else if ( euler.order === 'YXZ' ) {
  5437. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5438. te[ 0 ] = ce + df * b;
  5439. te[ 4 ] = de * b - cf;
  5440. te[ 8 ] = a * d;
  5441. te[ 1 ] = a * f;
  5442. te[ 5 ] = a * e;
  5443. te[ 9 ] = - b;
  5444. te[ 2 ] = cf * b - de;
  5445. te[ 6 ] = df + ce * b;
  5446. te[ 10 ] = a * c;
  5447. } else if ( euler.order === 'ZXY' ) {
  5448. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5449. te[ 0 ] = ce - df * b;
  5450. te[ 4 ] = - a * f;
  5451. te[ 8 ] = de + cf * b;
  5452. te[ 1 ] = cf + de * b;
  5453. te[ 5 ] = a * e;
  5454. te[ 9 ] = df - ce * b;
  5455. te[ 2 ] = - a * d;
  5456. te[ 6 ] = b;
  5457. te[ 10 ] = a * c;
  5458. } else if ( euler.order === 'ZYX' ) {
  5459. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5460. te[ 0 ] = c * e;
  5461. te[ 4 ] = be * d - af;
  5462. te[ 8 ] = ae * d + bf;
  5463. te[ 1 ] = c * f;
  5464. te[ 5 ] = bf * d + ae;
  5465. te[ 9 ] = af * d - be;
  5466. te[ 2 ] = - d;
  5467. te[ 6 ] = b * c;
  5468. te[ 10 ] = a * c;
  5469. } else if ( euler.order === 'YZX' ) {
  5470. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5471. te[ 0 ] = c * e;
  5472. te[ 4 ] = bd - ac * f;
  5473. te[ 8 ] = bc * f + ad;
  5474. te[ 1 ] = f;
  5475. te[ 5 ] = a * e;
  5476. te[ 9 ] = - b * e;
  5477. te[ 2 ] = - d * e;
  5478. te[ 6 ] = ad * f + bc;
  5479. te[ 10 ] = ac - bd * f;
  5480. } else if ( euler.order === 'XZY' ) {
  5481. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5482. te[ 0 ] = c * e;
  5483. te[ 4 ] = - f;
  5484. te[ 8 ] = d * e;
  5485. te[ 1 ] = ac * f + bd;
  5486. te[ 5 ] = a * e;
  5487. te[ 9 ] = ad * f - bc;
  5488. te[ 2 ] = bc * f - ad;
  5489. te[ 6 ] = b * e;
  5490. te[ 10 ] = bd * f + ac;
  5491. }
  5492. // bottom row
  5493. te[ 3 ] = 0;
  5494. te[ 7 ] = 0;
  5495. te[ 11 ] = 0;
  5496. // last column
  5497. te[ 12 ] = 0;
  5498. te[ 13 ] = 0;
  5499. te[ 14 ] = 0;
  5500. te[ 15 ] = 1;
  5501. return this;
  5502. },
  5503. makeRotationFromQuaternion: function () {
  5504. var zero = new Vector3( 0, 0, 0 );
  5505. var one = new Vector3( 1, 1, 1 );
  5506. return function makeRotationFromQuaternion( q ) {
  5507. return this.compose( zero, q, one );
  5508. };
  5509. }(),
  5510. lookAt: function () {
  5511. var x = new Vector3();
  5512. var y = new Vector3();
  5513. var z = new Vector3();
  5514. return function lookAt( eye, target, up ) {
  5515. var te = this.elements;
  5516. z.subVectors( eye, target );
  5517. if ( z.lengthSq() === 0 ) {
  5518. // eye and target are in the same position
  5519. z.z = 1;
  5520. }
  5521. z.normalize();
  5522. x.crossVectors( up, z );
  5523. if ( x.lengthSq() === 0 ) {
  5524. // up and z are parallel
  5525. if ( Math.abs( up.z ) === 1 ) {
  5526. z.x += 0.0001;
  5527. } else {
  5528. z.z += 0.0001;
  5529. }
  5530. z.normalize();
  5531. x.crossVectors( up, z );
  5532. }
  5533. x.normalize();
  5534. y.crossVectors( z, x );
  5535. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  5536. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  5537. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  5538. return this;
  5539. };
  5540. }(),
  5541. multiply: function ( m, n ) {
  5542. if ( n !== undefined ) {
  5543. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  5544. return this.multiplyMatrices( m, n );
  5545. }
  5546. return this.multiplyMatrices( this, m );
  5547. },
  5548. premultiply: function ( m ) {
  5549. return this.multiplyMatrices( m, this );
  5550. },
  5551. multiplyMatrices: function ( a, b ) {
  5552. var ae = a.elements;
  5553. var be = b.elements;
  5554. var te = this.elements;
  5555. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  5556. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  5557. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  5558. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  5559. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  5560. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  5561. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  5562. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  5563. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  5564. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  5565. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  5566. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  5567. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  5568. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  5569. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  5570. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  5571. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  5572. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  5573. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  5574. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  5575. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  5576. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  5577. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  5578. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  5579. return this;
  5580. },
  5581. multiplyScalar: function ( s ) {
  5582. var te = this.elements;
  5583. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  5584. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  5585. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  5586. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  5587. return this;
  5588. },
  5589. applyToBufferAttribute: function () {
  5590. var v1 = new Vector3();
  5591. return function applyToBufferAttribute( attribute ) {
  5592. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5593. v1.x = attribute.getX( i );
  5594. v1.y = attribute.getY( i );
  5595. v1.z = attribute.getZ( i );
  5596. v1.applyMatrix4( this );
  5597. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5598. }
  5599. return attribute;
  5600. };
  5601. }(),
  5602. determinant: function () {
  5603. var te = this.elements;
  5604. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  5605. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  5606. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  5607. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  5608. //TODO: make this more efficient
  5609. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  5610. return (
  5611. n41 * (
  5612. + n14 * n23 * n32
  5613. - n13 * n24 * n32
  5614. - n14 * n22 * n33
  5615. + n12 * n24 * n33
  5616. + n13 * n22 * n34
  5617. - n12 * n23 * n34
  5618. ) +
  5619. n42 * (
  5620. + n11 * n23 * n34
  5621. - n11 * n24 * n33
  5622. + n14 * n21 * n33
  5623. - n13 * n21 * n34
  5624. + n13 * n24 * n31
  5625. - n14 * n23 * n31
  5626. ) +
  5627. n43 * (
  5628. + n11 * n24 * n32
  5629. - n11 * n22 * n34
  5630. - n14 * n21 * n32
  5631. + n12 * n21 * n34
  5632. + n14 * n22 * n31
  5633. - n12 * n24 * n31
  5634. ) +
  5635. n44 * (
  5636. - n13 * n22 * n31
  5637. - n11 * n23 * n32
  5638. + n11 * n22 * n33
  5639. + n13 * n21 * n32
  5640. - n12 * n21 * n33
  5641. + n12 * n23 * n31
  5642. )
  5643. );
  5644. },
  5645. transpose: function () {
  5646. var te = this.elements;
  5647. var tmp;
  5648. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  5649. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  5650. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  5651. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  5652. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  5653. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  5654. return this;
  5655. },
  5656. setPosition: function ( v ) {
  5657. var te = this.elements;
  5658. te[ 12 ] = v.x;
  5659. te[ 13 ] = v.y;
  5660. te[ 14 ] = v.z;
  5661. return this;
  5662. },
  5663. getInverse: function ( m, throwOnDegenerate ) {
  5664. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  5665. var te = this.elements,
  5666. me = m.elements,
  5667. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  5668. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  5669. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  5670. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  5671. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  5672. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  5673. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  5674. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  5675. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  5676. if ( det === 0 ) {
  5677. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  5678. if ( throwOnDegenerate === true ) {
  5679. throw new Error( msg );
  5680. } else {
  5681. console.warn( msg );
  5682. }
  5683. return this.identity();
  5684. }
  5685. var detInv = 1 / det;
  5686. te[ 0 ] = t11 * detInv;
  5687. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  5688. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  5689. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  5690. te[ 4 ] = t12 * detInv;
  5691. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  5692. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  5693. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  5694. te[ 8 ] = t13 * detInv;
  5695. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  5696. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  5697. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  5698. te[ 12 ] = t14 * detInv;
  5699. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  5700. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  5701. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  5702. return this;
  5703. },
  5704. scale: function ( v ) {
  5705. var te = this.elements;
  5706. var x = v.x, y = v.y, z = v.z;
  5707. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  5708. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  5709. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  5710. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  5711. return this;
  5712. },
  5713. getMaxScaleOnAxis: function () {
  5714. var te = this.elements;
  5715. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  5716. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  5717. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  5718. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  5719. },
  5720. makeTranslation: function ( x, y, z ) {
  5721. this.set(
  5722. 1, 0, 0, x,
  5723. 0, 1, 0, y,
  5724. 0, 0, 1, z,
  5725. 0, 0, 0, 1
  5726. );
  5727. return this;
  5728. },
  5729. makeRotationX: function ( theta ) {
  5730. var c = Math.cos( theta ), s = Math.sin( theta );
  5731. this.set(
  5732. 1, 0, 0, 0,
  5733. 0, c, - s, 0,
  5734. 0, s, c, 0,
  5735. 0, 0, 0, 1
  5736. );
  5737. return this;
  5738. },
  5739. makeRotationY: function ( theta ) {
  5740. var c = Math.cos( theta ), s = Math.sin( theta );
  5741. this.set(
  5742. c, 0, s, 0,
  5743. 0, 1, 0, 0,
  5744. - s, 0, c, 0,
  5745. 0, 0, 0, 1
  5746. );
  5747. return this;
  5748. },
  5749. makeRotationZ: function ( theta ) {
  5750. var c = Math.cos( theta ), s = Math.sin( theta );
  5751. this.set(
  5752. c, - s, 0, 0,
  5753. s, c, 0, 0,
  5754. 0, 0, 1, 0,
  5755. 0, 0, 0, 1
  5756. );
  5757. return this;
  5758. },
  5759. makeRotationAxis: function ( axis, angle ) {
  5760. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  5761. var c = Math.cos( angle );
  5762. var s = Math.sin( angle );
  5763. var t = 1 - c;
  5764. var x = axis.x, y = axis.y, z = axis.z;
  5765. var tx = t * x, ty = t * y;
  5766. this.set(
  5767. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  5768. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  5769. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  5770. 0, 0, 0, 1
  5771. );
  5772. return this;
  5773. },
  5774. makeScale: function ( x, y, z ) {
  5775. this.set(
  5776. x, 0, 0, 0,
  5777. 0, y, 0, 0,
  5778. 0, 0, z, 0,
  5779. 0, 0, 0, 1
  5780. );
  5781. return this;
  5782. },
  5783. makeShear: function ( x, y, z ) {
  5784. this.set(
  5785. 1, y, z, 0,
  5786. x, 1, z, 0,
  5787. x, y, 1, 0,
  5788. 0, 0, 0, 1
  5789. );
  5790. return this;
  5791. },
  5792. compose: function ( position, quaternion, scale ) {
  5793. var te = this.elements;
  5794. var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  5795. var x2 = x + x, y2 = y + y, z2 = z + z;
  5796. var xx = x * x2, xy = x * y2, xz = x * z2;
  5797. var yy = y * y2, yz = y * z2, zz = z * z2;
  5798. var wx = w * x2, wy = w * y2, wz = w * z2;
  5799. var sx = scale.x, sy = scale.y, sz = scale.z;
  5800. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  5801. te[ 1 ] = ( xy + wz ) * sx;
  5802. te[ 2 ] = ( xz - wy ) * sx;
  5803. te[ 3 ] = 0;
  5804. te[ 4 ] = ( xy - wz ) * sy;
  5805. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  5806. te[ 6 ] = ( yz + wx ) * sy;
  5807. te[ 7 ] = 0;
  5808. te[ 8 ] = ( xz + wy ) * sz;
  5809. te[ 9 ] = ( yz - wx ) * sz;
  5810. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  5811. te[ 11 ] = 0;
  5812. te[ 12 ] = position.x;
  5813. te[ 13 ] = position.y;
  5814. te[ 14 ] = position.z;
  5815. te[ 15 ] = 1;
  5816. return this;
  5817. },
  5818. decompose: function () {
  5819. var vector = new Vector3();
  5820. var matrix = new Matrix4();
  5821. return function decompose( position, quaternion, scale ) {
  5822. var te = this.elements;
  5823. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  5824. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  5825. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  5826. // if determine is negative, we need to invert one scale
  5827. var det = this.determinant();
  5828. if ( det < 0 ) sx = - sx;
  5829. position.x = te[ 12 ];
  5830. position.y = te[ 13 ];
  5831. position.z = te[ 14 ];
  5832. // scale the rotation part
  5833. matrix.copy( this );
  5834. var invSX = 1 / sx;
  5835. var invSY = 1 / sy;
  5836. var invSZ = 1 / sz;
  5837. matrix.elements[ 0 ] *= invSX;
  5838. matrix.elements[ 1 ] *= invSX;
  5839. matrix.elements[ 2 ] *= invSX;
  5840. matrix.elements[ 4 ] *= invSY;
  5841. matrix.elements[ 5 ] *= invSY;
  5842. matrix.elements[ 6 ] *= invSY;
  5843. matrix.elements[ 8 ] *= invSZ;
  5844. matrix.elements[ 9 ] *= invSZ;
  5845. matrix.elements[ 10 ] *= invSZ;
  5846. quaternion.setFromRotationMatrix( matrix );
  5847. scale.x = sx;
  5848. scale.y = sy;
  5849. scale.z = sz;
  5850. return this;
  5851. };
  5852. }(),
  5853. makePerspective: function ( left, right, top, bottom, near, far ) {
  5854. if ( far === undefined ) {
  5855. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  5856. }
  5857. var te = this.elements;
  5858. var x = 2 * near / ( right - left );
  5859. var y = 2 * near / ( top - bottom );
  5860. var a = ( right + left ) / ( right - left );
  5861. var b = ( top + bottom ) / ( top - bottom );
  5862. var c = - ( far + near ) / ( far - near );
  5863. var d = - 2 * far * near / ( far - near );
  5864. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  5865. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  5866. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  5867. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  5868. return this;
  5869. },
  5870. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  5871. var te = this.elements;
  5872. var w = 1.0 / ( right - left );
  5873. var h = 1.0 / ( top - bottom );
  5874. var p = 1.0 / ( far - near );
  5875. var x = ( right + left ) * w;
  5876. var y = ( top + bottom ) * h;
  5877. var z = ( far + near ) * p;
  5878. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  5879. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5880. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5881. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5882. return this;
  5883. },
  5884. equals: function ( matrix ) {
  5885. var te = this.elements;
  5886. var me = matrix.elements;
  5887. for ( var i = 0; i < 16; i ++ ) {
  5888. if ( te[ i ] !== me[ i ] ) return false;
  5889. }
  5890. return true;
  5891. },
  5892. fromArray: function ( array, offset ) {
  5893. if ( offset === undefined ) offset = 0;
  5894. for ( var i = 0; i < 16; i ++ ) {
  5895. this.elements[ i ] = array[ i + offset ];
  5896. }
  5897. return this;
  5898. },
  5899. toArray: function ( array, offset ) {
  5900. if ( array === undefined ) array = [];
  5901. if ( offset === undefined ) offset = 0;
  5902. var te = this.elements;
  5903. array[ offset ] = te[ 0 ];
  5904. array[ offset + 1 ] = te[ 1 ];
  5905. array[ offset + 2 ] = te[ 2 ];
  5906. array[ offset + 3 ] = te[ 3 ];
  5907. array[ offset + 4 ] = te[ 4 ];
  5908. array[ offset + 5 ] = te[ 5 ];
  5909. array[ offset + 6 ] = te[ 6 ];
  5910. array[ offset + 7 ] = te[ 7 ];
  5911. array[ offset + 8 ] = te[ 8 ];
  5912. array[ offset + 9 ] = te[ 9 ];
  5913. array[ offset + 10 ] = te[ 10 ];
  5914. array[ offset + 11 ] = te[ 11 ];
  5915. array[ offset + 12 ] = te[ 12 ];
  5916. array[ offset + 13 ] = te[ 13 ];
  5917. array[ offset + 14 ] = te[ 14 ];
  5918. array[ offset + 15 ] = te[ 15 ];
  5919. return array;
  5920. }
  5921. } );
  5922. /**
  5923. * @author mikael emtinger / http://gomo.se/
  5924. * @author alteredq / http://alteredqualia.com/
  5925. * @author WestLangley / http://github.com/WestLangley
  5926. * @author bhouston / http://clara.io
  5927. */
  5928. function Quaternion( x, y, z, w ) {
  5929. this._x = x || 0;
  5930. this._y = y || 0;
  5931. this._z = z || 0;
  5932. this._w = ( w !== undefined ) ? w : 1;
  5933. }
  5934. Object.assign( Quaternion, {
  5935. slerp: function ( qa, qb, qm, t ) {
  5936. return qm.copy( qa ).slerp( qb, t );
  5937. },
  5938. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5939. // fuzz-free, array-based Quaternion SLERP operation
  5940. var x0 = src0[ srcOffset0 + 0 ],
  5941. y0 = src0[ srcOffset0 + 1 ],
  5942. z0 = src0[ srcOffset0 + 2 ],
  5943. w0 = src0[ srcOffset0 + 3 ],
  5944. x1 = src1[ srcOffset1 + 0 ],
  5945. y1 = src1[ srcOffset1 + 1 ],
  5946. z1 = src1[ srcOffset1 + 2 ],
  5947. w1 = src1[ srcOffset1 + 3 ];
  5948. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5949. var s = 1 - t,
  5950. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5951. dir = ( cos >= 0 ? 1 : - 1 ),
  5952. sqrSin = 1 - cos * cos;
  5953. // Skip the Slerp for tiny steps to avoid numeric problems:
  5954. if ( sqrSin > Number.EPSILON ) {
  5955. var sin = Math.sqrt( sqrSin ),
  5956. len = Math.atan2( sin, cos * dir );
  5957. s = Math.sin( s * len ) / sin;
  5958. t = Math.sin( t * len ) / sin;
  5959. }
  5960. var tDir = t * dir;
  5961. x0 = x0 * s + x1 * tDir;
  5962. y0 = y0 * s + y1 * tDir;
  5963. z0 = z0 * s + z1 * tDir;
  5964. w0 = w0 * s + w1 * tDir;
  5965. // Normalize in case we just did a lerp:
  5966. if ( s === 1 - t ) {
  5967. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5968. x0 *= f;
  5969. y0 *= f;
  5970. z0 *= f;
  5971. w0 *= f;
  5972. }
  5973. }
  5974. dst[ dstOffset ] = x0;
  5975. dst[ dstOffset + 1 ] = y0;
  5976. dst[ dstOffset + 2 ] = z0;
  5977. dst[ dstOffset + 3 ] = w0;
  5978. }
  5979. } );
  5980. Object.defineProperties( Quaternion.prototype, {
  5981. x: {
  5982. get: function () {
  5983. return this._x;
  5984. },
  5985. set: function ( value ) {
  5986. this._x = value;
  5987. this.onChangeCallback();
  5988. }
  5989. },
  5990. y: {
  5991. get: function () {
  5992. return this._y;
  5993. },
  5994. set: function ( value ) {
  5995. this._y = value;
  5996. this.onChangeCallback();
  5997. }
  5998. },
  5999. z: {
  6000. get: function () {
  6001. return this._z;
  6002. },
  6003. set: function ( value ) {
  6004. this._z = value;
  6005. this.onChangeCallback();
  6006. }
  6007. },
  6008. w: {
  6009. get: function () {
  6010. return this._w;
  6011. },
  6012. set: function ( value ) {
  6013. this._w = value;
  6014. this.onChangeCallback();
  6015. }
  6016. }
  6017. } );
  6018. Object.assign( Quaternion.prototype, {
  6019. isQuaternion: true,
  6020. set: function ( x, y, z, w ) {
  6021. this._x = x;
  6022. this._y = y;
  6023. this._z = z;
  6024. this._w = w;
  6025. this.onChangeCallback();
  6026. return this;
  6027. },
  6028. clone: function () {
  6029. return new this.constructor( this._x, this._y, this._z, this._w );
  6030. },
  6031. copy: function ( quaternion ) {
  6032. this._x = quaternion.x;
  6033. this._y = quaternion.y;
  6034. this._z = quaternion.z;
  6035. this._w = quaternion.w;
  6036. this.onChangeCallback();
  6037. return this;
  6038. },
  6039. setFromEuler: function ( euler, update ) {
  6040. if ( ! ( euler && euler.isEuler ) ) {
  6041. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6042. }
  6043. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  6044. // http://www.mathworks.com/matlabcentral/fileexchange/
  6045. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  6046. // content/SpinCalc.m
  6047. var cos = Math.cos;
  6048. var sin = Math.sin;
  6049. var c1 = cos( x / 2 );
  6050. var c2 = cos( y / 2 );
  6051. var c3 = cos( z / 2 );
  6052. var s1 = sin( x / 2 );
  6053. var s2 = sin( y / 2 );
  6054. var s3 = sin( z / 2 );
  6055. if ( order === 'XYZ' ) {
  6056. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6057. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6058. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6059. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6060. } else if ( order === 'YXZ' ) {
  6061. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6062. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6063. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6064. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6065. } else if ( order === 'ZXY' ) {
  6066. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6067. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6068. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6069. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6070. } else if ( order === 'ZYX' ) {
  6071. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6072. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6073. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6074. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6075. } else if ( order === 'YZX' ) {
  6076. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  6077. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  6078. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  6079. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  6080. } else if ( order === 'XZY' ) {
  6081. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  6082. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  6083. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  6084. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  6085. }
  6086. if ( update !== false ) this.onChangeCallback();
  6087. return this;
  6088. },
  6089. setFromAxisAngle: function ( axis, angle ) {
  6090. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  6091. // assumes axis is normalized
  6092. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  6093. this._x = axis.x * s;
  6094. this._y = axis.y * s;
  6095. this._z = axis.z * s;
  6096. this._w = Math.cos( halfAngle );
  6097. this.onChangeCallback();
  6098. return this;
  6099. },
  6100. setFromRotationMatrix: function ( m ) {
  6101. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  6102. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6103. var te = m.elements,
  6104. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6105. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6106. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  6107. trace = m11 + m22 + m33,
  6108. s;
  6109. if ( trace > 0 ) {
  6110. s = 0.5 / Math.sqrt( trace + 1.0 );
  6111. this._w = 0.25 / s;
  6112. this._x = ( m32 - m23 ) * s;
  6113. this._y = ( m13 - m31 ) * s;
  6114. this._z = ( m21 - m12 ) * s;
  6115. } else if ( m11 > m22 && m11 > m33 ) {
  6116. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  6117. this._w = ( m32 - m23 ) / s;
  6118. this._x = 0.25 * s;
  6119. this._y = ( m12 + m21 ) / s;
  6120. this._z = ( m13 + m31 ) / s;
  6121. } else if ( m22 > m33 ) {
  6122. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  6123. this._w = ( m13 - m31 ) / s;
  6124. this._x = ( m12 + m21 ) / s;
  6125. this._y = 0.25 * s;
  6126. this._z = ( m23 + m32 ) / s;
  6127. } else {
  6128. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  6129. this._w = ( m21 - m12 ) / s;
  6130. this._x = ( m13 + m31 ) / s;
  6131. this._y = ( m23 + m32 ) / s;
  6132. this._z = 0.25 * s;
  6133. }
  6134. this.onChangeCallback();
  6135. return this;
  6136. },
  6137. setFromUnitVectors: function () {
  6138. // assumes direction vectors vFrom and vTo are normalized
  6139. var v1 = new Vector3();
  6140. var r;
  6141. var EPS = 0.000001;
  6142. return function setFromUnitVectors( vFrom, vTo ) {
  6143. if ( v1 === undefined ) v1 = new Vector3();
  6144. r = vFrom.dot( vTo ) + 1;
  6145. if ( r < EPS ) {
  6146. r = 0;
  6147. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  6148. v1.set( - vFrom.y, vFrom.x, 0 );
  6149. } else {
  6150. v1.set( 0, - vFrom.z, vFrom.y );
  6151. }
  6152. } else {
  6153. v1.crossVectors( vFrom, vTo );
  6154. }
  6155. this._x = v1.x;
  6156. this._y = v1.y;
  6157. this._z = v1.z;
  6158. this._w = r;
  6159. return this.normalize();
  6160. };
  6161. }(),
  6162. angleTo: function ( q ) {
  6163. return 2 * Math.acos( Math.abs( _Math.clamp( this.dot( q ), - 1, 1 ) ) );
  6164. },
  6165. rotateTowards: function ( q, step ) {
  6166. var angle = this.angleTo( q );
  6167. if ( angle === 0 ) return this;
  6168. var t = Math.min( 1, step / angle );
  6169. this.slerp( q, t );
  6170. return this;
  6171. },
  6172. inverse: function () {
  6173. // quaternion is assumed to have unit length
  6174. return this.conjugate();
  6175. },
  6176. conjugate: function () {
  6177. this._x *= - 1;
  6178. this._y *= - 1;
  6179. this._z *= - 1;
  6180. this.onChangeCallback();
  6181. return this;
  6182. },
  6183. dot: function ( v ) {
  6184. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  6185. },
  6186. lengthSq: function () {
  6187. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  6188. },
  6189. length: function () {
  6190. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  6191. },
  6192. normalize: function () {
  6193. var l = this.length();
  6194. if ( l === 0 ) {
  6195. this._x = 0;
  6196. this._y = 0;
  6197. this._z = 0;
  6198. this._w = 1;
  6199. } else {
  6200. l = 1 / l;
  6201. this._x = this._x * l;
  6202. this._y = this._y * l;
  6203. this._z = this._z * l;
  6204. this._w = this._w * l;
  6205. }
  6206. this.onChangeCallback();
  6207. return this;
  6208. },
  6209. multiply: function ( q, p ) {
  6210. if ( p !== undefined ) {
  6211. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  6212. return this.multiplyQuaternions( q, p );
  6213. }
  6214. return this.multiplyQuaternions( this, q );
  6215. },
  6216. premultiply: function ( q ) {
  6217. return this.multiplyQuaternions( q, this );
  6218. },
  6219. multiplyQuaternions: function ( a, b ) {
  6220. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6221. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6222. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6223. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6224. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6225. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6226. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6227. this.onChangeCallback();
  6228. return this;
  6229. },
  6230. slerp: function ( qb, t ) {
  6231. if ( t === 0 ) return this;
  6232. if ( t === 1 ) return this.copy( qb );
  6233. var x = this._x, y = this._y, z = this._z, w = this._w;
  6234. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6235. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6236. if ( cosHalfTheta < 0 ) {
  6237. this._w = - qb._w;
  6238. this._x = - qb._x;
  6239. this._y = - qb._y;
  6240. this._z = - qb._z;
  6241. cosHalfTheta = - cosHalfTheta;
  6242. } else {
  6243. this.copy( qb );
  6244. }
  6245. if ( cosHalfTheta >= 1.0 ) {
  6246. this._w = w;
  6247. this._x = x;
  6248. this._y = y;
  6249. this._z = z;
  6250. return this;
  6251. }
  6252. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  6253. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  6254. var s = 1 - t;
  6255. this._w = s * w + t * this._w;
  6256. this._x = s * x + t * this._x;
  6257. this._y = s * y + t * this._y;
  6258. this._z = s * z + t * this._z;
  6259. return this.normalize();
  6260. }
  6261. var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  6262. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6263. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6264. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6265. this._w = ( w * ratioA + this._w * ratioB );
  6266. this._x = ( x * ratioA + this._x * ratioB );
  6267. this._y = ( y * ratioA + this._y * ratioB );
  6268. this._z = ( z * ratioA + this._z * ratioB );
  6269. this.onChangeCallback();
  6270. return this;
  6271. },
  6272. equals: function ( quaternion ) {
  6273. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6274. },
  6275. fromArray: function ( array, offset ) {
  6276. if ( offset === undefined ) offset = 0;
  6277. this._x = array[ offset ];
  6278. this._y = array[ offset + 1 ];
  6279. this._z = array[ offset + 2 ];
  6280. this._w = array[ offset + 3 ];
  6281. this.onChangeCallback();
  6282. return this;
  6283. },
  6284. toArray: function ( array, offset ) {
  6285. if ( array === undefined ) array = [];
  6286. if ( offset === undefined ) offset = 0;
  6287. array[ offset ] = this._x;
  6288. array[ offset + 1 ] = this._y;
  6289. array[ offset + 2 ] = this._z;
  6290. array[ offset + 3 ] = this._w;
  6291. return array;
  6292. },
  6293. onChange: function ( callback ) {
  6294. this.onChangeCallback = callback;
  6295. return this;
  6296. },
  6297. onChangeCallback: function () {}
  6298. } );
  6299. /**
  6300. * @author mrdoob / http://mrdoob.com/
  6301. * @author kile / http://kile.stravaganza.org/
  6302. * @author philogb / http://blog.thejit.org/
  6303. * @author mikael emtinger / http://gomo.se/
  6304. * @author egraether / http://egraether.com/
  6305. * @author WestLangley / http://github.com/WestLangley
  6306. */
  6307. function Vector3( x, y, z ) {
  6308. this.x = x || 0;
  6309. this.y = y || 0;
  6310. this.z = z || 0;
  6311. }
  6312. Object.assign( Vector3.prototype, {
  6313. isVector3: true,
  6314. set: function ( x, y, z ) {
  6315. this.x = x;
  6316. this.y = y;
  6317. this.z = z;
  6318. return this;
  6319. },
  6320. setScalar: function ( scalar ) {
  6321. this.x = scalar;
  6322. this.y = scalar;
  6323. this.z = scalar;
  6324. return this;
  6325. },
  6326. setX: function ( x ) {
  6327. this.x = x;
  6328. return this;
  6329. },
  6330. setY: function ( y ) {
  6331. this.y = y;
  6332. return this;
  6333. },
  6334. setZ: function ( z ) {
  6335. this.z = z;
  6336. return this;
  6337. },
  6338. setComponent: function ( index, value ) {
  6339. switch ( index ) {
  6340. case 0: this.x = value; break;
  6341. case 1: this.y = value; break;
  6342. case 2: this.z = value; break;
  6343. default: throw new Error( 'index is out of range: ' + index );
  6344. }
  6345. return this;
  6346. },
  6347. getComponent: function ( index ) {
  6348. switch ( index ) {
  6349. case 0: return this.x;
  6350. case 1: return this.y;
  6351. case 2: return this.z;
  6352. default: throw new Error( 'index is out of range: ' + index );
  6353. }
  6354. },
  6355. clone: function () {
  6356. return new this.constructor( this.x, this.y, this.z );
  6357. },
  6358. copy: function ( v ) {
  6359. this.x = v.x;
  6360. this.y = v.y;
  6361. this.z = v.z;
  6362. return this;
  6363. },
  6364. add: function ( v, w ) {
  6365. if ( w !== undefined ) {
  6366. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6367. return this.addVectors( v, w );
  6368. }
  6369. this.x += v.x;
  6370. this.y += v.y;
  6371. this.z += v.z;
  6372. return this;
  6373. },
  6374. addScalar: function ( s ) {
  6375. this.x += s;
  6376. this.y += s;
  6377. this.z += s;
  6378. return this;
  6379. },
  6380. addVectors: function ( a, b ) {
  6381. this.x = a.x + b.x;
  6382. this.y = a.y + b.y;
  6383. this.z = a.z + b.z;
  6384. return this;
  6385. },
  6386. addScaledVector: function ( v, s ) {
  6387. this.x += v.x * s;
  6388. this.y += v.y * s;
  6389. this.z += v.z * s;
  6390. return this;
  6391. },
  6392. sub: function ( v, w ) {
  6393. if ( w !== undefined ) {
  6394. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6395. return this.subVectors( v, w );
  6396. }
  6397. this.x -= v.x;
  6398. this.y -= v.y;
  6399. this.z -= v.z;
  6400. return this;
  6401. },
  6402. subScalar: function ( s ) {
  6403. this.x -= s;
  6404. this.y -= s;
  6405. this.z -= s;
  6406. return this;
  6407. },
  6408. subVectors: function ( a, b ) {
  6409. this.x = a.x - b.x;
  6410. this.y = a.y - b.y;
  6411. this.z = a.z - b.z;
  6412. return this;
  6413. },
  6414. multiply: function ( v, w ) {
  6415. if ( w !== undefined ) {
  6416. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6417. return this.multiplyVectors( v, w );
  6418. }
  6419. this.x *= v.x;
  6420. this.y *= v.y;
  6421. this.z *= v.z;
  6422. return this;
  6423. },
  6424. multiplyScalar: function ( scalar ) {
  6425. this.x *= scalar;
  6426. this.y *= scalar;
  6427. this.z *= scalar;
  6428. return this;
  6429. },
  6430. multiplyVectors: function ( a, b ) {
  6431. this.x = a.x * b.x;
  6432. this.y = a.y * b.y;
  6433. this.z = a.z * b.z;
  6434. return this;
  6435. },
  6436. applyEuler: function () {
  6437. var quaternion = new Quaternion();
  6438. return function applyEuler( euler ) {
  6439. if ( ! ( euler && euler.isEuler ) ) {
  6440. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6441. }
  6442. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  6443. };
  6444. }(),
  6445. applyAxisAngle: function () {
  6446. var quaternion = new Quaternion();
  6447. return function applyAxisAngle( axis, angle ) {
  6448. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  6449. };
  6450. }(),
  6451. applyMatrix3: function ( m ) {
  6452. var x = this.x, y = this.y, z = this.z;
  6453. var e = m.elements;
  6454. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6455. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6456. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6457. return this;
  6458. },
  6459. applyMatrix4: function ( m ) {
  6460. var x = this.x, y = this.y, z = this.z;
  6461. var e = m.elements;
  6462. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6463. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6464. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6465. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6466. return this;
  6467. },
  6468. applyQuaternion: function ( q ) {
  6469. var x = this.x, y = this.y, z = this.z;
  6470. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6471. // calculate quat * vector
  6472. var ix = qw * x + qy * z - qz * y;
  6473. var iy = qw * y + qz * x - qx * z;
  6474. var iz = qw * z + qx * y - qy * x;
  6475. var iw = - qx * x - qy * y - qz * z;
  6476. // calculate result * inverse quat
  6477. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6478. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6479. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6480. return this;
  6481. },
  6482. project: function ( camera ) {
  6483. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  6484. },
  6485. unproject: function () {
  6486. var matrix = new Matrix4();
  6487. return function unproject( camera ) {
  6488. return this.applyMatrix4( matrix.getInverse( camera.projectionMatrix ) ).applyMatrix4( camera.matrixWorld );
  6489. };
  6490. }(),
  6491. transformDirection: function ( m ) {
  6492. // input: THREE.Matrix4 affine matrix
  6493. // vector interpreted as a direction
  6494. var x = this.x, y = this.y, z = this.z;
  6495. var e = m.elements;
  6496. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6497. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6498. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6499. return this.normalize();
  6500. },
  6501. divide: function ( v ) {
  6502. this.x /= v.x;
  6503. this.y /= v.y;
  6504. this.z /= v.z;
  6505. return this;
  6506. },
  6507. divideScalar: function ( scalar ) {
  6508. return this.multiplyScalar( 1 / scalar );
  6509. },
  6510. min: function ( v ) {
  6511. this.x = Math.min( this.x, v.x );
  6512. this.y = Math.min( this.y, v.y );
  6513. this.z = Math.min( this.z, v.z );
  6514. return this;
  6515. },
  6516. max: function ( v ) {
  6517. this.x = Math.max( this.x, v.x );
  6518. this.y = Math.max( this.y, v.y );
  6519. this.z = Math.max( this.z, v.z );
  6520. return this;
  6521. },
  6522. clamp: function ( min, max ) {
  6523. // assumes min < max, componentwise
  6524. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6525. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6526. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6527. return this;
  6528. },
  6529. clampScalar: function () {
  6530. var min = new Vector3();
  6531. var max = new Vector3();
  6532. return function clampScalar( minVal, maxVal ) {
  6533. min.set( minVal, minVal, minVal );
  6534. max.set( maxVal, maxVal, maxVal );
  6535. return this.clamp( min, max );
  6536. };
  6537. }(),
  6538. clampLength: function ( min, max ) {
  6539. var length = this.length();
  6540. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6541. },
  6542. floor: function () {
  6543. this.x = Math.floor( this.x );
  6544. this.y = Math.floor( this.y );
  6545. this.z = Math.floor( this.z );
  6546. return this;
  6547. },
  6548. ceil: function () {
  6549. this.x = Math.ceil( this.x );
  6550. this.y = Math.ceil( this.y );
  6551. this.z = Math.ceil( this.z );
  6552. return this;
  6553. },
  6554. round: function () {
  6555. this.x = Math.round( this.x );
  6556. this.y = Math.round( this.y );
  6557. this.z = Math.round( this.z );
  6558. return this;
  6559. },
  6560. roundToZero: function () {
  6561. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6562. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6563. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6564. return this;
  6565. },
  6566. negate: function () {
  6567. this.x = - this.x;
  6568. this.y = - this.y;
  6569. this.z = - this.z;
  6570. return this;
  6571. },
  6572. dot: function ( v ) {
  6573. return this.x * v.x + this.y * v.y + this.z * v.z;
  6574. },
  6575. // TODO lengthSquared?
  6576. lengthSq: function () {
  6577. return this.x * this.x + this.y * this.y + this.z * this.z;
  6578. },
  6579. length: function () {
  6580. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6581. },
  6582. manhattanLength: function () {
  6583. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6584. },
  6585. normalize: function () {
  6586. return this.divideScalar( this.length() || 1 );
  6587. },
  6588. setLength: function ( length ) {
  6589. return this.normalize().multiplyScalar( length );
  6590. },
  6591. lerp: function ( v, alpha ) {
  6592. this.x += ( v.x - this.x ) * alpha;
  6593. this.y += ( v.y - this.y ) * alpha;
  6594. this.z += ( v.z - this.z ) * alpha;
  6595. return this;
  6596. },
  6597. lerpVectors: function ( v1, v2, alpha ) {
  6598. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6599. },
  6600. cross: function ( v, w ) {
  6601. if ( w !== undefined ) {
  6602. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6603. return this.crossVectors( v, w );
  6604. }
  6605. return this.crossVectors( this, v );
  6606. },
  6607. crossVectors: function ( a, b ) {
  6608. var ax = a.x, ay = a.y, az = a.z;
  6609. var bx = b.x, by = b.y, bz = b.z;
  6610. this.x = ay * bz - az * by;
  6611. this.y = az * bx - ax * bz;
  6612. this.z = ax * by - ay * bx;
  6613. return this;
  6614. },
  6615. projectOnVector: function ( vector ) {
  6616. var scalar = vector.dot( this ) / vector.lengthSq();
  6617. return this.copy( vector ).multiplyScalar( scalar );
  6618. },
  6619. projectOnPlane: function () {
  6620. var v1 = new Vector3();
  6621. return function projectOnPlane( planeNormal ) {
  6622. v1.copy( this ).projectOnVector( planeNormal );
  6623. return this.sub( v1 );
  6624. };
  6625. }(),
  6626. reflect: function () {
  6627. // reflect incident vector off plane orthogonal to normal
  6628. // normal is assumed to have unit length
  6629. var v1 = new Vector3();
  6630. return function reflect( normal ) {
  6631. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6632. };
  6633. }(),
  6634. angleTo: function ( v ) {
  6635. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6636. // clamp, to handle numerical problems
  6637. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6638. },
  6639. distanceTo: function ( v ) {
  6640. return Math.sqrt( this.distanceToSquared( v ) );
  6641. },
  6642. distanceToSquared: function ( v ) {
  6643. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6644. return dx * dx + dy * dy + dz * dz;
  6645. },
  6646. manhattanDistanceTo: function ( v ) {
  6647. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6648. },
  6649. setFromSpherical: function ( s ) {
  6650. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  6651. },
  6652. setFromSphericalCoords: function ( radius, phi, theta ) {
  6653. var sinPhiRadius = Math.sin( phi ) * radius;
  6654. this.x = sinPhiRadius * Math.sin( theta );
  6655. this.y = Math.cos( phi ) * radius;
  6656. this.z = sinPhiRadius * Math.cos( theta );
  6657. return this;
  6658. },
  6659. setFromCylindrical: function ( c ) {
  6660. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  6661. },
  6662. setFromCylindricalCoords: function ( radius, theta, y ) {
  6663. this.x = radius * Math.sin( theta );
  6664. this.y = y;
  6665. this.z = radius * Math.cos( theta );
  6666. return this;
  6667. },
  6668. setFromMatrixPosition: function ( m ) {
  6669. var e = m.elements;
  6670. this.x = e[ 12 ];
  6671. this.y = e[ 13 ];
  6672. this.z = e[ 14 ];
  6673. return this;
  6674. },
  6675. setFromMatrixScale: function ( m ) {
  6676. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6677. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6678. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6679. this.x = sx;
  6680. this.y = sy;
  6681. this.z = sz;
  6682. return this;
  6683. },
  6684. setFromMatrixColumn: function ( m, index ) {
  6685. return this.fromArray( m.elements, index * 4 );
  6686. },
  6687. equals: function ( v ) {
  6688. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6689. },
  6690. fromArray: function ( array, offset ) {
  6691. if ( offset === undefined ) offset = 0;
  6692. this.x = array[ offset ];
  6693. this.y = array[ offset + 1 ];
  6694. this.z = array[ offset + 2 ];
  6695. return this;
  6696. },
  6697. toArray: function ( array, offset ) {
  6698. if ( array === undefined ) array = [];
  6699. if ( offset === undefined ) offset = 0;
  6700. array[ offset ] = this.x;
  6701. array[ offset + 1 ] = this.y;
  6702. array[ offset + 2 ] = this.z;
  6703. return array;
  6704. },
  6705. fromBufferAttribute: function ( attribute, index, offset ) {
  6706. if ( offset !== undefined ) {
  6707. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6708. }
  6709. this.x = attribute.getX( index );
  6710. this.y = attribute.getY( index );
  6711. this.z = attribute.getZ( index );
  6712. return this;
  6713. }
  6714. } );
  6715. /**
  6716. * @author alteredq / http://alteredqualia.com/
  6717. * @author WestLangley / http://github.com/WestLangley
  6718. * @author bhouston / http://clara.io
  6719. * @author tschw
  6720. */
  6721. function Matrix3() {
  6722. this.elements = [
  6723. 1, 0, 0,
  6724. 0, 1, 0,
  6725. 0, 0, 1
  6726. ];
  6727. if ( arguments.length > 0 ) {
  6728. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6729. }
  6730. }
  6731. Object.assign( Matrix3.prototype, {
  6732. isMatrix3: true,
  6733. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6734. var te = this.elements;
  6735. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6736. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6737. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6738. return this;
  6739. },
  6740. identity: function () {
  6741. this.set(
  6742. 1, 0, 0,
  6743. 0, 1, 0,
  6744. 0, 0, 1
  6745. );
  6746. return this;
  6747. },
  6748. clone: function () {
  6749. return new this.constructor().fromArray( this.elements );
  6750. },
  6751. copy: function ( m ) {
  6752. var te = this.elements;
  6753. var me = m.elements;
  6754. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  6755. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  6756. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  6757. return this;
  6758. },
  6759. setFromMatrix4: function ( m ) {
  6760. var me = m.elements;
  6761. this.set(
  6762. me[ 0 ], me[ 4 ], me[ 8 ],
  6763. me[ 1 ], me[ 5 ], me[ 9 ],
  6764. me[ 2 ], me[ 6 ], me[ 10 ]
  6765. );
  6766. return this;
  6767. },
  6768. applyToBufferAttribute: function () {
  6769. var v1 = new Vector3();
  6770. return function applyToBufferAttribute( attribute ) {
  6771. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6772. v1.x = attribute.getX( i );
  6773. v1.y = attribute.getY( i );
  6774. v1.z = attribute.getZ( i );
  6775. v1.applyMatrix3( this );
  6776. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6777. }
  6778. return attribute;
  6779. };
  6780. }(),
  6781. multiply: function ( m ) {
  6782. return this.multiplyMatrices( this, m );
  6783. },
  6784. premultiply: function ( m ) {
  6785. return this.multiplyMatrices( m, this );
  6786. },
  6787. multiplyMatrices: function ( a, b ) {
  6788. var ae = a.elements;
  6789. var be = b.elements;
  6790. var te = this.elements;
  6791. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6792. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6793. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6794. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6795. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6796. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6797. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6798. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6799. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6800. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6801. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6802. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6803. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6804. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6805. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6806. return this;
  6807. },
  6808. multiplyScalar: function ( s ) {
  6809. var te = this.elements;
  6810. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6811. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6812. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6813. return this;
  6814. },
  6815. determinant: function () {
  6816. var te = this.elements;
  6817. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6818. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6819. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6820. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6821. },
  6822. getInverse: function ( matrix, throwOnDegenerate ) {
  6823. if ( matrix && matrix.isMatrix4 ) {
  6824. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  6825. }
  6826. var me = matrix.elements,
  6827. te = this.elements,
  6828. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6829. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6830. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6831. t11 = n33 * n22 - n32 * n23,
  6832. t12 = n32 * n13 - n33 * n12,
  6833. t13 = n23 * n12 - n22 * n13,
  6834. det = n11 * t11 + n21 * t12 + n31 * t13;
  6835. if ( det === 0 ) {
  6836. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  6837. if ( throwOnDegenerate === true ) {
  6838. throw new Error( msg );
  6839. } else {
  6840. console.warn( msg );
  6841. }
  6842. return this.identity();
  6843. }
  6844. var detInv = 1 / det;
  6845. te[ 0 ] = t11 * detInv;
  6846. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6847. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6848. te[ 3 ] = t12 * detInv;
  6849. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6850. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6851. te[ 6 ] = t13 * detInv;
  6852. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6853. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6854. return this;
  6855. },
  6856. transpose: function () {
  6857. var tmp, m = this.elements;
  6858. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6859. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6860. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6861. return this;
  6862. },
  6863. getNormalMatrix: function ( matrix4 ) {
  6864. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6865. },
  6866. transposeIntoArray: function ( r ) {
  6867. var m = this.elements;
  6868. r[ 0 ] = m[ 0 ];
  6869. r[ 1 ] = m[ 3 ];
  6870. r[ 2 ] = m[ 6 ];
  6871. r[ 3 ] = m[ 1 ];
  6872. r[ 4 ] = m[ 4 ];
  6873. r[ 5 ] = m[ 7 ];
  6874. r[ 6 ] = m[ 2 ];
  6875. r[ 7 ] = m[ 5 ];
  6876. r[ 8 ] = m[ 8 ];
  6877. return this;
  6878. },
  6879. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6880. var c = Math.cos( rotation );
  6881. var s = Math.sin( rotation );
  6882. this.set(
  6883. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6884. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6885. 0, 0, 1
  6886. );
  6887. },
  6888. scale: function ( sx, sy ) {
  6889. var te = this.elements;
  6890. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6891. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6892. return this;
  6893. },
  6894. rotate: function ( theta ) {
  6895. var c = Math.cos( theta );
  6896. var s = Math.sin( theta );
  6897. var te = this.elements;
  6898. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6899. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6900. te[ 0 ] = c * a11 + s * a21;
  6901. te[ 3 ] = c * a12 + s * a22;
  6902. te[ 6 ] = c * a13 + s * a23;
  6903. te[ 1 ] = - s * a11 + c * a21;
  6904. te[ 4 ] = - s * a12 + c * a22;
  6905. te[ 7 ] = - s * a13 + c * a23;
  6906. return this;
  6907. },
  6908. translate: function ( tx, ty ) {
  6909. var te = this.elements;
  6910. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6911. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6912. return this;
  6913. },
  6914. equals: function ( matrix ) {
  6915. var te = this.elements;
  6916. var me = matrix.elements;
  6917. for ( var i = 0; i < 9; i ++ ) {
  6918. if ( te[ i ] !== me[ i ] ) return false;
  6919. }
  6920. return true;
  6921. },
  6922. fromArray: function ( array, offset ) {
  6923. if ( offset === undefined ) offset = 0;
  6924. for ( var i = 0; i < 9; i ++ ) {
  6925. this.elements[ i ] = array[ i + offset ];
  6926. }
  6927. return this;
  6928. },
  6929. toArray: function ( array, offset ) {
  6930. if ( array === undefined ) array = [];
  6931. if ( offset === undefined ) offset = 0;
  6932. var te = this.elements;
  6933. array[ offset ] = te[ 0 ];
  6934. array[ offset + 1 ] = te[ 1 ];
  6935. array[ offset + 2 ] = te[ 2 ];
  6936. array[ offset + 3 ] = te[ 3 ];
  6937. array[ offset + 4 ] = te[ 4 ];
  6938. array[ offset + 5 ] = te[ 5 ];
  6939. array[ offset + 6 ] = te[ 6 ];
  6940. array[ offset + 7 ] = te[ 7 ];
  6941. array[ offset + 8 ] = te[ 8 ];
  6942. return array;
  6943. }
  6944. } );
  6945. /**
  6946. * @author mrdoob / http://mrdoob.com/
  6947. * @author alteredq / http://alteredqualia.com/
  6948. * @author szimek / https://github.com/szimek/
  6949. */
  6950. var _canvas;
  6951. var ImageUtils = {
  6952. getDataURL: function ( image ) {
  6953. var canvas;
  6954. if ( typeof HTMLCanvasElement == 'undefined' ) {
  6955. return image.src;
  6956. } else if ( image instanceof HTMLCanvasElement ) {
  6957. canvas = image;
  6958. } else {
  6959. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  6960. _canvas.width = image.width;
  6961. _canvas.height = image.height;
  6962. var context = _canvas.getContext( '2d' );
  6963. if ( image instanceof ImageData ) {
  6964. context.putImageData( image, 0, 0 );
  6965. } else {
  6966. context.drawImage( image, 0, 0, image.width, image.height );
  6967. }
  6968. canvas = _canvas;
  6969. }
  6970. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6971. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6972. } else {
  6973. return canvas.toDataURL( 'image/png' );
  6974. }
  6975. }
  6976. };
  6977. /**
  6978. * @author mrdoob / http://mrdoob.com/
  6979. * @author alteredq / http://alteredqualia.com/
  6980. * @author szimek / https://github.com/szimek/
  6981. */
  6982. var textureId = 0;
  6983. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6984. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6985. this.uuid = _Math.generateUUID();
  6986. this.name = '';
  6987. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6988. this.mipmaps = [];
  6989. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6990. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6991. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6992. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6993. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  6994. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6995. this.format = format !== undefined ? format : RGBAFormat;
  6996. this.type = type !== undefined ? type : UnsignedByteType;
  6997. this.offset = new Vector2( 0, 0 );
  6998. this.repeat = new Vector2( 1, 1 );
  6999. this.center = new Vector2( 0, 0 );
  7000. this.rotation = 0;
  7001. this.matrixAutoUpdate = true;
  7002. this.matrix = new Matrix3();
  7003. this.generateMipmaps = true;
  7004. this.premultiplyAlpha = false;
  7005. this.flipY = true;
  7006. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7007. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  7008. //
  7009. // Also changing the encoding after already used by a Material will not automatically make the Material
  7010. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  7011. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  7012. this.version = 0;
  7013. this.onUpdate = null;
  7014. }
  7015. Texture.DEFAULT_IMAGE = undefined;
  7016. Texture.DEFAULT_MAPPING = UVMapping;
  7017. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7018. constructor: Texture,
  7019. isTexture: true,
  7020. updateMatrix: function () {
  7021. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  7022. },
  7023. clone: function () {
  7024. return new this.constructor().copy( this );
  7025. },
  7026. copy: function ( source ) {
  7027. this.name = source.name;
  7028. this.image = source.image;
  7029. this.mipmaps = source.mipmaps.slice( 0 );
  7030. this.mapping = source.mapping;
  7031. this.wrapS = source.wrapS;
  7032. this.wrapT = source.wrapT;
  7033. this.magFilter = source.magFilter;
  7034. this.minFilter = source.minFilter;
  7035. this.anisotropy = source.anisotropy;
  7036. this.format = source.format;
  7037. this.type = source.type;
  7038. this.offset.copy( source.offset );
  7039. this.repeat.copy( source.repeat );
  7040. this.center.copy( source.center );
  7041. this.rotation = source.rotation;
  7042. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7043. this.matrix.copy( source.matrix );
  7044. this.generateMipmaps = source.generateMipmaps;
  7045. this.premultiplyAlpha = source.premultiplyAlpha;
  7046. this.flipY = source.flipY;
  7047. this.unpackAlignment = source.unpackAlignment;
  7048. this.encoding = source.encoding;
  7049. return this;
  7050. },
  7051. toJSON: function ( meta ) {
  7052. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  7053. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  7054. return meta.textures[ this.uuid ];
  7055. }
  7056. var output = {
  7057. metadata: {
  7058. version: 4.5,
  7059. type: 'Texture',
  7060. generator: 'Texture.toJSON'
  7061. },
  7062. uuid: this.uuid,
  7063. name: this.name,
  7064. mapping: this.mapping,
  7065. repeat: [ this.repeat.x, this.repeat.y ],
  7066. offset: [ this.offset.x, this.offset.y ],
  7067. center: [ this.center.x, this.center.y ],
  7068. rotation: this.rotation,
  7069. wrap: [ this.wrapS, this.wrapT ],
  7070. format: this.format,
  7071. type: this.type,
  7072. encoding: this.encoding,
  7073. minFilter: this.minFilter,
  7074. magFilter: this.magFilter,
  7075. anisotropy: this.anisotropy,
  7076. flipY: this.flipY,
  7077. premultiplyAlpha: this.premultiplyAlpha,
  7078. unpackAlignment: this.unpackAlignment
  7079. };
  7080. if ( this.image !== undefined ) {
  7081. // TODO: Move to THREE.Image
  7082. var image = this.image;
  7083. if ( image.uuid === undefined ) {
  7084. image.uuid = _Math.generateUUID(); // UGH
  7085. }
  7086. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  7087. var url;
  7088. if ( Array.isArray( image ) ) {
  7089. // process array of images e.g. CubeTexture
  7090. url = [];
  7091. for ( var i = 0, l = image.length; i < l; i ++ ) {
  7092. url.push( ImageUtils.getDataURL( image[ i ] ) );
  7093. }
  7094. } else {
  7095. // process single image
  7096. url = ImageUtils.getDataURL( image );
  7097. }
  7098. meta.images[ image.uuid ] = {
  7099. uuid: image.uuid,
  7100. url: url
  7101. };
  7102. }
  7103. output.image = image.uuid;
  7104. }
  7105. if ( ! isRootObject ) {
  7106. meta.textures[ this.uuid ] = output;
  7107. }
  7108. return output;
  7109. },
  7110. dispose: function () {
  7111. this.dispatchEvent( { type: 'dispose' } );
  7112. },
  7113. transformUv: function ( uv ) {
  7114. if ( this.mapping !== UVMapping ) return uv;
  7115. uv.applyMatrix3( this.matrix );
  7116. if ( uv.x < 0 || uv.x > 1 ) {
  7117. switch ( this.wrapS ) {
  7118. case RepeatWrapping:
  7119. uv.x = uv.x - Math.floor( uv.x );
  7120. break;
  7121. case ClampToEdgeWrapping:
  7122. uv.x = uv.x < 0 ? 0 : 1;
  7123. break;
  7124. case MirroredRepeatWrapping:
  7125. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  7126. uv.x = Math.ceil( uv.x ) - uv.x;
  7127. } else {
  7128. uv.x = uv.x - Math.floor( uv.x );
  7129. }
  7130. break;
  7131. }
  7132. }
  7133. if ( uv.y < 0 || uv.y > 1 ) {
  7134. switch ( this.wrapT ) {
  7135. case RepeatWrapping:
  7136. uv.y = uv.y - Math.floor( uv.y );
  7137. break;
  7138. case ClampToEdgeWrapping:
  7139. uv.y = uv.y < 0 ? 0 : 1;
  7140. break;
  7141. case MirroredRepeatWrapping:
  7142. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  7143. uv.y = Math.ceil( uv.y ) - uv.y;
  7144. } else {
  7145. uv.y = uv.y - Math.floor( uv.y );
  7146. }
  7147. break;
  7148. }
  7149. }
  7150. if ( this.flipY ) {
  7151. uv.y = 1 - uv.y;
  7152. }
  7153. return uv;
  7154. }
  7155. } );
  7156. Object.defineProperty( Texture.prototype, "needsUpdate", {
  7157. set: function ( value ) {
  7158. if ( value === true ) this.version ++;
  7159. }
  7160. } );
  7161. /**
  7162. * @author supereggbert / http://www.paulbrunt.co.uk/
  7163. * @author philogb / http://blog.thejit.org/
  7164. * @author mikael emtinger / http://gomo.se/
  7165. * @author egraether / http://egraether.com/
  7166. * @author WestLangley / http://github.com/WestLangley
  7167. */
  7168. function Vector4( x, y, z, w ) {
  7169. this.x = x || 0;
  7170. this.y = y || 0;
  7171. this.z = z || 0;
  7172. this.w = ( w !== undefined ) ? w : 1;
  7173. }
  7174. Object.assign( Vector4.prototype, {
  7175. isVector4: true,
  7176. set: function ( x, y, z, w ) {
  7177. this.x = x;
  7178. this.y = y;
  7179. this.z = z;
  7180. this.w = w;
  7181. return this;
  7182. },
  7183. setScalar: function ( scalar ) {
  7184. this.x = scalar;
  7185. this.y = scalar;
  7186. this.z = scalar;
  7187. this.w = scalar;
  7188. return this;
  7189. },
  7190. setX: function ( x ) {
  7191. this.x = x;
  7192. return this;
  7193. },
  7194. setY: function ( y ) {
  7195. this.y = y;
  7196. return this;
  7197. },
  7198. setZ: function ( z ) {
  7199. this.z = z;
  7200. return this;
  7201. },
  7202. setW: function ( w ) {
  7203. this.w = w;
  7204. return this;
  7205. },
  7206. setComponent: function ( index, value ) {
  7207. switch ( index ) {
  7208. case 0: this.x = value; break;
  7209. case 1: this.y = value; break;
  7210. case 2: this.z = value; break;
  7211. case 3: this.w = value; break;
  7212. default: throw new Error( 'index is out of range: ' + index );
  7213. }
  7214. return this;
  7215. },
  7216. getComponent: function ( index ) {
  7217. switch ( index ) {
  7218. case 0: return this.x;
  7219. case 1: return this.y;
  7220. case 2: return this.z;
  7221. case 3: return this.w;
  7222. default: throw new Error( 'index is out of range: ' + index );
  7223. }
  7224. },
  7225. clone: function () {
  7226. return new this.constructor( this.x, this.y, this.z, this.w );
  7227. },
  7228. copy: function ( v ) {
  7229. this.x = v.x;
  7230. this.y = v.y;
  7231. this.z = v.z;
  7232. this.w = ( v.w !== undefined ) ? v.w : 1;
  7233. return this;
  7234. },
  7235. add: function ( v, w ) {
  7236. if ( w !== undefined ) {
  7237. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  7238. return this.addVectors( v, w );
  7239. }
  7240. this.x += v.x;
  7241. this.y += v.y;
  7242. this.z += v.z;
  7243. this.w += v.w;
  7244. return this;
  7245. },
  7246. addScalar: function ( s ) {
  7247. this.x += s;
  7248. this.y += s;
  7249. this.z += s;
  7250. this.w += s;
  7251. return this;
  7252. },
  7253. addVectors: function ( a, b ) {
  7254. this.x = a.x + b.x;
  7255. this.y = a.y + b.y;
  7256. this.z = a.z + b.z;
  7257. this.w = a.w + b.w;
  7258. return this;
  7259. },
  7260. addScaledVector: function ( v, s ) {
  7261. this.x += v.x * s;
  7262. this.y += v.y * s;
  7263. this.z += v.z * s;
  7264. this.w += v.w * s;
  7265. return this;
  7266. },
  7267. sub: function ( v, w ) {
  7268. if ( w !== undefined ) {
  7269. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  7270. return this.subVectors( v, w );
  7271. }
  7272. this.x -= v.x;
  7273. this.y -= v.y;
  7274. this.z -= v.z;
  7275. this.w -= v.w;
  7276. return this;
  7277. },
  7278. subScalar: function ( s ) {
  7279. this.x -= s;
  7280. this.y -= s;
  7281. this.z -= s;
  7282. this.w -= s;
  7283. return this;
  7284. },
  7285. subVectors: function ( a, b ) {
  7286. this.x = a.x - b.x;
  7287. this.y = a.y - b.y;
  7288. this.z = a.z - b.z;
  7289. this.w = a.w - b.w;
  7290. return this;
  7291. },
  7292. multiplyScalar: function ( scalar ) {
  7293. this.x *= scalar;
  7294. this.y *= scalar;
  7295. this.z *= scalar;
  7296. this.w *= scalar;
  7297. return this;
  7298. },
  7299. applyMatrix4: function ( m ) {
  7300. var x = this.x, y = this.y, z = this.z, w = this.w;
  7301. var e = m.elements;
  7302. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  7303. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  7304. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  7305. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  7306. return this;
  7307. },
  7308. divideScalar: function ( scalar ) {
  7309. return this.multiplyScalar( 1 / scalar );
  7310. },
  7311. setAxisAngleFromQuaternion: function ( q ) {
  7312. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  7313. // q is assumed to be normalized
  7314. this.w = 2 * Math.acos( q.w );
  7315. var s = Math.sqrt( 1 - q.w * q.w );
  7316. if ( s < 0.0001 ) {
  7317. this.x = 1;
  7318. this.y = 0;
  7319. this.z = 0;
  7320. } else {
  7321. this.x = q.x / s;
  7322. this.y = q.y / s;
  7323. this.z = q.z / s;
  7324. }
  7325. return this;
  7326. },
  7327. setAxisAngleFromRotationMatrix: function ( m ) {
  7328. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  7329. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7330. var angle, x, y, z, // variables for result
  7331. epsilon = 0.01, // margin to allow for rounding errors
  7332. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  7333. te = m.elements,
  7334. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  7335. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  7336. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7337. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  7338. ( Math.abs( m13 - m31 ) < epsilon ) &&
  7339. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  7340. // singularity found
  7341. // first check for identity matrix which must have +1 for all terms
  7342. // in leading diagonal and zero in other terms
  7343. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  7344. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  7345. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  7346. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  7347. // this singularity is identity matrix so angle = 0
  7348. this.set( 1, 0, 0, 0 );
  7349. return this; // zero angle, arbitrary axis
  7350. }
  7351. // otherwise this singularity is angle = 180
  7352. angle = Math.PI;
  7353. var xx = ( m11 + 1 ) / 2;
  7354. var yy = ( m22 + 1 ) / 2;
  7355. var zz = ( m33 + 1 ) / 2;
  7356. var xy = ( m12 + m21 ) / 4;
  7357. var xz = ( m13 + m31 ) / 4;
  7358. var yz = ( m23 + m32 ) / 4;
  7359. if ( ( xx > yy ) && ( xx > zz ) ) {
  7360. // m11 is the largest diagonal term
  7361. if ( xx < epsilon ) {
  7362. x = 0;
  7363. y = 0.707106781;
  7364. z = 0.707106781;
  7365. } else {
  7366. x = Math.sqrt( xx );
  7367. y = xy / x;
  7368. z = xz / x;
  7369. }
  7370. } else if ( yy > zz ) {
  7371. // m22 is the largest diagonal term
  7372. if ( yy < epsilon ) {
  7373. x = 0.707106781;
  7374. y = 0;
  7375. z = 0.707106781;
  7376. } else {
  7377. y = Math.sqrt( yy );
  7378. x = xy / y;
  7379. z = yz / y;
  7380. }
  7381. } else {
  7382. // m33 is the largest diagonal term so base result on this
  7383. if ( zz < epsilon ) {
  7384. x = 0.707106781;
  7385. y = 0.707106781;
  7386. z = 0;
  7387. } else {
  7388. z = Math.sqrt( zz );
  7389. x = xz / z;
  7390. y = yz / z;
  7391. }
  7392. }
  7393. this.set( x, y, z, angle );
  7394. return this; // return 180 deg rotation
  7395. }
  7396. // as we have reached here there are no singularities so we can handle normally
  7397. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  7398. ( m13 - m31 ) * ( m13 - m31 ) +
  7399. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  7400. if ( Math.abs( s ) < 0.001 ) s = 1;
  7401. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7402. // caught by singularity test above, but I've left it in just in case
  7403. this.x = ( m32 - m23 ) / s;
  7404. this.y = ( m13 - m31 ) / s;
  7405. this.z = ( m21 - m12 ) / s;
  7406. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  7407. return this;
  7408. },
  7409. min: function ( v ) {
  7410. this.x = Math.min( this.x, v.x );
  7411. this.y = Math.min( this.y, v.y );
  7412. this.z = Math.min( this.z, v.z );
  7413. this.w = Math.min( this.w, v.w );
  7414. return this;
  7415. },
  7416. max: function ( v ) {
  7417. this.x = Math.max( this.x, v.x );
  7418. this.y = Math.max( this.y, v.y );
  7419. this.z = Math.max( this.z, v.z );
  7420. this.w = Math.max( this.w, v.w );
  7421. return this;
  7422. },
  7423. clamp: function ( min, max ) {
  7424. // assumes min < max, componentwise
  7425. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7426. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7427. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7428. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  7429. return this;
  7430. },
  7431. clampScalar: function () {
  7432. var min, max;
  7433. return function clampScalar( minVal, maxVal ) {
  7434. if ( min === undefined ) {
  7435. min = new Vector4();
  7436. max = new Vector4();
  7437. }
  7438. min.set( minVal, minVal, minVal, minVal );
  7439. max.set( maxVal, maxVal, maxVal, maxVal );
  7440. return this.clamp( min, max );
  7441. };
  7442. }(),
  7443. clampLength: function ( min, max ) {
  7444. var length = this.length();
  7445. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7446. },
  7447. floor: function () {
  7448. this.x = Math.floor( this.x );
  7449. this.y = Math.floor( this.y );
  7450. this.z = Math.floor( this.z );
  7451. this.w = Math.floor( this.w );
  7452. return this;
  7453. },
  7454. ceil: function () {
  7455. this.x = Math.ceil( this.x );
  7456. this.y = Math.ceil( this.y );
  7457. this.z = Math.ceil( this.z );
  7458. this.w = Math.ceil( this.w );
  7459. return this;
  7460. },
  7461. round: function () {
  7462. this.x = Math.round( this.x );
  7463. this.y = Math.round( this.y );
  7464. this.z = Math.round( this.z );
  7465. this.w = Math.round( this.w );
  7466. return this;
  7467. },
  7468. roundToZero: function () {
  7469. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7470. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7471. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7472. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7473. return this;
  7474. },
  7475. negate: function () {
  7476. this.x = - this.x;
  7477. this.y = - this.y;
  7478. this.z = - this.z;
  7479. this.w = - this.w;
  7480. return this;
  7481. },
  7482. dot: function ( v ) {
  7483. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7484. },
  7485. lengthSq: function () {
  7486. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7487. },
  7488. length: function () {
  7489. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7490. },
  7491. manhattanLength: function () {
  7492. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7493. },
  7494. normalize: function () {
  7495. return this.divideScalar( this.length() || 1 );
  7496. },
  7497. setLength: function ( length ) {
  7498. return this.normalize().multiplyScalar( length );
  7499. },
  7500. lerp: function ( v, alpha ) {
  7501. this.x += ( v.x - this.x ) * alpha;
  7502. this.y += ( v.y - this.y ) * alpha;
  7503. this.z += ( v.z - this.z ) * alpha;
  7504. this.w += ( v.w - this.w ) * alpha;
  7505. return this;
  7506. },
  7507. lerpVectors: function ( v1, v2, alpha ) {
  7508. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7509. },
  7510. equals: function ( v ) {
  7511. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7512. },
  7513. fromArray: function ( array, offset ) {
  7514. if ( offset === undefined ) offset = 0;
  7515. this.x = array[ offset ];
  7516. this.y = array[ offset + 1 ];
  7517. this.z = array[ offset + 2 ];
  7518. this.w = array[ offset + 3 ];
  7519. return this;
  7520. },
  7521. toArray: function ( array, offset ) {
  7522. if ( array === undefined ) array = [];
  7523. if ( offset === undefined ) offset = 0;
  7524. array[ offset ] = this.x;
  7525. array[ offset + 1 ] = this.y;
  7526. array[ offset + 2 ] = this.z;
  7527. array[ offset + 3 ] = this.w;
  7528. return array;
  7529. },
  7530. fromBufferAttribute: function ( attribute, index, offset ) {
  7531. if ( offset !== undefined ) {
  7532. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7533. }
  7534. this.x = attribute.getX( index );
  7535. this.y = attribute.getY( index );
  7536. this.z = attribute.getZ( index );
  7537. this.w = attribute.getW( index );
  7538. return this;
  7539. }
  7540. } );
  7541. /**
  7542. * @author szimek / https://github.com/szimek/
  7543. * @author alteredq / http://alteredqualia.com/
  7544. * @author Marius Kintel / https://github.com/kintel
  7545. */
  7546. /*
  7547. In options, we can specify:
  7548. * Texture parameters for an auto-generated target texture
  7549. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7550. */
  7551. function WebGLRenderTarget( width, height, options ) {
  7552. this.width = width;
  7553. this.height = height;
  7554. this.scissor = new Vector4( 0, 0, width, height );
  7555. this.scissorTest = false;
  7556. this.viewport = new Vector4( 0, 0, width, height );
  7557. options = options || {};
  7558. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7559. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7560. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7561. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7562. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7563. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7564. }
  7565. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7566. constructor: WebGLRenderTarget,
  7567. isWebGLRenderTarget: true,
  7568. setSize: function ( width, height ) {
  7569. if ( this.width !== width || this.height !== height ) {
  7570. this.width = width;
  7571. this.height = height;
  7572. this.dispose();
  7573. }
  7574. this.viewport.set( 0, 0, width, height );
  7575. this.scissor.set( 0, 0, width, height );
  7576. },
  7577. clone: function () {
  7578. return new this.constructor().copy( this );
  7579. },
  7580. copy: function ( source ) {
  7581. this.width = source.width;
  7582. this.height = source.height;
  7583. this.viewport.copy( source.viewport );
  7584. this.texture = source.texture.clone();
  7585. this.depthBuffer = source.depthBuffer;
  7586. this.stencilBuffer = source.stencilBuffer;
  7587. this.depthTexture = source.depthTexture;
  7588. return this;
  7589. },
  7590. dispose: function () {
  7591. this.dispatchEvent( { type: 'dispose' } );
  7592. }
  7593. } );
  7594. /**
  7595. * @author Mugen87 / https://github.com/Mugen87
  7596. * @author Matt DesLauriers / @mattdesl
  7597. */
  7598. function WebGLMultisampleRenderTarget( width, height, options ) {
  7599. WebGLRenderTarget.call( this, width, height, options );
  7600. this.samples = 4;
  7601. }
  7602. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  7603. constructor: WebGLMultisampleRenderTarget,
  7604. isWebGLMultisampleRenderTarget: true,
  7605. copy: function ( source ) {
  7606. WebGLRenderTarget.prototype.copy.call( this, source );
  7607. this.samples = source.samples;
  7608. return this;
  7609. }
  7610. } );
  7611. /**
  7612. * @author alteredq / http://alteredqualia.com
  7613. */
  7614. function WebGLRenderTargetCube( width, height, options ) {
  7615. WebGLRenderTarget.call( this, width, height, options );
  7616. }
  7617. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  7618. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  7619. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  7620. /**
  7621. * @author alteredq / http://alteredqualia.com/
  7622. */
  7623. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7624. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7625. this.image = { data: data, width: width, height: height };
  7626. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7627. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7628. this.generateMipmaps = false;
  7629. this.flipY = false;
  7630. this.unpackAlignment = 1;
  7631. }
  7632. DataTexture.prototype = Object.create( Texture.prototype );
  7633. DataTexture.prototype.constructor = DataTexture;
  7634. DataTexture.prototype.isDataTexture = true;
  7635. /**
  7636. * @author bhouston / http://clara.io
  7637. * @author WestLangley / http://github.com/WestLangley
  7638. */
  7639. function Box3( min, max ) {
  7640. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  7641. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  7642. }
  7643. Object.assign( Box3.prototype, {
  7644. isBox3: true,
  7645. set: function ( min, max ) {
  7646. this.min.copy( min );
  7647. this.max.copy( max );
  7648. return this;
  7649. },
  7650. setFromArray: function ( array ) {
  7651. var minX = + Infinity;
  7652. var minY = + Infinity;
  7653. var minZ = + Infinity;
  7654. var maxX = - Infinity;
  7655. var maxY = - Infinity;
  7656. var maxZ = - Infinity;
  7657. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  7658. var x = array[ i ];
  7659. var y = array[ i + 1 ];
  7660. var z = array[ i + 2 ];
  7661. if ( x < minX ) minX = x;
  7662. if ( y < minY ) minY = y;
  7663. if ( z < minZ ) minZ = z;
  7664. if ( x > maxX ) maxX = x;
  7665. if ( y > maxY ) maxY = y;
  7666. if ( z > maxZ ) maxZ = z;
  7667. }
  7668. this.min.set( minX, minY, minZ );
  7669. this.max.set( maxX, maxY, maxZ );
  7670. return this;
  7671. },
  7672. setFromBufferAttribute: function ( attribute ) {
  7673. var minX = + Infinity;
  7674. var minY = + Infinity;
  7675. var minZ = + Infinity;
  7676. var maxX = - Infinity;
  7677. var maxY = - Infinity;
  7678. var maxZ = - Infinity;
  7679. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  7680. var x = attribute.getX( i );
  7681. var y = attribute.getY( i );
  7682. var z = attribute.getZ( i );
  7683. if ( x < minX ) minX = x;
  7684. if ( y < minY ) minY = y;
  7685. if ( z < minZ ) minZ = z;
  7686. if ( x > maxX ) maxX = x;
  7687. if ( y > maxY ) maxY = y;
  7688. if ( z > maxZ ) maxZ = z;
  7689. }
  7690. this.min.set( minX, minY, minZ );
  7691. this.max.set( maxX, maxY, maxZ );
  7692. return this;
  7693. },
  7694. setFromPoints: function ( points ) {
  7695. this.makeEmpty();
  7696. for ( var i = 0, il = points.length; i < il; i ++ ) {
  7697. this.expandByPoint( points[ i ] );
  7698. }
  7699. return this;
  7700. },
  7701. setFromCenterAndSize: function () {
  7702. var v1 = new Vector3();
  7703. return function setFromCenterAndSize( center, size ) {
  7704. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  7705. this.min.copy( center ).sub( halfSize );
  7706. this.max.copy( center ).add( halfSize );
  7707. return this;
  7708. };
  7709. }(),
  7710. setFromObject: function ( object ) {
  7711. this.makeEmpty();
  7712. return this.expandByObject( object );
  7713. },
  7714. clone: function () {
  7715. return new this.constructor().copy( this );
  7716. },
  7717. copy: function ( box ) {
  7718. this.min.copy( box.min );
  7719. this.max.copy( box.max );
  7720. return this;
  7721. },
  7722. makeEmpty: function () {
  7723. this.min.x = this.min.y = this.min.z = + Infinity;
  7724. this.max.x = this.max.y = this.max.z = - Infinity;
  7725. return this;
  7726. },
  7727. isEmpty: function () {
  7728. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7729. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7730. },
  7731. getCenter: function ( target ) {
  7732. if ( target === undefined ) {
  7733. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  7734. target = new Vector3();
  7735. }
  7736. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7737. },
  7738. getSize: function ( target ) {
  7739. if ( target === undefined ) {
  7740. console.warn( 'THREE.Box3: .getSize() target is now required' );
  7741. target = new Vector3();
  7742. }
  7743. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7744. },
  7745. expandByPoint: function ( point ) {
  7746. this.min.min( point );
  7747. this.max.max( point );
  7748. return this;
  7749. },
  7750. expandByVector: function ( vector ) {
  7751. this.min.sub( vector );
  7752. this.max.add( vector );
  7753. return this;
  7754. },
  7755. expandByScalar: function ( scalar ) {
  7756. this.min.addScalar( - scalar );
  7757. this.max.addScalar( scalar );
  7758. return this;
  7759. },
  7760. expandByObject: function () {
  7761. // Computes the world-axis-aligned bounding box of an object (including its children),
  7762. // accounting for both the object's, and children's, world transforms
  7763. var scope, i, l;
  7764. var v1 = new Vector3();
  7765. function traverse( node ) {
  7766. var geometry = node.geometry;
  7767. if ( geometry !== undefined ) {
  7768. if ( geometry.isGeometry ) {
  7769. var vertices = geometry.vertices;
  7770. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  7771. v1.copy( vertices[ i ] );
  7772. v1.applyMatrix4( node.matrixWorld );
  7773. scope.expandByPoint( v1 );
  7774. }
  7775. } else if ( geometry.isBufferGeometry ) {
  7776. var attribute = geometry.attributes.position;
  7777. if ( attribute !== undefined ) {
  7778. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  7779. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  7780. scope.expandByPoint( v1 );
  7781. }
  7782. }
  7783. }
  7784. }
  7785. }
  7786. return function expandByObject( object ) {
  7787. scope = this;
  7788. object.updateMatrixWorld( true );
  7789. object.traverse( traverse );
  7790. return this;
  7791. };
  7792. }(),
  7793. containsPoint: function ( point ) {
  7794. return point.x < this.min.x || point.x > this.max.x ||
  7795. point.y < this.min.y || point.y > this.max.y ||
  7796. point.z < this.min.z || point.z > this.max.z ? false : true;
  7797. },
  7798. containsBox: function ( box ) {
  7799. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7800. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7801. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7802. },
  7803. getParameter: function ( point, target ) {
  7804. // This can potentially have a divide by zero if the box
  7805. // has a size dimension of 0.
  7806. if ( target === undefined ) {
  7807. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  7808. target = new Vector3();
  7809. }
  7810. return target.set(
  7811. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7812. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7813. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7814. );
  7815. },
  7816. intersectsBox: function ( box ) {
  7817. // using 6 splitting planes to rule out intersections.
  7818. return box.max.x < this.min.x || box.min.x > this.max.x ||
  7819. box.max.y < this.min.y || box.min.y > this.max.y ||
  7820. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  7821. },
  7822. intersectsSphere: ( function () {
  7823. var closestPoint = new Vector3();
  7824. return function intersectsSphere( sphere ) {
  7825. // Find the point on the AABB closest to the sphere center.
  7826. this.clampPoint( sphere.center, closestPoint );
  7827. // If that point is inside the sphere, the AABB and sphere intersect.
  7828. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7829. };
  7830. } )(),
  7831. intersectsPlane: function ( plane ) {
  7832. // We compute the minimum and maximum dot product values. If those values
  7833. // are on the same side (back or front) of the plane, then there is no intersection.
  7834. var min, max;
  7835. if ( plane.normal.x > 0 ) {
  7836. min = plane.normal.x * this.min.x;
  7837. max = plane.normal.x * this.max.x;
  7838. } else {
  7839. min = plane.normal.x * this.max.x;
  7840. max = plane.normal.x * this.min.x;
  7841. }
  7842. if ( plane.normal.y > 0 ) {
  7843. min += plane.normal.y * this.min.y;
  7844. max += plane.normal.y * this.max.y;
  7845. } else {
  7846. min += plane.normal.y * this.max.y;
  7847. max += plane.normal.y * this.min.y;
  7848. }
  7849. if ( plane.normal.z > 0 ) {
  7850. min += plane.normal.z * this.min.z;
  7851. max += plane.normal.z * this.max.z;
  7852. } else {
  7853. min += plane.normal.z * this.max.z;
  7854. max += plane.normal.z * this.min.z;
  7855. }
  7856. return ( min <= - plane.constant && max >= - plane.constant );
  7857. },
  7858. intersectsTriangle: ( function () {
  7859. // triangle centered vertices
  7860. var v0 = new Vector3();
  7861. var v1 = new Vector3();
  7862. var v2 = new Vector3();
  7863. // triangle edge vectors
  7864. var f0 = new Vector3();
  7865. var f1 = new Vector3();
  7866. var f2 = new Vector3();
  7867. var testAxis = new Vector3();
  7868. var center = new Vector3();
  7869. var extents = new Vector3();
  7870. var triangleNormal = new Vector3();
  7871. function satForAxes( axes ) {
  7872. var i, j;
  7873. for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7874. testAxis.fromArray( axes, i );
  7875. // project the aabb onto the seperating axis
  7876. var r = extents.x * Math.abs( testAxis.x ) + extents.y * Math.abs( testAxis.y ) + extents.z * Math.abs( testAxis.z );
  7877. // project all 3 vertices of the triangle onto the seperating axis
  7878. var p0 = v0.dot( testAxis );
  7879. var p1 = v1.dot( testAxis );
  7880. var p2 = v2.dot( testAxis );
  7881. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7882. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7883. // points of the projected triangle are outside the projected half-length of the aabb
  7884. // the axis is seperating and we can exit
  7885. return false;
  7886. }
  7887. }
  7888. return true;
  7889. }
  7890. return function intersectsTriangle( triangle ) {
  7891. if ( this.isEmpty() ) {
  7892. return false;
  7893. }
  7894. // compute box center and extents
  7895. this.getCenter( center );
  7896. extents.subVectors( this.max, center );
  7897. // translate triangle to aabb origin
  7898. v0.subVectors( triangle.a, center );
  7899. v1.subVectors( triangle.b, center );
  7900. v2.subVectors( triangle.c, center );
  7901. // compute edge vectors for triangle
  7902. f0.subVectors( v1, v0 );
  7903. f1.subVectors( v2, v1 );
  7904. f2.subVectors( v0, v2 );
  7905. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7906. // 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
  7907. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7908. var axes = [
  7909. 0, - f0.z, f0.y, 0, - f1.z, f1.y, 0, - f2.z, f2.y,
  7910. f0.z, 0, - f0.x, f1.z, 0, - f1.x, f2.z, 0, - f2.x,
  7911. - f0.y, f0.x, 0, - f1.y, f1.x, 0, - f2.y, f2.x, 0
  7912. ];
  7913. if ( ! satForAxes( axes ) ) {
  7914. return false;
  7915. }
  7916. // test 3 face normals from the aabb
  7917. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7918. if ( ! satForAxes( axes ) ) {
  7919. return false;
  7920. }
  7921. // finally testing the face normal of the triangle
  7922. // use already existing triangle edge vectors here
  7923. triangleNormal.crossVectors( f0, f1 );
  7924. axes = [ triangleNormal.x, triangleNormal.y, triangleNormal.z ];
  7925. return satForAxes( axes );
  7926. };
  7927. } )(),
  7928. clampPoint: function ( point, target ) {
  7929. if ( target === undefined ) {
  7930. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  7931. target = new Vector3();
  7932. }
  7933. return target.copy( point ).clamp( this.min, this.max );
  7934. },
  7935. distanceToPoint: function () {
  7936. var v1 = new Vector3();
  7937. return function distanceToPoint( point ) {
  7938. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  7939. return clampedPoint.sub( point ).length();
  7940. };
  7941. }(),
  7942. getBoundingSphere: function () {
  7943. var v1 = new Vector3();
  7944. return function getBoundingSphere( target ) {
  7945. if ( target === undefined ) {
  7946. console.warn( 'THREE.Box3: .getBoundingSphere() target is now required' );
  7947. target = new Sphere();
  7948. }
  7949. this.getCenter( target.center );
  7950. target.radius = this.getSize( v1 ).length() * 0.5;
  7951. return target;
  7952. };
  7953. }(),
  7954. intersect: function ( box ) {
  7955. this.min.max( box.min );
  7956. this.max.min( box.max );
  7957. // 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.
  7958. if ( this.isEmpty() ) this.makeEmpty();
  7959. return this;
  7960. },
  7961. union: function ( box ) {
  7962. this.min.min( box.min );
  7963. this.max.max( box.max );
  7964. return this;
  7965. },
  7966. applyMatrix4: function () {
  7967. var points = [
  7968. new Vector3(),
  7969. new Vector3(),
  7970. new Vector3(),
  7971. new Vector3(),
  7972. new Vector3(),
  7973. new Vector3(),
  7974. new Vector3(),
  7975. new Vector3()
  7976. ];
  7977. return function applyMatrix4( matrix ) {
  7978. // transform of empty box is an empty box.
  7979. if ( this.isEmpty() ) return this;
  7980. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7981. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7982. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7983. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7984. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7985. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7986. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7987. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7988. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7989. this.setFromPoints( points );
  7990. return this;
  7991. };
  7992. }(),
  7993. translate: function ( offset ) {
  7994. this.min.add( offset );
  7995. this.max.add( offset );
  7996. return this;
  7997. },
  7998. equals: function ( box ) {
  7999. return box.min.equals( this.min ) && box.max.equals( this.max );
  8000. }
  8001. } );
  8002. /**
  8003. * @author bhouston / http://clara.io
  8004. * @author mrdoob / http://mrdoob.com/
  8005. */
  8006. function Sphere( center, radius ) {
  8007. this.center = ( center !== undefined ) ? center : new Vector3();
  8008. this.radius = ( radius !== undefined ) ? radius : 0;
  8009. }
  8010. Object.assign( Sphere.prototype, {
  8011. set: function ( center, radius ) {
  8012. this.center.copy( center );
  8013. this.radius = radius;
  8014. return this;
  8015. },
  8016. setFromPoints: function () {
  8017. var box = new Box3();
  8018. return function setFromPoints( points, optionalCenter ) {
  8019. var center = this.center;
  8020. if ( optionalCenter !== undefined ) {
  8021. center.copy( optionalCenter );
  8022. } else {
  8023. box.setFromPoints( points ).getCenter( center );
  8024. }
  8025. var maxRadiusSq = 0;
  8026. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8027. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8028. }
  8029. this.radius = Math.sqrt( maxRadiusSq );
  8030. return this;
  8031. };
  8032. }(),
  8033. clone: function () {
  8034. return new this.constructor().copy( this );
  8035. },
  8036. copy: function ( sphere ) {
  8037. this.center.copy( sphere.center );
  8038. this.radius = sphere.radius;
  8039. return this;
  8040. },
  8041. empty: function () {
  8042. return ( this.radius <= 0 );
  8043. },
  8044. containsPoint: function ( point ) {
  8045. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8046. },
  8047. distanceToPoint: function ( point ) {
  8048. return ( point.distanceTo( this.center ) - this.radius );
  8049. },
  8050. intersectsSphere: function ( sphere ) {
  8051. var radiusSum = this.radius + sphere.radius;
  8052. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8053. },
  8054. intersectsBox: function ( box ) {
  8055. return box.intersectsSphere( this );
  8056. },
  8057. intersectsPlane: function ( plane ) {
  8058. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8059. },
  8060. clampPoint: function ( point, target ) {
  8061. var deltaLengthSq = this.center.distanceToSquared( point );
  8062. if ( target === undefined ) {
  8063. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  8064. target = new Vector3();
  8065. }
  8066. target.copy( point );
  8067. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8068. target.sub( this.center ).normalize();
  8069. target.multiplyScalar( this.radius ).add( this.center );
  8070. }
  8071. return target;
  8072. },
  8073. getBoundingBox: function ( target ) {
  8074. if ( target === undefined ) {
  8075. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  8076. target = new Box3();
  8077. }
  8078. target.set( this.center, this.center );
  8079. target.expandByScalar( this.radius );
  8080. return target;
  8081. },
  8082. applyMatrix4: function ( matrix ) {
  8083. this.center.applyMatrix4( matrix );
  8084. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8085. return this;
  8086. },
  8087. translate: function ( offset ) {
  8088. this.center.add( offset );
  8089. return this;
  8090. },
  8091. equals: function ( sphere ) {
  8092. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8093. }
  8094. } );
  8095. /**
  8096. * @author bhouston / http://clara.io
  8097. */
  8098. function Plane( normal, constant ) {
  8099. // normal is assumed to be normalized
  8100. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  8101. this.constant = ( constant !== undefined ) ? constant : 0;
  8102. }
  8103. Object.assign( Plane.prototype, {
  8104. set: function ( normal, constant ) {
  8105. this.normal.copy( normal );
  8106. this.constant = constant;
  8107. return this;
  8108. },
  8109. setComponents: function ( x, y, z, w ) {
  8110. this.normal.set( x, y, z );
  8111. this.constant = w;
  8112. return this;
  8113. },
  8114. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  8115. this.normal.copy( normal );
  8116. this.constant = - point.dot( this.normal );
  8117. return this;
  8118. },
  8119. setFromCoplanarPoints: function () {
  8120. var v1 = new Vector3();
  8121. var v2 = new Vector3();
  8122. return function setFromCoplanarPoints( a, b, c ) {
  8123. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  8124. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8125. this.setFromNormalAndCoplanarPoint( normal, a );
  8126. return this;
  8127. };
  8128. }(),
  8129. clone: function () {
  8130. return new this.constructor().copy( this );
  8131. },
  8132. copy: function ( plane ) {
  8133. this.normal.copy( plane.normal );
  8134. this.constant = plane.constant;
  8135. return this;
  8136. },
  8137. normalize: function () {
  8138. // Note: will lead to a divide by zero if the plane is invalid.
  8139. var inverseNormalLength = 1.0 / this.normal.length();
  8140. this.normal.multiplyScalar( inverseNormalLength );
  8141. this.constant *= inverseNormalLength;
  8142. return this;
  8143. },
  8144. negate: function () {
  8145. this.constant *= - 1;
  8146. this.normal.negate();
  8147. return this;
  8148. },
  8149. distanceToPoint: function ( point ) {
  8150. return this.normal.dot( point ) + this.constant;
  8151. },
  8152. distanceToSphere: function ( sphere ) {
  8153. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8154. },
  8155. projectPoint: function ( point, target ) {
  8156. if ( target === undefined ) {
  8157. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  8158. target = new Vector3();
  8159. }
  8160. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  8161. },
  8162. intersectLine: function () {
  8163. var v1 = new Vector3();
  8164. return function intersectLine( line, target ) {
  8165. if ( target === undefined ) {
  8166. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  8167. target = new Vector3();
  8168. }
  8169. var direction = line.delta( v1 );
  8170. var denominator = this.normal.dot( direction );
  8171. if ( denominator === 0 ) {
  8172. // line is coplanar, return origin
  8173. if ( this.distanceToPoint( line.start ) === 0 ) {
  8174. return target.copy( line.start );
  8175. }
  8176. // Unsure if this is the correct method to handle this case.
  8177. return undefined;
  8178. }
  8179. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8180. if ( t < 0 || t > 1 ) {
  8181. return undefined;
  8182. }
  8183. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  8184. };
  8185. }(),
  8186. intersectsLine: function ( line ) {
  8187. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8188. var startSign = this.distanceToPoint( line.start );
  8189. var endSign = this.distanceToPoint( line.end );
  8190. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8191. },
  8192. intersectsBox: function ( box ) {
  8193. return box.intersectsPlane( this );
  8194. },
  8195. intersectsSphere: function ( sphere ) {
  8196. return sphere.intersectsPlane( this );
  8197. },
  8198. coplanarPoint: function ( target ) {
  8199. if ( target === undefined ) {
  8200. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  8201. target = new Vector3();
  8202. }
  8203. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8204. },
  8205. applyMatrix4: function () {
  8206. var v1 = new Vector3();
  8207. var m1 = new Matrix3();
  8208. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  8209. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  8210. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  8211. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8212. this.constant = - referencePoint.dot( normal );
  8213. return this;
  8214. };
  8215. }(),
  8216. translate: function ( offset ) {
  8217. this.constant -= offset.dot( this.normal );
  8218. return this;
  8219. },
  8220. equals: function ( plane ) {
  8221. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8222. }
  8223. } );
  8224. /**
  8225. * @author mrdoob / http://mrdoob.com/
  8226. * @author alteredq / http://alteredqualia.com/
  8227. * @author bhouston / http://clara.io
  8228. */
  8229. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  8230. this.planes = [
  8231. ( p0 !== undefined ) ? p0 : new Plane(),
  8232. ( p1 !== undefined ) ? p1 : new Plane(),
  8233. ( p2 !== undefined ) ? p2 : new Plane(),
  8234. ( p3 !== undefined ) ? p3 : new Plane(),
  8235. ( p4 !== undefined ) ? p4 : new Plane(),
  8236. ( p5 !== undefined ) ? p5 : new Plane()
  8237. ];
  8238. }
  8239. Object.assign( Frustum.prototype, {
  8240. set: function ( p0, p1, p2, p3, p4, p5 ) {
  8241. var planes = this.planes;
  8242. planes[ 0 ].copy( p0 );
  8243. planes[ 1 ].copy( p1 );
  8244. planes[ 2 ].copy( p2 );
  8245. planes[ 3 ].copy( p3 );
  8246. planes[ 4 ].copy( p4 );
  8247. planes[ 5 ].copy( p5 );
  8248. return this;
  8249. },
  8250. clone: function () {
  8251. return new this.constructor().copy( this );
  8252. },
  8253. copy: function ( frustum ) {
  8254. var planes = this.planes;
  8255. for ( var i = 0; i < 6; i ++ ) {
  8256. planes[ i ].copy( frustum.planes[ i ] );
  8257. }
  8258. return this;
  8259. },
  8260. setFromMatrix: function ( m ) {
  8261. var planes = this.planes;
  8262. var me = m.elements;
  8263. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8264. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8265. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8266. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8267. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8268. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8269. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8270. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8271. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8272. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8273. return this;
  8274. },
  8275. intersectsObject: function () {
  8276. var sphere = new Sphere();
  8277. return function intersectsObject( object ) {
  8278. var geometry = object.geometry;
  8279. if ( geometry.boundingSphere === null )
  8280. geometry.computeBoundingSphere();
  8281. sphere.copy( geometry.boundingSphere )
  8282. .applyMatrix4( object.matrixWorld );
  8283. return this.intersectsSphere( sphere );
  8284. };
  8285. }(),
  8286. intersectsSprite: function () {
  8287. var sphere = new Sphere();
  8288. return function intersectsSprite( sprite ) {
  8289. sphere.center.set( 0, 0, 0 );
  8290. sphere.radius = 0.7071067811865476;
  8291. sphere.applyMatrix4( sprite.matrixWorld );
  8292. return this.intersectsSphere( sphere );
  8293. };
  8294. }(),
  8295. intersectsSphere: function ( sphere ) {
  8296. var planes = this.planes;
  8297. var center = sphere.center;
  8298. var negRadius = - sphere.radius;
  8299. for ( var i = 0; i < 6; i ++ ) {
  8300. var distance = planes[ i ].distanceToPoint( center );
  8301. if ( distance < negRadius ) {
  8302. return false;
  8303. }
  8304. }
  8305. return true;
  8306. },
  8307. intersectsBox: function () {
  8308. var p = new Vector3();
  8309. return function intersectsBox( box ) {
  8310. var planes = this.planes;
  8311. for ( var i = 0; i < 6; i ++ ) {
  8312. var plane = planes[ i ];
  8313. // corner at max distance
  8314. p.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8315. p.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8316. p.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8317. if ( plane.distanceToPoint( p ) < 0 ) {
  8318. return false;
  8319. }
  8320. }
  8321. return true;
  8322. };
  8323. }(),
  8324. containsPoint: function ( point ) {
  8325. var planes = this.planes;
  8326. for ( var i = 0; i < 6; i ++ ) {
  8327. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8328. return false;
  8329. }
  8330. }
  8331. return true;
  8332. }
  8333. } );
  8334. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8335. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8336. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8337. 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( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  8338. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8339. var begin_vertex = "vec3 transformed = vec3( position );";
  8340. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8341. 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}\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 GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, 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_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 GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.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( specularColor, dotNV );\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}";
  8342. 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";
  8343. 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";
  8344. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8345. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";
  8346. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";
  8347. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8348. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8349. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8350. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  8351. 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 whiteCompliment(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}\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};\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}";
  8352. 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";
  8353. 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";
  8354. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8355. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif";
  8356. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8357. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8358. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8359. 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}";
  8360. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\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";
  8361. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  8362. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  8363. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\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";
  8364. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  8365. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8366. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\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";
  8367. 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";
  8368. 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";
  8369. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif";
  8370. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8371. 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";
  8372. var lights_pars_begin = "uniform vec3 ambientLightColor;\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";
  8373. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP ) && defined( PHYSICAL )\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 blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, 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, BlinnExponentToGGXRoughness(blinnShininessExponent ));\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";
  8374. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8375. 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)";
  8376. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif";
  8377. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#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#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#endif\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#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\tfloat clearCoatInv = 1.0 - clearCoatDHR;\n\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec3 singleScattering = vec3( 0.0 );\n\t\tvec3 multiScattering = vec3( 0.0 );\n\t\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\t\tvec3 diffuse = material.diffuseColor;\n\t\treflectedLight.indirectSpecular += clearCoatInv * radiance * singleScattering;\n\t\treflectedLight.indirectDiffuse += multiScattering * cosineWeightedIrradiance;\n\t\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n\t#else\n\t\treflectedLight.indirectSpecular += clearCoatInv * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#endif\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\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}";
  8378. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\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#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? 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#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? 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#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? 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 irradiance = getAmbientLightIrradiance( ambientLightColor );\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";
  8379. 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( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), maxMipLevel );\n\t#ifndef STANDARD\n\t\tclearCoatRadiance += getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), maxMipLevel );\n\t#endif\n#endif";
  8380. 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, irradiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif";
  8381. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8382. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n#endif";
  8383. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8384. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif";
  8385. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8386. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8387. 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";
  8388. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif";
  8389. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8390. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8391. 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";
  8392. 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";
  8393. 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";
  8394. 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";
  8395. var normal_fragment_maps = "#ifdef USE_NORMALMAP\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t#ifdef FLIP_SIDED\n\t\t\tnormal = - normal;\n\t\t#endif\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\tnormal = normalize( normalMatrix * normal );\n\t#else\n\t\t#ifdef USE_TANGENT\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t\tmapN.xy = normalScale * mapN.xy;\n\t\t\tnormal = normalize( vTBN * mapN );\n\t\t#else\n\t\t\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n\t\t#endif\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8396. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\t#ifdef OBJECTSPACE_NORMALMAP\n\t\tuniform mat3 normalMatrix;\n\t#else\n\t\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\t\tvec2 st0 = dFdx( vUv.st );\n\t\t\tvec2 st1 = dFdy( vUv.st );\n\t\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\t\tvec3 N = normalize( surf_norm );\n\t\t\tmat3 tsn = mat3( S, T, N );\n\t\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\t\tmapN.xy *= normalScale;\n\t\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\treturn normalize( tsn * mapN );\n\t\t}\n\t#endif\n#endif";
  8397. 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}\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}";
  8398. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8399. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;";
  8400. var dithering_fragment = "#if defined( DITHERING )\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8401. var dithering_pars_fragment = "#if defined( 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";
  8402. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8403. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8404. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\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 ) / size;\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\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( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, 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( 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 / 9.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#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 )\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";
  8405. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif";
  8406. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";
  8407. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\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\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\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\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\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\tshadow *= bool( pointLight.shadow ) ? 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}";
  8408. 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";
  8409. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform 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";
  8410. 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";
  8411. 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";
  8412. 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";
  8413. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8414. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8415. 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}";
  8416. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  8417. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif";
  8418. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8419. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8420. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  8421. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  8422. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif";
  8423. 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}";
  8424. 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}";
  8425. 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}";
  8426. 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}";
  8427. 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}";
  8428. 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}";
  8429. 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}";
  8430. 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}";
  8431. 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}";
  8432. 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}";
  8433. 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}";
  8434. 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}";
  8435. 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_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}";
  8436. 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}";
  8437. 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_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}";
  8438. 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}";
  8439. 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}";
  8440. 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}";
  8441. 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_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}";
  8442. 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}";
  8443. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\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_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 <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 <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\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}";
  8444. var meshphysical_vert = "#define PHYSICAL\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}";
  8445. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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>\nvoid main() {\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}";
  8446. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_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>\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#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || ( defined( USE_NORMALMAP ) && ! defined( OBJECTSPACE_NORMALMAP ) )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8447. 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}";
  8448. 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 = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\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}";
  8449. 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}";
  8450. 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}";
  8451. 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}";
  8452. 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 = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 );\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}";
  8453. var ShaderChunk = {
  8454. alphamap_fragment: alphamap_fragment,
  8455. alphamap_pars_fragment: alphamap_pars_fragment,
  8456. alphatest_fragment: alphatest_fragment,
  8457. aomap_fragment: aomap_fragment,
  8458. aomap_pars_fragment: aomap_pars_fragment,
  8459. begin_vertex: begin_vertex,
  8460. beginnormal_vertex: beginnormal_vertex,
  8461. bsdfs: bsdfs,
  8462. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8463. clipping_planes_fragment: clipping_planes_fragment,
  8464. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8465. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8466. clipping_planes_vertex: clipping_planes_vertex,
  8467. color_fragment: color_fragment,
  8468. color_pars_fragment: color_pars_fragment,
  8469. color_pars_vertex: color_pars_vertex,
  8470. color_vertex: color_vertex,
  8471. common: common,
  8472. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8473. defaultnormal_vertex: defaultnormal_vertex,
  8474. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8475. displacementmap_vertex: displacementmap_vertex,
  8476. emissivemap_fragment: emissivemap_fragment,
  8477. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8478. encodings_fragment: encodings_fragment,
  8479. encodings_pars_fragment: encodings_pars_fragment,
  8480. envmap_fragment: envmap_fragment,
  8481. envmap_pars_fragment: envmap_pars_fragment,
  8482. envmap_pars_vertex: envmap_pars_vertex,
  8483. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8484. envmap_vertex: envmap_vertex,
  8485. fog_vertex: fog_vertex,
  8486. fog_pars_vertex: fog_pars_vertex,
  8487. fog_fragment: fog_fragment,
  8488. fog_pars_fragment: fog_pars_fragment,
  8489. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8490. lightmap_fragment: lightmap_fragment,
  8491. lightmap_pars_fragment: lightmap_pars_fragment,
  8492. lights_lambert_vertex: lights_lambert_vertex,
  8493. lights_pars_begin: lights_pars_begin,
  8494. lights_phong_fragment: lights_phong_fragment,
  8495. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8496. lights_physical_fragment: lights_physical_fragment,
  8497. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8498. lights_fragment_begin: lights_fragment_begin,
  8499. lights_fragment_maps: lights_fragment_maps,
  8500. lights_fragment_end: lights_fragment_end,
  8501. logdepthbuf_fragment: logdepthbuf_fragment,
  8502. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8503. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8504. logdepthbuf_vertex: logdepthbuf_vertex,
  8505. map_fragment: map_fragment,
  8506. map_pars_fragment: map_pars_fragment,
  8507. map_particle_fragment: map_particle_fragment,
  8508. map_particle_pars_fragment: map_particle_pars_fragment,
  8509. metalnessmap_fragment: metalnessmap_fragment,
  8510. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8511. morphnormal_vertex: morphnormal_vertex,
  8512. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8513. morphtarget_vertex: morphtarget_vertex,
  8514. normal_fragment_begin: normal_fragment_begin,
  8515. normal_fragment_maps: normal_fragment_maps,
  8516. normalmap_pars_fragment: normalmap_pars_fragment,
  8517. packing: packing,
  8518. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8519. project_vertex: project_vertex,
  8520. dithering_fragment: dithering_fragment,
  8521. dithering_pars_fragment: dithering_pars_fragment,
  8522. roughnessmap_fragment: roughnessmap_fragment,
  8523. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8524. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8525. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8526. shadowmap_vertex: shadowmap_vertex,
  8527. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8528. skinbase_vertex: skinbase_vertex,
  8529. skinning_pars_vertex: skinning_pars_vertex,
  8530. skinning_vertex: skinning_vertex,
  8531. skinnormal_vertex: skinnormal_vertex,
  8532. specularmap_fragment: specularmap_fragment,
  8533. specularmap_pars_fragment: specularmap_pars_fragment,
  8534. tonemapping_fragment: tonemapping_fragment,
  8535. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8536. uv_pars_fragment: uv_pars_fragment,
  8537. uv_pars_vertex: uv_pars_vertex,
  8538. uv_vertex: uv_vertex,
  8539. uv2_pars_fragment: uv2_pars_fragment,
  8540. uv2_pars_vertex: uv2_pars_vertex,
  8541. uv2_vertex: uv2_vertex,
  8542. worldpos_vertex: worldpos_vertex,
  8543. background_frag: background_frag,
  8544. background_vert: background_vert,
  8545. cube_frag: cube_frag,
  8546. cube_vert: cube_vert,
  8547. depth_frag: depth_frag,
  8548. depth_vert: depth_vert,
  8549. distanceRGBA_frag: distanceRGBA_frag,
  8550. distanceRGBA_vert: distanceRGBA_vert,
  8551. equirect_frag: equirect_frag,
  8552. equirect_vert: equirect_vert,
  8553. linedashed_frag: linedashed_frag,
  8554. linedashed_vert: linedashed_vert,
  8555. meshbasic_frag: meshbasic_frag,
  8556. meshbasic_vert: meshbasic_vert,
  8557. meshlambert_frag: meshlambert_frag,
  8558. meshlambert_vert: meshlambert_vert,
  8559. meshmatcap_frag: meshmatcap_frag,
  8560. meshmatcap_vert: meshmatcap_vert,
  8561. meshphong_frag: meshphong_frag,
  8562. meshphong_vert: meshphong_vert,
  8563. meshphysical_frag: meshphysical_frag,
  8564. meshphysical_vert: meshphysical_vert,
  8565. normal_frag: normal_frag,
  8566. normal_vert: normal_vert,
  8567. points_frag: points_frag,
  8568. points_vert: points_vert,
  8569. shadow_frag: shadow_frag,
  8570. shadow_vert: shadow_vert,
  8571. sprite_frag: sprite_frag,
  8572. sprite_vert: sprite_vert
  8573. };
  8574. /**
  8575. * Uniform Utilities
  8576. */
  8577. function cloneUniforms( src ) {
  8578. var dst = {};
  8579. for ( var u in src ) {
  8580. dst[ u ] = {};
  8581. for ( var p in src[ u ] ) {
  8582. var property = src[ u ][ p ];
  8583. if ( property && ( property.isColor ||
  8584. property.isMatrix3 || property.isMatrix4 ||
  8585. property.isVector2 || property.isVector3 || property.isVector4 ||
  8586. property.isTexture ) ) {
  8587. dst[ u ][ p ] = property.clone();
  8588. } else if ( Array.isArray( property ) ) {
  8589. dst[ u ][ p ] = property.slice();
  8590. } else {
  8591. dst[ u ][ p ] = property;
  8592. }
  8593. }
  8594. }
  8595. return dst;
  8596. }
  8597. function mergeUniforms( uniforms ) {
  8598. var merged = {};
  8599. for ( var u = 0; u < uniforms.length; u ++ ) {
  8600. var tmp = cloneUniforms( uniforms[ u ] );
  8601. for ( var p in tmp ) {
  8602. merged[ p ] = tmp[ p ];
  8603. }
  8604. }
  8605. return merged;
  8606. }
  8607. // Legacy
  8608. var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  8609. /**
  8610. * @author mrdoob / http://mrdoob.com/
  8611. */
  8612. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  8613. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  8614. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  8615. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  8616. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  8617. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  8618. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  8619. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  8620. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  8621. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  8622. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  8623. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  8624. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  8625. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  8626. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  8627. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  8628. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  8629. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  8630. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  8631. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  8632. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  8633. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  8634. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  8635. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  8636. function Color( r, g, b ) {
  8637. if ( g === undefined && b === undefined ) {
  8638. // r is THREE.Color, hex or string
  8639. return this.set( r );
  8640. }
  8641. return this.setRGB( r, g, b );
  8642. }
  8643. Object.assign( Color.prototype, {
  8644. isColor: true,
  8645. r: 1, g: 1, b: 1,
  8646. set: function ( value ) {
  8647. if ( value && value.isColor ) {
  8648. this.copy( value );
  8649. } else if ( typeof value === 'number' ) {
  8650. this.setHex( value );
  8651. } else if ( typeof value === 'string' ) {
  8652. this.setStyle( value );
  8653. }
  8654. return this;
  8655. },
  8656. setScalar: function ( scalar ) {
  8657. this.r = scalar;
  8658. this.g = scalar;
  8659. this.b = scalar;
  8660. return this;
  8661. },
  8662. setHex: function ( hex ) {
  8663. hex = Math.floor( hex );
  8664. this.r = ( hex >> 16 & 255 ) / 255;
  8665. this.g = ( hex >> 8 & 255 ) / 255;
  8666. this.b = ( hex & 255 ) / 255;
  8667. return this;
  8668. },
  8669. setRGB: function ( r, g, b ) {
  8670. this.r = r;
  8671. this.g = g;
  8672. this.b = b;
  8673. return this;
  8674. },
  8675. setHSL: function () {
  8676. function hue2rgb( p, q, t ) {
  8677. if ( t < 0 ) t += 1;
  8678. if ( t > 1 ) t -= 1;
  8679. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  8680. if ( t < 1 / 2 ) return q;
  8681. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  8682. return p;
  8683. }
  8684. return function setHSL( h, s, l ) {
  8685. // h,s,l ranges are in 0.0 - 1.0
  8686. h = _Math.euclideanModulo( h, 1 );
  8687. s = _Math.clamp( s, 0, 1 );
  8688. l = _Math.clamp( l, 0, 1 );
  8689. if ( s === 0 ) {
  8690. this.r = this.g = this.b = l;
  8691. } else {
  8692. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  8693. var q = ( 2 * l ) - p;
  8694. this.r = hue2rgb( q, p, h + 1 / 3 );
  8695. this.g = hue2rgb( q, p, h );
  8696. this.b = hue2rgb( q, p, h - 1 / 3 );
  8697. }
  8698. return this;
  8699. };
  8700. }(),
  8701. setStyle: function ( style ) {
  8702. function handleAlpha( string ) {
  8703. if ( string === undefined ) return;
  8704. if ( parseFloat( string ) < 1 ) {
  8705. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  8706. }
  8707. }
  8708. var m;
  8709. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  8710. // rgb / hsl
  8711. var color;
  8712. var name = m[ 1 ];
  8713. var components = m[ 2 ];
  8714. switch ( name ) {
  8715. case 'rgb':
  8716. case 'rgba':
  8717. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8718. // rgb(255,0,0) rgba(255,0,0,0.5)
  8719. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  8720. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  8721. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  8722. handleAlpha( color[ 5 ] );
  8723. return this;
  8724. }
  8725. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8726. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  8727. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  8728. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  8729. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  8730. handleAlpha( color[ 5 ] );
  8731. return this;
  8732. }
  8733. break;
  8734. case 'hsl':
  8735. case 'hsla':
  8736. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  8737. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  8738. var h = parseFloat( color[ 1 ] ) / 360;
  8739. var s = parseInt( color[ 2 ], 10 ) / 100;
  8740. var l = parseInt( color[ 3 ], 10 ) / 100;
  8741. handleAlpha( color[ 5 ] );
  8742. return this.setHSL( h, s, l );
  8743. }
  8744. break;
  8745. }
  8746. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  8747. // hex color
  8748. var hex = m[ 1 ];
  8749. var size = hex.length;
  8750. if ( size === 3 ) {
  8751. // #ff0
  8752. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  8753. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  8754. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  8755. return this;
  8756. } else if ( size === 6 ) {
  8757. // #ff0000
  8758. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  8759. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  8760. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  8761. return this;
  8762. }
  8763. }
  8764. if ( style && style.length > 0 ) {
  8765. // color keywords
  8766. var hex = ColorKeywords[ style ];
  8767. if ( hex !== undefined ) {
  8768. // red
  8769. this.setHex( hex );
  8770. } else {
  8771. // unknown color
  8772. console.warn( 'THREE.Color: Unknown color ' + style );
  8773. }
  8774. }
  8775. return this;
  8776. },
  8777. clone: function () {
  8778. return new this.constructor( this.r, this.g, this.b );
  8779. },
  8780. copy: function ( color ) {
  8781. this.r = color.r;
  8782. this.g = color.g;
  8783. this.b = color.b;
  8784. return this;
  8785. },
  8786. copyGammaToLinear: function ( color, gammaFactor ) {
  8787. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  8788. this.r = Math.pow( color.r, gammaFactor );
  8789. this.g = Math.pow( color.g, gammaFactor );
  8790. this.b = Math.pow( color.b, gammaFactor );
  8791. return this;
  8792. },
  8793. copyLinearToGamma: function ( color, gammaFactor ) {
  8794. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  8795. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  8796. this.r = Math.pow( color.r, safeInverse );
  8797. this.g = Math.pow( color.g, safeInverse );
  8798. this.b = Math.pow( color.b, safeInverse );
  8799. return this;
  8800. },
  8801. convertGammaToLinear: function ( gammaFactor ) {
  8802. this.copyGammaToLinear( this, gammaFactor );
  8803. return this;
  8804. },
  8805. convertLinearToGamma: function ( gammaFactor ) {
  8806. this.copyLinearToGamma( this, gammaFactor );
  8807. return this;
  8808. },
  8809. copySRGBToLinear: function () {
  8810. function SRGBToLinear( c ) {
  8811. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  8812. }
  8813. return function copySRGBToLinear( color ) {
  8814. this.r = SRGBToLinear( color.r );
  8815. this.g = SRGBToLinear( color.g );
  8816. this.b = SRGBToLinear( color.b );
  8817. return this;
  8818. };
  8819. }(),
  8820. copyLinearToSRGB: function () {
  8821. function LinearToSRGB( c ) {
  8822. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  8823. }
  8824. return function copyLinearToSRGB( color ) {
  8825. this.r = LinearToSRGB( color.r );
  8826. this.g = LinearToSRGB( color.g );
  8827. this.b = LinearToSRGB( color.b );
  8828. return this;
  8829. };
  8830. }(),
  8831. convertSRGBToLinear: function () {
  8832. this.copySRGBToLinear( this );
  8833. return this;
  8834. },
  8835. convertLinearToSRGB: function () {
  8836. this.copyLinearToSRGB( this );
  8837. return this;
  8838. },
  8839. getHex: function () {
  8840. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  8841. },
  8842. getHexString: function () {
  8843. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  8844. },
  8845. getHSL: function ( target ) {
  8846. // h,s,l ranges are in 0.0 - 1.0
  8847. if ( target === undefined ) {
  8848. console.warn( 'THREE.Color: .getHSL() target is now required' );
  8849. target = { h: 0, s: 0, l: 0 };
  8850. }
  8851. var r = this.r, g = this.g, b = this.b;
  8852. var max = Math.max( r, g, b );
  8853. var min = Math.min( r, g, b );
  8854. var hue, saturation;
  8855. var lightness = ( min + max ) / 2.0;
  8856. if ( min === max ) {
  8857. hue = 0;
  8858. saturation = 0;
  8859. } else {
  8860. var delta = max - min;
  8861. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  8862. switch ( max ) {
  8863. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  8864. case g: hue = ( b - r ) / delta + 2; break;
  8865. case b: hue = ( r - g ) / delta + 4; break;
  8866. }
  8867. hue /= 6;
  8868. }
  8869. target.h = hue;
  8870. target.s = saturation;
  8871. target.l = lightness;
  8872. return target;
  8873. },
  8874. getStyle: function () {
  8875. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  8876. },
  8877. offsetHSL: function () {
  8878. var hsl = {};
  8879. return function ( h, s, l ) {
  8880. this.getHSL( hsl );
  8881. hsl.h += h; hsl.s += s; hsl.l += l;
  8882. this.setHSL( hsl.h, hsl.s, hsl.l );
  8883. return this;
  8884. };
  8885. }(),
  8886. add: function ( color ) {
  8887. this.r += color.r;
  8888. this.g += color.g;
  8889. this.b += color.b;
  8890. return this;
  8891. },
  8892. addColors: function ( color1, color2 ) {
  8893. this.r = color1.r + color2.r;
  8894. this.g = color1.g + color2.g;
  8895. this.b = color1.b + color2.b;
  8896. return this;
  8897. },
  8898. addScalar: function ( s ) {
  8899. this.r += s;
  8900. this.g += s;
  8901. this.b += s;
  8902. return this;
  8903. },
  8904. sub: function ( color ) {
  8905. this.r = Math.max( 0, this.r - color.r );
  8906. this.g = Math.max( 0, this.g - color.g );
  8907. this.b = Math.max( 0, this.b - color.b );
  8908. return this;
  8909. },
  8910. multiply: function ( color ) {
  8911. this.r *= color.r;
  8912. this.g *= color.g;
  8913. this.b *= color.b;
  8914. return this;
  8915. },
  8916. multiplyScalar: function ( s ) {
  8917. this.r *= s;
  8918. this.g *= s;
  8919. this.b *= s;
  8920. return this;
  8921. },
  8922. lerp: function ( color, alpha ) {
  8923. this.r += ( color.r - this.r ) * alpha;
  8924. this.g += ( color.g - this.g ) * alpha;
  8925. this.b += ( color.b - this.b ) * alpha;
  8926. return this;
  8927. },
  8928. lerpHSL: function () {
  8929. var hslA = { h: 0, s: 0, l: 0 };
  8930. var hslB = { h: 0, s: 0, l: 0 };
  8931. return function lerpHSL( color, alpha ) {
  8932. this.getHSL( hslA );
  8933. color.getHSL( hslB );
  8934. var h = _Math.lerp( hslA.h, hslB.h, alpha );
  8935. var s = _Math.lerp( hslA.s, hslB.s, alpha );
  8936. var l = _Math.lerp( hslA.l, hslB.l, alpha );
  8937. this.setHSL( h, s, l );
  8938. return this;
  8939. };
  8940. }(),
  8941. equals: function ( c ) {
  8942. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  8943. },
  8944. fromArray: function ( array, offset ) {
  8945. if ( offset === undefined ) offset = 0;
  8946. this.r = array[ offset ];
  8947. this.g = array[ offset + 1 ];
  8948. this.b = array[ offset + 2 ];
  8949. return this;
  8950. },
  8951. toArray: function ( array, offset ) {
  8952. if ( array === undefined ) array = [];
  8953. if ( offset === undefined ) offset = 0;
  8954. array[ offset ] = this.r;
  8955. array[ offset + 1 ] = this.g;
  8956. array[ offset + 2 ] = this.b;
  8957. return array;
  8958. },
  8959. toJSON: function () {
  8960. return this.getHex();
  8961. }
  8962. } );
  8963. /**
  8964. * Uniforms library for shared webgl shaders
  8965. */
  8966. var UniformsLib = {
  8967. common: {
  8968. diffuse: { value: new Color( 0xeeeeee ) },
  8969. opacity: { value: 1.0 },
  8970. map: { value: null },
  8971. uvTransform: { value: new Matrix3() },
  8972. alphaMap: { value: null },
  8973. },
  8974. specularmap: {
  8975. specularMap: { value: null },
  8976. },
  8977. envmap: {
  8978. envMap: { value: null },
  8979. flipEnvMap: { value: - 1 },
  8980. reflectivity: { value: 1.0 },
  8981. refractionRatio: { value: 0.98 },
  8982. maxMipLevel: { value: 0 }
  8983. },
  8984. aomap: {
  8985. aoMap: { value: null },
  8986. aoMapIntensity: { value: 1 }
  8987. },
  8988. lightmap: {
  8989. lightMap: { value: null },
  8990. lightMapIntensity: { value: 1 }
  8991. },
  8992. emissivemap: {
  8993. emissiveMap: { value: null }
  8994. },
  8995. bumpmap: {
  8996. bumpMap: { value: null },
  8997. bumpScale: { value: 1 }
  8998. },
  8999. normalmap: {
  9000. normalMap: { value: null },
  9001. normalScale: { value: new Vector2( 1, 1 ) }
  9002. },
  9003. displacementmap: {
  9004. displacementMap: { value: null },
  9005. displacementScale: { value: 1 },
  9006. displacementBias: { value: 0 }
  9007. },
  9008. roughnessmap: {
  9009. roughnessMap: { value: null }
  9010. },
  9011. metalnessmap: {
  9012. metalnessMap: { value: null }
  9013. },
  9014. gradientmap: {
  9015. gradientMap: { value: null }
  9016. },
  9017. fog: {
  9018. fogDensity: { value: 0.00025 },
  9019. fogNear: { value: 1 },
  9020. fogFar: { value: 2000 },
  9021. fogColor: { value: new Color( 0xffffff ) }
  9022. },
  9023. lights: {
  9024. ambientLightColor: { value: [] },
  9025. directionalLights: { value: [], properties: {
  9026. direction: {},
  9027. color: {},
  9028. shadow: {},
  9029. shadowBias: {},
  9030. shadowRadius: {},
  9031. shadowMapSize: {}
  9032. } },
  9033. directionalShadowMap: { value: [] },
  9034. directionalShadowMatrix: { value: [] },
  9035. spotLights: { value: [], properties: {
  9036. color: {},
  9037. position: {},
  9038. direction: {},
  9039. distance: {},
  9040. coneCos: {},
  9041. penumbraCos: {},
  9042. decay: {},
  9043. shadow: {},
  9044. shadowBias: {},
  9045. shadowRadius: {},
  9046. shadowMapSize: {}
  9047. } },
  9048. spotShadowMap: { value: [] },
  9049. spotShadowMatrix: { value: [] },
  9050. pointLights: { value: [], properties: {
  9051. color: {},
  9052. position: {},
  9053. decay: {},
  9054. distance: {},
  9055. shadow: {},
  9056. shadowBias: {},
  9057. shadowRadius: {},
  9058. shadowMapSize: {},
  9059. shadowCameraNear: {},
  9060. shadowCameraFar: {}
  9061. } },
  9062. pointShadowMap: { value: [] },
  9063. pointShadowMatrix: { value: [] },
  9064. hemisphereLights: { value: [], properties: {
  9065. direction: {},
  9066. skyColor: {},
  9067. groundColor: {}
  9068. } },
  9069. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9070. rectAreaLights: { value: [], properties: {
  9071. color: {},
  9072. position: {},
  9073. width: {},
  9074. height: {}
  9075. } }
  9076. },
  9077. points: {
  9078. diffuse: { value: new Color( 0xeeeeee ) },
  9079. opacity: { value: 1.0 },
  9080. size: { value: 1.0 },
  9081. scale: { value: 1.0 },
  9082. map: { value: null },
  9083. uvTransform: { value: new Matrix3() }
  9084. },
  9085. sprite: {
  9086. diffuse: { value: new Color( 0xeeeeee ) },
  9087. opacity: { value: 1.0 },
  9088. center: { value: new Vector2( 0.5, 0.5 ) },
  9089. rotation: { value: 0.0 },
  9090. map: { value: null },
  9091. uvTransform: { value: new Matrix3() }
  9092. }
  9093. };
  9094. /**
  9095. * @author alteredq / http://alteredqualia.com/
  9096. * @author mrdoob / http://mrdoob.com/
  9097. * @author mikael emtinger / http://gomo.se/
  9098. */
  9099. var ShaderLib = {
  9100. basic: {
  9101. uniforms: mergeUniforms( [
  9102. UniformsLib.common,
  9103. UniformsLib.specularmap,
  9104. UniformsLib.envmap,
  9105. UniformsLib.aomap,
  9106. UniformsLib.lightmap,
  9107. UniformsLib.fog
  9108. ] ),
  9109. vertexShader: ShaderChunk.meshbasic_vert,
  9110. fragmentShader: ShaderChunk.meshbasic_frag
  9111. },
  9112. lambert: {
  9113. uniforms: mergeUniforms( [
  9114. UniformsLib.common,
  9115. UniformsLib.specularmap,
  9116. UniformsLib.envmap,
  9117. UniformsLib.aomap,
  9118. UniformsLib.lightmap,
  9119. UniformsLib.emissivemap,
  9120. UniformsLib.fog,
  9121. UniformsLib.lights,
  9122. {
  9123. emissive: { value: new Color( 0x000000 ) }
  9124. }
  9125. ] ),
  9126. vertexShader: ShaderChunk.meshlambert_vert,
  9127. fragmentShader: ShaderChunk.meshlambert_frag
  9128. },
  9129. phong: {
  9130. uniforms: mergeUniforms( [
  9131. UniformsLib.common,
  9132. UniformsLib.specularmap,
  9133. UniformsLib.envmap,
  9134. UniformsLib.aomap,
  9135. UniformsLib.lightmap,
  9136. UniformsLib.emissivemap,
  9137. UniformsLib.bumpmap,
  9138. UniformsLib.normalmap,
  9139. UniformsLib.displacementmap,
  9140. UniformsLib.gradientmap,
  9141. UniformsLib.fog,
  9142. UniformsLib.lights,
  9143. {
  9144. emissive: { value: new Color( 0x000000 ) },
  9145. specular: { value: new Color( 0x111111 ) },
  9146. shininess: { value: 30 }
  9147. }
  9148. ] ),
  9149. vertexShader: ShaderChunk.meshphong_vert,
  9150. fragmentShader: ShaderChunk.meshphong_frag
  9151. },
  9152. standard: {
  9153. uniforms: mergeUniforms( [
  9154. UniformsLib.common,
  9155. UniformsLib.envmap,
  9156. UniformsLib.aomap,
  9157. UniformsLib.lightmap,
  9158. UniformsLib.emissivemap,
  9159. UniformsLib.bumpmap,
  9160. UniformsLib.normalmap,
  9161. UniformsLib.displacementmap,
  9162. UniformsLib.roughnessmap,
  9163. UniformsLib.metalnessmap,
  9164. UniformsLib.fog,
  9165. UniformsLib.lights,
  9166. {
  9167. emissive: { value: new Color( 0x000000 ) },
  9168. roughness: { value: 0.5 },
  9169. metalness: { value: 0.5 },
  9170. envMapIntensity: { value: 1 } // temporary
  9171. }
  9172. ] ),
  9173. vertexShader: ShaderChunk.meshphysical_vert,
  9174. fragmentShader: ShaderChunk.meshphysical_frag
  9175. },
  9176. matcap: {
  9177. uniforms: mergeUniforms( [
  9178. UniformsLib.common,
  9179. UniformsLib.bumpmap,
  9180. UniformsLib.normalmap,
  9181. UniformsLib.displacementmap,
  9182. UniformsLib.fog,
  9183. {
  9184. matcap: { value: null }
  9185. }
  9186. ] ),
  9187. vertexShader: ShaderChunk.meshmatcap_vert,
  9188. fragmentShader: ShaderChunk.meshmatcap_frag
  9189. },
  9190. points: {
  9191. uniforms: mergeUniforms( [
  9192. UniformsLib.points,
  9193. UniformsLib.fog
  9194. ] ),
  9195. vertexShader: ShaderChunk.points_vert,
  9196. fragmentShader: ShaderChunk.points_frag
  9197. },
  9198. dashed: {
  9199. uniforms: mergeUniforms( [
  9200. UniformsLib.common,
  9201. UniformsLib.fog,
  9202. {
  9203. scale: { value: 1 },
  9204. dashSize: { value: 1 },
  9205. totalSize: { value: 2 }
  9206. }
  9207. ] ),
  9208. vertexShader: ShaderChunk.linedashed_vert,
  9209. fragmentShader: ShaderChunk.linedashed_frag
  9210. },
  9211. depth: {
  9212. uniforms: mergeUniforms( [
  9213. UniformsLib.common,
  9214. UniformsLib.displacementmap
  9215. ] ),
  9216. vertexShader: ShaderChunk.depth_vert,
  9217. fragmentShader: ShaderChunk.depth_frag
  9218. },
  9219. normal: {
  9220. uniforms: mergeUniforms( [
  9221. UniformsLib.common,
  9222. UniformsLib.bumpmap,
  9223. UniformsLib.normalmap,
  9224. UniformsLib.displacementmap,
  9225. {
  9226. opacity: { value: 1.0 }
  9227. }
  9228. ] ),
  9229. vertexShader: ShaderChunk.normal_vert,
  9230. fragmentShader: ShaderChunk.normal_frag
  9231. },
  9232. sprite: {
  9233. uniforms: mergeUniforms( [
  9234. UniformsLib.sprite,
  9235. UniformsLib.fog
  9236. ] ),
  9237. vertexShader: ShaderChunk.sprite_vert,
  9238. fragmentShader: ShaderChunk.sprite_frag
  9239. },
  9240. background: {
  9241. uniforms: {
  9242. uvTransform: { value: new Matrix3() },
  9243. t2D: { value: null },
  9244. },
  9245. vertexShader: ShaderChunk.background_vert,
  9246. fragmentShader: ShaderChunk.background_frag
  9247. },
  9248. /* -------------------------------------------------------------------------
  9249. // Cube map shader
  9250. ------------------------------------------------------------------------- */
  9251. cube: {
  9252. uniforms: {
  9253. tCube: { value: null },
  9254. tFlip: { value: - 1 },
  9255. opacity: { value: 1.0 }
  9256. },
  9257. vertexShader: ShaderChunk.cube_vert,
  9258. fragmentShader: ShaderChunk.cube_frag
  9259. },
  9260. equirect: {
  9261. uniforms: {
  9262. tEquirect: { value: null },
  9263. },
  9264. vertexShader: ShaderChunk.equirect_vert,
  9265. fragmentShader: ShaderChunk.equirect_frag
  9266. },
  9267. distanceRGBA: {
  9268. uniforms: mergeUniforms( [
  9269. UniformsLib.common,
  9270. UniformsLib.displacementmap,
  9271. {
  9272. referencePosition: { value: new Vector3() },
  9273. nearDistance: { value: 1 },
  9274. farDistance: { value: 1000 }
  9275. }
  9276. ] ),
  9277. vertexShader: ShaderChunk.distanceRGBA_vert,
  9278. fragmentShader: ShaderChunk.distanceRGBA_frag
  9279. },
  9280. shadow: {
  9281. uniforms: mergeUniforms( [
  9282. UniformsLib.lights,
  9283. UniformsLib.fog,
  9284. {
  9285. color: { value: new Color( 0x00000 ) },
  9286. opacity: { value: 1.0 }
  9287. },
  9288. ] ),
  9289. vertexShader: ShaderChunk.shadow_vert,
  9290. fragmentShader: ShaderChunk.shadow_frag
  9291. }
  9292. };
  9293. ShaderLib.physical = {
  9294. uniforms: mergeUniforms( [
  9295. ShaderLib.standard.uniforms,
  9296. {
  9297. clearCoat: { value: 0 },
  9298. clearCoatRoughness: { value: 0 }
  9299. }
  9300. ] ),
  9301. vertexShader: ShaderChunk.meshphysical_vert,
  9302. fragmentShader: ShaderChunk.meshphysical_frag
  9303. };
  9304. /**
  9305. * @author mrdoob / http://mrdoob.com/
  9306. */
  9307. function WebGLAnimation() {
  9308. var context = null;
  9309. var isAnimating = false;
  9310. var animationLoop = null;
  9311. function onAnimationFrame( time, frame ) {
  9312. if ( isAnimating === false ) return;
  9313. animationLoop( time, frame );
  9314. context.requestAnimationFrame( onAnimationFrame );
  9315. }
  9316. return {
  9317. start: function () {
  9318. if ( isAnimating === true ) return;
  9319. if ( animationLoop === null ) return;
  9320. context.requestAnimationFrame( onAnimationFrame );
  9321. isAnimating = true;
  9322. },
  9323. stop: function () {
  9324. isAnimating = false;
  9325. },
  9326. setAnimationLoop: function ( callback ) {
  9327. animationLoop = callback;
  9328. },
  9329. setContext: function ( value ) {
  9330. context = value;
  9331. }
  9332. };
  9333. }
  9334. /**
  9335. * @author mrdoob / http://mrdoob.com/
  9336. */
  9337. function WebGLAttributes( gl ) {
  9338. var buffers = new WeakMap();
  9339. function createBuffer( attribute, bufferType ) {
  9340. var array = attribute.array;
  9341. var usage = attribute.dynamic ? 35048 : 35044;
  9342. var buffer = gl.createBuffer();
  9343. gl.bindBuffer( bufferType, buffer );
  9344. gl.bufferData( bufferType, array, usage );
  9345. attribute.onUploadCallback();
  9346. var type = 5126;
  9347. if ( array instanceof Float32Array ) {
  9348. type = 5126;
  9349. } else if ( array instanceof Float64Array ) {
  9350. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  9351. } else if ( array instanceof Uint16Array ) {
  9352. type = 5123;
  9353. } else if ( array instanceof Int16Array ) {
  9354. type = 5122;
  9355. } else if ( array instanceof Uint32Array ) {
  9356. type = 5125;
  9357. } else if ( array instanceof Int32Array ) {
  9358. type = 5124;
  9359. } else if ( array instanceof Int8Array ) {
  9360. type = 5120;
  9361. } else if ( array instanceof Uint8Array ) {
  9362. type = 5121;
  9363. }
  9364. return {
  9365. buffer: buffer,
  9366. type: type,
  9367. bytesPerElement: array.BYTES_PER_ELEMENT,
  9368. version: attribute.version
  9369. };
  9370. }
  9371. function updateBuffer( buffer, attribute, bufferType ) {
  9372. var array = attribute.array;
  9373. var updateRange = attribute.updateRange;
  9374. gl.bindBuffer( bufferType, buffer );
  9375. if ( attribute.dynamic === false ) {
  9376. gl.bufferData( bufferType, array, 35044 );
  9377. } else if ( updateRange.count === - 1 ) {
  9378. // Not using update ranges
  9379. gl.bufferSubData( bufferType, 0, array );
  9380. } else if ( updateRange.count === 0 ) {
  9381. 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.' );
  9382. } else {
  9383. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  9384. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  9385. updateRange.count = - 1; // reset range
  9386. }
  9387. }
  9388. //
  9389. function get( attribute ) {
  9390. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9391. return buffers.get( attribute );
  9392. }
  9393. function remove( attribute ) {
  9394. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9395. var data = buffers.get( attribute );
  9396. if ( data ) {
  9397. gl.deleteBuffer( data.buffer );
  9398. buffers.delete( attribute );
  9399. }
  9400. }
  9401. function update( attribute, bufferType ) {
  9402. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  9403. var data = buffers.get( attribute );
  9404. if ( data === undefined ) {
  9405. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  9406. } else if ( data.version < attribute.version ) {
  9407. updateBuffer( data.buffer, attribute, bufferType );
  9408. data.version = attribute.version;
  9409. }
  9410. }
  9411. return {
  9412. get: get,
  9413. remove: remove,
  9414. update: update
  9415. };
  9416. }
  9417. /**
  9418. * @author mrdoob / http://mrdoob.com/
  9419. * @author alteredq / http://alteredqualia.com/
  9420. */
  9421. function Face3( a, b, c, normal, color, materialIndex ) {
  9422. this.a = a;
  9423. this.b = b;
  9424. this.c = c;
  9425. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  9426. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  9427. this.color = ( color && color.isColor ) ? color : new Color();
  9428. this.vertexColors = Array.isArray( color ) ? color : [];
  9429. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  9430. }
  9431. Object.assign( Face3.prototype, {
  9432. clone: function () {
  9433. return new this.constructor().copy( this );
  9434. },
  9435. copy: function ( source ) {
  9436. this.a = source.a;
  9437. this.b = source.b;
  9438. this.c = source.c;
  9439. this.normal.copy( source.normal );
  9440. this.color.copy( source.color );
  9441. this.materialIndex = source.materialIndex;
  9442. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  9443. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  9444. }
  9445. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  9446. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  9447. }
  9448. return this;
  9449. }
  9450. } );
  9451. /**
  9452. * @author mrdoob / http://mrdoob.com/
  9453. * @author WestLangley / http://github.com/WestLangley
  9454. * @author bhouston / http://clara.io
  9455. */
  9456. function Euler( x, y, z, order ) {
  9457. this._x = x || 0;
  9458. this._y = y || 0;
  9459. this._z = z || 0;
  9460. this._order = order || Euler.DefaultOrder;
  9461. }
  9462. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  9463. Euler.DefaultOrder = 'XYZ';
  9464. Object.defineProperties( Euler.prototype, {
  9465. x: {
  9466. get: function () {
  9467. return this._x;
  9468. },
  9469. set: function ( value ) {
  9470. this._x = value;
  9471. this.onChangeCallback();
  9472. }
  9473. },
  9474. y: {
  9475. get: function () {
  9476. return this._y;
  9477. },
  9478. set: function ( value ) {
  9479. this._y = value;
  9480. this.onChangeCallback();
  9481. }
  9482. },
  9483. z: {
  9484. get: function () {
  9485. return this._z;
  9486. },
  9487. set: function ( value ) {
  9488. this._z = value;
  9489. this.onChangeCallback();
  9490. }
  9491. },
  9492. order: {
  9493. get: function () {
  9494. return this._order;
  9495. },
  9496. set: function ( value ) {
  9497. this._order = value;
  9498. this.onChangeCallback();
  9499. }
  9500. }
  9501. } );
  9502. Object.assign( Euler.prototype, {
  9503. isEuler: true,
  9504. set: function ( x, y, z, order ) {
  9505. this._x = x;
  9506. this._y = y;
  9507. this._z = z;
  9508. this._order = order || this._order;
  9509. this.onChangeCallback();
  9510. return this;
  9511. },
  9512. clone: function () {
  9513. return new this.constructor( this._x, this._y, this._z, this._order );
  9514. },
  9515. copy: function ( euler ) {
  9516. this._x = euler._x;
  9517. this._y = euler._y;
  9518. this._z = euler._z;
  9519. this._order = euler._order;
  9520. this.onChangeCallback();
  9521. return this;
  9522. },
  9523. setFromRotationMatrix: function ( m, order, update ) {
  9524. var clamp = _Math.clamp;
  9525. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9526. var te = m.elements;
  9527. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9528. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9529. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9530. order = order || this._order;
  9531. if ( order === 'XYZ' ) {
  9532. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  9533. if ( Math.abs( m13 ) < 0.99999 ) {
  9534. this._x = Math.atan2( - m23, m33 );
  9535. this._z = Math.atan2( - m12, m11 );
  9536. } else {
  9537. this._x = Math.atan2( m32, m22 );
  9538. this._z = 0;
  9539. }
  9540. } else if ( order === 'YXZ' ) {
  9541. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  9542. if ( Math.abs( m23 ) < 0.99999 ) {
  9543. this._y = Math.atan2( m13, m33 );
  9544. this._z = Math.atan2( m21, m22 );
  9545. } else {
  9546. this._y = Math.atan2( - m31, m11 );
  9547. this._z = 0;
  9548. }
  9549. } else if ( order === 'ZXY' ) {
  9550. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  9551. if ( Math.abs( m32 ) < 0.99999 ) {
  9552. this._y = Math.atan2( - m31, m33 );
  9553. this._z = Math.atan2( - m12, m22 );
  9554. } else {
  9555. this._y = 0;
  9556. this._z = Math.atan2( m21, m11 );
  9557. }
  9558. } else if ( order === 'ZYX' ) {
  9559. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  9560. if ( Math.abs( m31 ) < 0.99999 ) {
  9561. this._x = Math.atan2( m32, m33 );
  9562. this._z = Math.atan2( m21, m11 );
  9563. } else {
  9564. this._x = 0;
  9565. this._z = Math.atan2( - m12, m22 );
  9566. }
  9567. } else if ( order === 'YZX' ) {
  9568. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  9569. if ( Math.abs( m21 ) < 0.99999 ) {
  9570. this._x = Math.atan2( - m23, m22 );
  9571. this._y = Math.atan2( - m31, m11 );
  9572. } else {
  9573. this._x = 0;
  9574. this._y = Math.atan2( m13, m33 );
  9575. }
  9576. } else if ( order === 'XZY' ) {
  9577. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  9578. if ( Math.abs( m12 ) < 0.99999 ) {
  9579. this._x = Math.atan2( m32, m22 );
  9580. this._y = Math.atan2( m13, m11 );
  9581. } else {
  9582. this._x = Math.atan2( - m23, m33 );
  9583. this._y = 0;
  9584. }
  9585. } else {
  9586. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  9587. }
  9588. this._order = order;
  9589. if ( update !== false ) this.onChangeCallback();
  9590. return this;
  9591. },
  9592. setFromQuaternion: function () {
  9593. var matrix = new Matrix4();
  9594. return function setFromQuaternion( q, order, update ) {
  9595. matrix.makeRotationFromQuaternion( q );
  9596. return this.setFromRotationMatrix( matrix, order, update );
  9597. };
  9598. }(),
  9599. setFromVector3: function ( v, order ) {
  9600. return this.set( v.x, v.y, v.z, order || this._order );
  9601. },
  9602. reorder: function () {
  9603. // WARNING: this discards revolution information -bhouston
  9604. var q = new Quaternion();
  9605. return function reorder( newOrder ) {
  9606. q.setFromEuler( this );
  9607. return this.setFromQuaternion( q, newOrder );
  9608. };
  9609. }(),
  9610. equals: function ( euler ) {
  9611. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9612. },
  9613. fromArray: function ( array ) {
  9614. this._x = array[ 0 ];
  9615. this._y = array[ 1 ];
  9616. this._z = array[ 2 ];
  9617. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9618. this.onChangeCallback();
  9619. return this;
  9620. },
  9621. toArray: function ( array, offset ) {
  9622. if ( array === undefined ) array = [];
  9623. if ( offset === undefined ) offset = 0;
  9624. array[ offset ] = this._x;
  9625. array[ offset + 1 ] = this._y;
  9626. array[ offset + 2 ] = this._z;
  9627. array[ offset + 3 ] = this._order;
  9628. return array;
  9629. },
  9630. toVector3: function ( optionalResult ) {
  9631. if ( optionalResult ) {
  9632. return optionalResult.set( this._x, this._y, this._z );
  9633. } else {
  9634. return new Vector3( this._x, this._y, this._z );
  9635. }
  9636. },
  9637. onChange: function ( callback ) {
  9638. this.onChangeCallback = callback;
  9639. return this;
  9640. },
  9641. onChangeCallback: function () {}
  9642. } );
  9643. /**
  9644. * @author mrdoob / http://mrdoob.com/
  9645. */
  9646. function Layers() {
  9647. this.mask = 1 | 0;
  9648. }
  9649. Object.assign( Layers.prototype, {
  9650. set: function ( channel ) {
  9651. this.mask = 1 << channel | 0;
  9652. },
  9653. enable: function ( channel ) {
  9654. this.mask |= 1 << channel | 0;
  9655. },
  9656. toggle: function ( channel ) {
  9657. this.mask ^= 1 << channel | 0;
  9658. },
  9659. disable: function ( channel ) {
  9660. this.mask &= ~ ( 1 << channel | 0 );
  9661. },
  9662. test: function ( layers ) {
  9663. return ( this.mask & layers.mask ) !== 0;
  9664. }
  9665. } );
  9666. /**
  9667. * @author mrdoob / http://mrdoob.com/
  9668. * @author mikael emtinger / http://gomo.se/
  9669. * @author alteredq / http://alteredqualia.com/
  9670. * @author WestLangley / http://github.com/WestLangley
  9671. * @author elephantatwork / www.elephantatwork.ch
  9672. */
  9673. var object3DId = 0;
  9674. function Object3D() {
  9675. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  9676. this.uuid = _Math.generateUUID();
  9677. this.name = '';
  9678. this.type = 'Object3D';
  9679. this.parent = null;
  9680. this.children = [];
  9681. this.up = Object3D.DefaultUp.clone();
  9682. var position = new Vector3();
  9683. var rotation = new Euler();
  9684. var quaternion = new Quaternion();
  9685. var scale = new Vector3( 1, 1, 1 );
  9686. function onRotationChange() {
  9687. quaternion.setFromEuler( rotation, false );
  9688. }
  9689. function onQuaternionChange() {
  9690. rotation.setFromQuaternion( quaternion, undefined, false );
  9691. }
  9692. rotation.onChange( onRotationChange );
  9693. quaternion.onChange( onQuaternionChange );
  9694. Object.defineProperties( this, {
  9695. position: {
  9696. configurable: true,
  9697. enumerable: true,
  9698. value: position
  9699. },
  9700. rotation: {
  9701. configurable: true,
  9702. enumerable: true,
  9703. value: rotation
  9704. },
  9705. quaternion: {
  9706. configurable: true,
  9707. enumerable: true,
  9708. value: quaternion
  9709. },
  9710. scale: {
  9711. configurable: true,
  9712. enumerable: true,
  9713. value: scale
  9714. },
  9715. modelViewMatrix: {
  9716. value: new Matrix4()
  9717. },
  9718. normalMatrix: {
  9719. value: new Matrix3()
  9720. }
  9721. } );
  9722. this.matrix = new Matrix4();
  9723. this.matrixWorld = new Matrix4();
  9724. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  9725. this.matrixWorldNeedsUpdate = false;
  9726. this.layers = new Layers();
  9727. this.visible = true;
  9728. this.castShadow = false;
  9729. this.receiveShadow = false;
  9730. this.frustumCulled = true;
  9731. this.renderOrder = 0;
  9732. this.userData = {};
  9733. }
  9734. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  9735. Object3D.DefaultMatrixAutoUpdate = true;
  9736. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9737. constructor: Object3D,
  9738. isObject3D: true,
  9739. onBeforeRender: function () {},
  9740. onAfterRender: function () {},
  9741. applyMatrix: function ( matrix ) {
  9742. this.matrix.multiplyMatrices( matrix, this.matrix );
  9743. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9744. },
  9745. applyQuaternion: function ( q ) {
  9746. this.quaternion.premultiply( q );
  9747. return this;
  9748. },
  9749. setRotationFromAxisAngle: function ( axis, angle ) {
  9750. // assumes axis is normalized
  9751. this.quaternion.setFromAxisAngle( axis, angle );
  9752. },
  9753. setRotationFromEuler: function ( euler ) {
  9754. this.quaternion.setFromEuler( euler, true );
  9755. },
  9756. setRotationFromMatrix: function ( m ) {
  9757. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9758. this.quaternion.setFromRotationMatrix( m );
  9759. },
  9760. setRotationFromQuaternion: function ( q ) {
  9761. // assumes q is normalized
  9762. this.quaternion.copy( q );
  9763. },
  9764. rotateOnAxis: function () {
  9765. // rotate object on axis in object space
  9766. // axis is assumed to be normalized
  9767. var q1 = new Quaternion();
  9768. return function rotateOnAxis( axis, angle ) {
  9769. q1.setFromAxisAngle( axis, angle );
  9770. this.quaternion.multiply( q1 );
  9771. return this;
  9772. };
  9773. }(),
  9774. rotateOnWorldAxis: function () {
  9775. // rotate object on axis in world space
  9776. // axis is assumed to be normalized
  9777. // method assumes no rotated parent
  9778. var q1 = new Quaternion();
  9779. return function rotateOnWorldAxis( axis, angle ) {
  9780. q1.setFromAxisAngle( axis, angle );
  9781. this.quaternion.premultiply( q1 );
  9782. return this;
  9783. };
  9784. }(),
  9785. rotateX: function () {
  9786. var v1 = new Vector3( 1, 0, 0 );
  9787. return function rotateX( angle ) {
  9788. return this.rotateOnAxis( v1, angle );
  9789. };
  9790. }(),
  9791. rotateY: function () {
  9792. var v1 = new Vector3( 0, 1, 0 );
  9793. return function rotateY( angle ) {
  9794. return this.rotateOnAxis( v1, angle );
  9795. };
  9796. }(),
  9797. rotateZ: function () {
  9798. var v1 = new Vector3( 0, 0, 1 );
  9799. return function rotateZ( angle ) {
  9800. return this.rotateOnAxis( v1, angle );
  9801. };
  9802. }(),
  9803. translateOnAxis: function () {
  9804. // translate object by distance along axis in object space
  9805. // axis is assumed to be normalized
  9806. var v1 = new Vector3();
  9807. return function translateOnAxis( axis, distance ) {
  9808. v1.copy( axis ).applyQuaternion( this.quaternion );
  9809. this.position.add( v1.multiplyScalar( distance ) );
  9810. return this;
  9811. };
  9812. }(),
  9813. translateX: function () {
  9814. var v1 = new Vector3( 1, 0, 0 );
  9815. return function translateX( distance ) {
  9816. return this.translateOnAxis( v1, distance );
  9817. };
  9818. }(),
  9819. translateY: function () {
  9820. var v1 = new Vector3( 0, 1, 0 );
  9821. return function translateY( distance ) {
  9822. return this.translateOnAxis( v1, distance );
  9823. };
  9824. }(),
  9825. translateZ: function () {
  9826. var v1 = new Vector3( 0, 0, 1 );
  9827. return function translateZ( distance ) {
  9828. return this.translateOnAxis( v1, distance );
  9829. };
  9830. }(),
  9831. localToWorld: function ( vector ) {
  9832. return vector.applyMatrix4( this.matrixWorld );
  9833. },
  9834. worldToLocal: function () {
  9835. var m1 = new Matrix4();
  9836. return function worldToLocal( vector ) {
  9837. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  9838. };
  9839. }(),
  9840. lookAt: function () {
  9841. // This method does not support objects having non-uniformly-scaled parent(s)
  9842. var q1 = new Quaternion();
  9843. var m1 = new Matrix4();
  9844. var target = new Vector3();
  9845. var position = new Vector3();
  9846. return function lookAt( x, y, z ) {
  9847. if ( x.isVector3 ) {
  9848. target.copy( x );
  9849. } else {
  9850. target.set( x, y, z );
  9851. }
  9852. var parent = this.parent;
  9853. this.updateWorldMatrix( true, false );
  9854. position.setFromMatrixPosition( this.matrixWorld );
  9855. if ( this.isCamera || this.isLight ) {
  9856. m1.lookAt( position, target, this.up );
  9857. } else {
  9858. m1.lookAt( target, position, this.up );
  9859. }
  9860. this.quaternion.setFromRotationMatrix( m1 );
  9861. if ( parent ) {
  9862. m1.extractRotation( parent.matrixWorld );
  9863. q1.setFromRotationMatrix( m1 );
  9864. this.quaternion.premultiply( q1.inverse() );
  9865. }
  9866. };
  9867. }(),
  9868. add: function ( object ) {
  9869. if ( arguments.length > 1 ) {
  9870. for ( var i = 0; i < arguments.length; i ++ ) {
  9871. this.add( arguments[ i ] );
  9872. }
  9873. return this;
  9874. }
  9875. if ( object === this ) {
  9876. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  9877. return this;
  9878. }
  9879. if ( ( object && object.isObject3D ) ) {
  9880. if ( object.parent !== null ) {
  9881. object.parent.remove( object );
  9882. }
  9883. object.parent = this;
  9884. object.dispatchEvent( { type: 'added' } );
  9885. this.children.push( object );
  9886. } else {
  9887. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  9888. }
  9889. return this;
  9890. },
  9891. remove: function ( object ) {
  9892. if ( arguments.length > 1 ) {
  9893. for ( var i = 0; i < arguments.length; i ++ ) {
  9894. this.remove( arguments[ i ] );
  9895. }
  9896. return this;
  9897. }
  9898. var index = this.children.indexOf( object );
  9899. if ( index !== - 1 ) {
  9900. object.parent = null;
  9901. object.dispatchEvent( { type: 'removed' } );
  9902. this.children.splice( index, 1 );
  9903. }
  9904. return this;
  9905. },
  9906. getObjectById: function ( id ) {
  9907. return this.getObjectByProperty( 'id', id );
  9908. },
  9909. getObjectByName: function ( name ) {
  9910. return this.getObjectByProperty( 'name', name );
  9911. },
  9912. getObjectByProperty: function ( name, value ) {
  9913. if ( this[ name ] === value ) return this;
  9914. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9915. var child = this.children[ i ];
  9916. var object = child.getObjectByProperty( name, value );
  9917. if ( object !== undefined ) {
  9918. return object;
  9919. }
  9920. }
  9921. return undefined;
  9922. },
  9923. getWorldPosition: function ( target ) {
  9924. if ( target === undefined ) {
  9925. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  9926. target = new Vector3();
  9927. }
  9928. this.updateMatrixWorld( true );
  9929. return target.setFromMatrixPosition( this.matrixWorld );
  9930. },
  9931. getWorldQuaternion: function () {
  9932. var position = new Vector3();
  9933. var scale = new Vector3();
  9934. return function getWorldQuaternion( target ) {
  9935. if ( target === undefined ) {
  9936. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  9937. target = new Quaternion();
  9938. }
  9939. this.updateMatrixWorld( true );
  9940. this.matrixWorld.decompose( position, target, scale );
  9941. return target;
  9942. };
  9943. }(),
  9944. getWorldScale: function () {
  9945. var position = new Vector3();
  9946. var quaternion = new Quaternion();
  9947. return function getWorldScale( target ) {
  9948. if ( target === undefined ) {
  9949. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  9950. target = new Vector3();
  9951. }
  9952. this.updateMatrixWorld( true );
  9953. this.matrixWorld.decompose( position, quaternion, target );
  9954. return target;
  9955. };
  9956. }(),
  9957. getWorldDirection: function ( target ) {
  9958. if ( target === undefined ) {
  9959. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  9960. target = new Vector3();
  9961. }
  9962. this.updateMatrixWorld( true );
  9963. var e = this.matrixWorld.elements;
  9964. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9965. },
  9966. raycast: function () {},
  9967. traverse: function ( callback ) {
  9968. callback( this );
  9969. var children = this.children;
  9970. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9971. children[ i ].traverse( callback );
  9972. }
  9973. },
  9974. traverseVisible: function ( callback ) {
  9975. if ( this.visible === false ) return;
  9976. callback( this );
  9977. var children = this.children;
  9978. for ( var i = 0, l = children.length; i < l; i ++ ) {
  9979. children[ i ].traverseVisible( callback );
  9980. }
  9981. },
  9982. traverseAncestors: function ( callback ) {
  9983. var parent = this.parent;
  9984. if ( parent !== null ) {
  9985. callback( parent );
  9986. parent.traverseAncestors( callback );
  9987. }
  9988. },
  9989. updateMatrix: function () {
  9990. this.matrix.compose( this.position, this.quaternion, this.scale );
  9991. this.matrixWorldNeedsUpdate = true;
  9992. },
  9993. updateMatrixWorld: function ( force ) {
  9994. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9995. if ( this.matrixWorldNeedsUpdate || force ) {
  9996. if ( this.parent === null ) {
  9997. this.matrixWorld.copy( this.matrix );
  9998. } else {
  9999. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10000. }
  10001. this.matrixWorldNeedsUpdate = false;
  10002. force = true;
  10003. }
  10004. // update children
  10005. var children = this.children;
  10006. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10007. children[ i ].updateMatrixWorld( force );
  10008. }
  10009. },
  10010. updateWorldMatrix: function ( updateParents, updateChildren ) {
  10011. var parent = this.parent;
  10012. if ( updateParents === true && parent !== null ) {
  10013. parent.updateWorldMatrix( true, false );
  10014. }
  10015. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10016. if ( this.parent === null ) {
  10017. this.matrixWorld.copy( this.matrix );
  10018. } else {
  10019. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10020. }
  10021. // update children
  10022. if ( updateChildren === true ) {
  10023. var children = this.children;
  10024. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10025. children[ i ].updateWorldMatrix( false, true );
  10026. }
  10027. }
  10028. },
  10029. toJSON: function ( meta ) {
  10030. // meta is a string when called from JSON.stringify
  10031. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  10032. var output = {};
  10033. // meta is a hash used to collect geometries, materials.
  10034. // not providing it implies that this is the root object
  10035. // being serialized.
  10036. if ( isRootObject ) {
  10037. // initialize meta obj
  10038. meta = {
  10039. geometries: {},
  10040. materials: {},
  10041. textures: {},
  10042. images: {},
  10043. shapes: {}
  10044. };
  10045. output.metadata = {
  10046. version: 4.5,
  10047. type: 'Object',
  10048. generator: 'Object3D.toJSON'
  10049. };
  10050. }
  10051. // standard Object3D serialization
  10052. var object = {};
  10053. object.uuid = this.uuid;
  10054. object.type = this.type;
  10055. if ( this.name !== '' ) object.name = this.name;
  10056. if ( this.castShadow === true ) object.castShadow = true;
  10057. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10058. if ( this.visible === false ) object.visible = false;
  10059. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10060. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10061. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  10062. object.layers = this.layers.mask;
  10063. object.matrix = this.matrix.toArray();
  10064. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10065. // object specific properties
  10066. if ( this.isMesh && this.drawMode !== TrianglesDrawMode ) object.drawMode = this.drawMode;
  10067. //
  10068. function serialize( library, element ) {
  10069. if ( library[ element.uuid ] === undefined ) {
  10070. library[ element.uuid ] = element.toJSON( meta );
  10071. }
  10072. return element.uuid;
  10073. }
  10074. if ( this.isMesh || this.isLine || this.isPoints ) {
  10075. object.geometry = serialize( meta.geometries, this.geometry );
  10076. var parameters = this.geometry.parameters;
  10077. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10078. var shapes = parameters.shapes;
  10079. if ( Array.isArray( shapes ) ) {
  10080. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  10081. var shape = shapes[ i ];
  10082. serialize( meta.shapes, shape );
  10083. }
  10084. } else {
  10085. serialize( meta.shapes, shapes );
  10086. }
  10087. }
  10088. }
  10089. if ( this.material !== undefined ) {
  10090. if ( Array.isArray( this.material ) ) {
  10091. var uuids = [];
  10092. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  10093. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10094. }
  10095. object.material = uuids;
  10096. } else {
  10097. object.material = serialize( meta.materials, this.material );
  10098. }
  10099. }
  10100. //
  10101. if ( this.children.length > 0 ) {
  10102. object.children = [];
  10103. for ( var i = 0; i < this.children.length; i ++ ) {
  10104. object.children.push( this.children[ i ].toJSON( meta ).object );
  10105. }
  10106. }
  10107. if ( isRootObject ) {
  10108. var geometries = extractFromCache( meta.geometries );
  10109. var materials = extractFromCache( meta.materials );
  10110. var textures = extractFromCache( meta.textures );
  10111. var images = extractFromCache( meta.images );
  10112. var shapes = extractFromCache( meta.shapes );
  10113. if ( geometries.length > 0 ) output.geometries = geometries;
  10114. if ( materials.length > 0 ) output.materials = materials;
  10115. if ( textures.length > 0 ) output.textures = textures;
  10116. if ( images.length > 0 ) output.images = images;
  10117. if ( shapes.length > 0 ) output.shapes = shapes;
  10118. }
  10119. output.object = object;
  10120. return output;
  10121. // extract data from the cache hash
  10122. // remove metadata on each item
  10123. // and return as array
  10124. function extractFromCache( cache ) {
  10125. var values = [];
  10126. for ( var key in cache ) {
  10127. var data = cache[ key ];
  10128. delete data.metadata;
  10129. values.push( data );
  10130. }
  10131. return values;
  10132. }
  10133. },
  10134. clone: function ( recursive ) {
  10135. return new this.constructor().copy( this, recursive );
  10136. },
  10137. copy: function ( source, recursive ) {
  10138. if ( recursive === undefined ) recursive = true;
  10139. this.name = source.name;
  10140. this.up.copy( source.up );
  10141. this.position.copy( source.position );
  10142. this.quaternion.copy( source.quaternion );
  10143. this.scale.copy( source.scale );
  10144. this.matrix.copy( source.matrix );
  10145. this.matrixWorld.copy( source.matrixWorld );
  10146. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10147. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10148. this.layers.mask = source.layers.mask;
  10149. this.visible = source.visible;
  10150. this.castShadow = source.castShadow;
  10151. this.receiveShadow = source.receiveShadow;
  10152. this.frustumCulled = source.frustumCulled;
  10153. this.renderOrder = source.renderOrder;
  10154. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10155. if ( recursive === true ) {
  10156. for ( var i = 0; i < source.children.length; i ++ ) {
  10157. var child = source.children[ i ];
  10158. this.add( child.clone() );
  10159. }
  10160. }
  10161. return this;
  10162. }
  10163. } );
  10164. /**
  10165. * @author mrdoob / http://mrdoob.com/
  10166. * @author kile / http://kile.stravaganza.org/
  10167. * @author alteredq / http://alteredqualia.com/
  10168. * @author mikael emtinger / http://gomo.se/
  10169. * @author zz85 / http://www.lab4games.net/zz85/blog
  10170. * @author bhouston / http://clara.io
  10171. */
  10172. var geometryId = 0; // Geometry uses even numbers as Id
  10173. function Geometry() {
  10174. Object.defineProperty( this, 'id', { value: geometryId += 2 } );
  10175. this.uuid = _Math.generateUUID();
  10176. this.name = '';
  10177. this.type = 'Geometry';
  10178. this.vertices = [];
  10179. this.colors = [];
  10180. this.faces = [];
  10181. this.faceVertexUvs = [[]];
  10182. this.morphTargets = [];
  10183. this.morphNormals = [];
  10184. this.skinWeights = [];
  10185. this.skinIndices = [];
  10186. this.lineDistances = [];
  10187. this.boundingBox = null;
  10188. this.boundingSphere = null;
  10189. // update flags
  10190. this.elementsNeedUpdate = false;
  10191. this.verticesNeedUpdate = false;
  10192. this.uvsNeedUpdate = false;
  10193. this.normalsNeedUpdate = false;
  10194. this.colorsNeedUpdate = false;
  10195. this.lineDistancesNeedUpdate = false;
  10196. this.groupsNeedUpdate = false;
  10197. }
  10198. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10199. constructor: Geometry,
  10200. isGeometry: true,
  10201. applyMatrix: function ( matrix ) {
  10202. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10203. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  10204. var vertex = this.vertices[ i ];
  10205. vertex.applyMatrix4( matrix );
  10206. }
  10207. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  10208. var face = this.faces[ i ];
  10209. face.normal.applyMatrix3( normalMatrix ).normalize();
  10210. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  10211. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  10212. }
  10213. }
  10214. if ( this.boundingBox !== null ) {
  10215. this.computeBoundingBox();
  10216. }
  10217. if ( this.boundingSphere !== null ) {
  10218. this.computeBoundingSphere();
  10219. }
  10220. this.verticesNeedUpdate = true;
  10221. this.normalsNeedUpdate = true;
  10222. return this;
  10223. },
  10224. rotateX: function () {
  10225. // rotate geometry around world x-axis
  10226. var m1 = new Matrix4();
  10227. return function rotateX( angle ) {
  10228. m1.makeRotationX( angle );
  10229. this.applyMatrix( m1 );
  10230. return this;
  10231. };
  10232. }(),
  10233. rotateY: function () {
  10234. // rotate geometry around world y-axis
  10235. var m1 = new Matrix4();
  10236. return function rotateY( angle ) {
  10237. m1.makeRotationY( angle );
  10238. this.applyMatrix( m1 );
  10239. return this;
  10240. };
  10241. }(),
  10242. rotateZ: function () {
  10243. // rotate geometry around world z-axis
  10244. var m1 = new Matrix4();
  10245. return function rotateZ( angle ) {
  10246. m1.makeRotationZ( angle );
  10247. this.applyMatrix( m1 );
  10248. return this;
  10249. };
  10250. }(),
  10251. translate: function () {
  10252. // translate geometry
  10253. var m1 = new Matrix4();
  10254. return function translate( x, y, z ) {
  10255. m1.makeTranslation( x, y, z );
  10256. this.applyMatrix( m1 );
  10257. return this;
  10258. };
  10259. }(),
  10260. scale: function () {
  10261. // scale geometry
  10262. var m1 = new Matrix4();
  10263. return function scale( x, y, z ) {
  10264. m1.makeScale( x, y, z );
  10265. this.applyMatrix( m1 );
  10266. return this;
  10267. };
  10268. }(),
  10269. lookAt: function () {
  10270. var obj = new Object3D();
  10271. return function lookAt( vector ) {
  10272. obj.lookAt( vector );
  10273. obj.updateMatrix();
  10274. this.applyMatrix( obj.matrix );
  10275. };
  10276. }(),
  10277. fromBufferGeometry: function ( geometry ) {
  10278. var scope = this;
  10279. var indices = geometry.index !== null ? geometry.index.array : undefined;
  10280. var attributes = geometry.attributes;
  10281. var positions = attributes.position.array;
  10282. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  10283. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  10284. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  10285. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  10286. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  10287. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  10288. scope.vertices.push( new Vector3().fromArray( positions, i ) );
  10289. if ( colors !== undefined ) {
  10290. scope.colors.push( new Color().fromArray( colors, i ) );
  10291. }
  10292. }
  10293. function addFace( a, b, c, materialIndex ) {
  10294. var vertexColors = ( colors === undefined ) ? [] : [
  10295. scope.colors[ a ].clone(),
  10296. scope.colors[ b ].clone(),
  10297. scope.colors[ c ].clone() ];
  10298. var vertexNormals = ( normals === undefined ) ? [] : [
  10299. new Vector3().fromArray( normals, a * 3 ),
  10300. new Vector3().fromArray( normals, b * 3 ),
  10301. new Vector3().fromArray( normals, c * 3 )
  10302. ];
  10303. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  10304. scope.faces.push( face );
  10305. if ( uvs !== undefined ) {
  10306. scope.faceVertexUvs[ 0 ].push( [
  10307. new Vector2().fromArray( uvs, a * 2 ),
  10308. new Vector2().fromArray( uvs, b * 2 ),
  10309. new Vector2().fromArray( uvs, c * 2 )
  10310. ] );
  10311. }
  10312. if ( uvs2 !== undefined ) {
  10313. scope.faceVertexUvs[ 1 ].push( [
  10314. new Vector2().fromArray( uvs2, a * 2 ),
  10315. new Vector2().fromArray( uvs2, b * 2 ),
  10316. new Vector2().fromArray( uvs2, c * 2 )
  10317. ] );
  10318. }
  10319. }
  10320. var groups = geometry.groups;
  10321. if ( groups.length > 0 ) {
  10322. for ( var i = 0; i < groups.length; i ++ ) {
  10323. var group = groups[ i ];
  10324. var start = group.start;
  10325. var count = group.count;
  10326. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  10327. if ( indices !== undefined ) {
  10328. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  10329. } else {
  10330. addFace( j, j + 1, j + 2, group.materialIndex );
  10331. }
  10332. }
  10333. }
  10334. } else {
  10335. if ( indices !== undefined ) {
  10336. for ( var i = 0; i < indices.length; i += 3 ) {
  10337. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  10338. }
  10339. } else {
  10340. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  10341. addFace( i, i + 1, i + 2 );
  10342. }
  10343. }
  10344. }
  10345. this.computeFaceNormals();
  10346. if ( geometry.boundingBox !== null ) {
  10347. this.boundingBox = geometry.boundingBox.clone();
  10348. }
  10349. if ( geometry.boundingSphere !== null ) {
  10350. this.boundingSphere = geometry.boundingSphere.clone();
  10351. }
  10352. return this;
  10353. },
  10354. center: function () {
  10355. var offset = new Vector3();
  10356. return function center() {
  10357. this.computeBoundingBox();
  10358. this.boundingBox.getCenter( offset ).negate();
  10359. this.translate( offset.x, offset.y, offset.z );
  10360. return this;
  10361. };
  10362. }(),
  10363. normalize: function () {
  10364. this.computeBoundingSphere();
  10365. var center = this.boundingSphere.center;
  10366. var radius = this.boundingSphere.radius;
  10367. var s = radius === 0 ? 1 : 1.0 / radius;
  10368. var matrix = new Matrix4();
  10369. matrix.set(
  10370. s, 0, 0, - s * center.x,
  10371. 0, s, 0, - s * center.y,
  10372. 0, 0, s, - s * center.z,
  10373. 0, 0, 0, 1
  10374. );
  10375. this.applyMatrix( matrix );
  10376. return this;
  10377. },
  10378. computeFaceNormals: function () {
  10379. var cb = new Vector3(), ab = new Vector3();
  10380. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10381. var face = this.faces[ f ];
  10382. var vA = this.vertices[ face.a ];
  10383. var vB = this.vertices[ face.b ];
  10384. var vC = this.vertices[ face.c ];
  10385. cb.subVectors( vC, vB );
  10386. ab.subVectors( vA, vB );
  10387. cb.cross( ab );
  10388. cb.normalize();
  10389. face.normal.copy( cb );
  10390. }
  10391. },
  10392. computeVertexNormals: function ( areaWeighted ) {
  10393. if ( areaWeighted === undefined ) areaWeighted = true;
  10394. var v, vl, f, fl, face, vertices;
  10395. vertices = new Array( this.vertices.length );
  10396. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  10397. vertices[ v ] = new Vector3();
  10398. }
  10399. if ( areaWeighted ) {
  10400. // vertex normals weighted by triangle areas
  10401. // http://www.iquilezles.org/www/articles/normals/normals.htm
  10402. var vA, vB, vC;
  10403. var cb = new Vector3(), ab = new Vector3();
  10404. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10405. face = this.faces[ f ];
  10406. vA = this.vertices[ face.a ];
  10407. vB = this.vertices[ face.b ];
  10408. vC = this.vertices[ face.c ];
  10409. cb.subVectors( vC, vB );
  10410. ab.subVectors( vA, vB );
  10411. cb.cross( ab );
  10412. vertices[ face.a ].add( cb );
  10413. vertices[ face.b ].add( cb );
  10414. vertices[ face.c ].add( cb );
  10415. }
  10416. } else {
  10417. this.computeFaceNormals();
  10418. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10419. face = this.faces[ f ];
  10420. vertices[ face.a ].add( face.normal );
  10421. vertices[ face.b ].add( face.normal );
  10422. vertices[ face.c ].add( face.normal );
  10423. }
  10424. }
  10425. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  10426. vertices[ v ].normalize();
  10427. }
  10428. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10429. face = this.faces[ f ];
  10430. var vertexNormals = face.vertexNormals;
  10431. if ( vertexNormals.length === 3 ) {
  10432. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  10433. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  10434. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  10435. } else {
  10436. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  10437. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  10438. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  10439. }
  10440. }
  10441. if ( this.faces.length > 0 ) {
  10442. this.normalsNeedUpdate = true;
  10443. }
  10444. },
  10445. computeFlatVertexNormals: function () {
  10446. var f, fl, face;
  10447. this.computeFaceNormals();
  10448. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10449. face = this.faces[ f ];
  10450. var vertexNormals = face.vertexNormals;
  10451. if ( vertexNormals.length === 3 ) {
  10452. vertexNormals[ 0 ].copy( face.normal );
  10453. vertexNormals[ 1 ].copy( face.normal );
  10454. vertexNormals[ 2 ].copy( face.normal );
  10455. } else {
  10456. vertexNormals[ 0 ] = face.normal.clone();
  10457. vertexNormals[ 1 ] = face.normal.clone();
  10458. vertexNormals[ 2 ] = face.normal.clone();
  10459. }
  10460. }
  10461. if ( this.faces.length > 0 ) {
  10462. this.normalsNeedUpdate = true;
  10463. }
  10464. },
  10465. computeMorphNormals: function () {
  10466. var i, il, f, fl, face;
  10467. // save original normals
  10468. // - create temp variables on first access
  10469. // otherwise just copy (for faster repeated calls)
  10470. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10471. face = this.faces[ f ];
  10472. if ( ! face.__originalFaceNormal ) {
  10473. face.__originalFaceNormal = face.normal.clone();
  10474. } else {
  10475. face.__originalFaceNormal.copy( face.normal );
  10476. }
  10477. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  10478. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  10479. if ( ! face.__originalVertexNormals[ i ] ) {
  10480. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  10481. } else {
  10482. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  10483. }
  10484. }
  10485. }
  10486. // use temp geometry to compute face and vertex normals for each morph
  10487. var tmpGeo = new Geometry();
  10488. tmpGeo.faces = this.faces;
  10489. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  10490. // create on first access
  10491. if ( ! this.morphNormals[ i ] ) {
  10492. this.morphNormals[ i ] = {};
  10493. this.morphNormals[ i ].faceNormals = [];
  10494. this.morphNormals[ i ].vertexNormals = [];
  10495. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  10496. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  10497. var faceNormal, vertexNormals;
  10498. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10499. faceNormal = new Vector3();
  10500. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  10501. dstNormalsFace.push( faceNormal );
  10502. dstNormalsVertex.push( vertexNormals );
  10503. }
  10504. }
  10505. var morphNormals = this.morphNormals[ i ];
  10506. // set vertices to morph target
  10507. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  10508. // compute morph normals
  10509. tmpGeo.computeFaceNormals();
  10510. tmpGeo.computeVertexNormals();
  10511. // store morph normals
  10512. var faceNormal, vertexNormals;
  10513. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10514. face = this.faces[ f ];
  10515. faceNormal = morphNormals.faceNormals[ f ];
  10516. vertexNormals = morphNormals.vertexNormals[ f ];
  10517. faceNormal.copy( face.normal );
  10518. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  10519. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  10520. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  10521. }
  10522. }
  10523. // restore original normals
  10524. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  10525. face = this.faces[ f ];
  10526. face.normal = face.__originalFaceNormal;
  10527. face.vertexNormals = face.__originalVertexNormals;
  10528. }
  10529. },
  10530. computeBoundingBox: function () {
  10531. if ( this.boundingBox === null ) {
  10532. this.boundingBox = new Box3();
  10533. }
  10534. this.boundingBox.setFromPoints( this.vertices );
  10535. },
  10536. computeBoundingSphere: function () {
  10537. if ( this.boundingSphere === null ) {
  10538. this.boundingSphere = new Sphere();
  10539. }
  10540. this.boundingSphere.setFromPoints( this.vertices );
  10541. },
  10542. merge: function ( geometry, matrix, materialIndexOffset ) {
  10543. if ( ! ( geometry && geometry.isGeometry ) ) {
  10544. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  10545. return;
  10546. }
  10547. var normalMatrix,
  10548. vertexOffset = this.vertices.length,
  10549. vertices1 = this.vertices,
  10550. vertices2 = geometry.vertices,
  10551. faces1 = this.faces,
  10552. faces2 = geometry.faces,
  10553. uvs1 = this.faceVertexUvs[ 0 ],
  10554. uvs2 = geometry.faceVertexUvs[ 0 ],
  10555. colors1 = this.colors,
  10556. colors2 = geometry.colors;
  10557. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  10558. if ( matrix !== undefined ) {
  10559. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  10560. }
  10561. // vertices
  10562. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10563. var vertex = vertices2[ i ];
  10564. var vertexCopy = vertex.clone();
  10565. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  10566. vertices1.push( vertexCopy );
  10567. }
  10568. // colors
  10569. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  10570. colors1.push( colors2[ i ].clone() );
  10571. }
  10572. // faces
  10573. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10574. var face = faces2[ i ], faceCopy, normal, color,
  10575. faceVertexNormals = face.vertexNormals,
  10576. faceVertexColors = face.vertexColors;
  10577. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10578. faceCopy.normal.copy( face.normal );
  10579. if ( normalMatrix !== undefined ) {
  10580. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  10581. }
  10582. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10583. normal = faceVertexNormals[ j ].clone();
  10584. if ( normalMatrix !== undefined ) {
  10585. normal.applyMatrix3( normalMatrix ).normalize();
  10586. }
  10587. faceCopy.vertexNormals.push( normal );
  10588. }
  10589. faceCopy.color.copy( face.color );
  10590. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10591. color = faceVertexColors[ j ];
  10592. faceCopy.vertexColors.push( color.clone() );
  10593. }
  10594. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  10595. faces1.push( faceCopy );
  10596. }
  10597. // uvs
  10598. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10599. var uv = uvs2[ i ], uvCopy = [];
  10600. if ( uv === undefined ) {
  10601. continue;
  10602. }
  10603. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10604. uvCopy.push( uv[ j ].clone() );
  10605. }
  10606. uvs1.push( uvCopy );
  10607. }
  10608. },
  10609. mergeMesh: function ( mesh ) {
  10610. if ( ! ( mesh && mesh.isMesh ) ) {
  10611. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  10612. return;
  10613. }
  10614. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  10615. this.merge( mesh.geometry, mesh.matrix );
  10616. },
  10617. /*
  10618. * Checks for duplicate vertices with hashmap.
  10619. * Duplicated vertices are removed
  10620. * and faces' vertices are updated.
  10621. */
  10622. mergeVertices: function () {
  10623. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  10624. var unique = [], changes = [];
  10625. var v, key;
  10626. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  10627. var precision = Math.pow( 10, precisionPoints );
  10628. var i, il, face;
  10629. var indices, j, jl;
  10630. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  10631. v = this.vertices[ i ];
  10632. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  10633. if ( verticesMap[ key ] === undefined ) {
  10634. verticesMap[ key ] = i;
  10635. unique.push( this.vertices[ i ] );
  10636. changes[ i ] = unique.length - 1;
  10637. } else {
  10638. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  10639. changes[ i ] = changes[ verticesMap[ key ] ];
  10640. }
  10641. }
  10642. // if faces are completely degenerate after merging vertices, we
  10643. // have to remove them from the geometry.
  10644. var faceIndicesToRemove = [];
  10645. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  10646. face = this.faces[ i ];
  10647. face.a = changes[ face.a ];
  10648. face.b = changes[ face.b ];
  10649. face.c = changes[ face.c ];
  10650. indices = [ face.a, face.b, face.c ];
  10651. // if any duplicate vertices are found in a Face3
  10652. // we have to remove the face as nothing can be saved
  10653. for ( var n = 0; n < 3; n ++ ) {
  10654. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  10655. faceIndicesToRemove.push( i );
  10656. break;
  10657. }
  10658. }
  10659. }
  10660. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  10661. var idx = faceIndicesToRemove[ i ];
  10662. this.faces.splice( idx, 1 );
  10663. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  10664. this.faceVertexUvs[ j ].splice( idx, 1 );
  10665. }
  10666. }
  10667. // Use unique set of vertices
  10668. var diff = this.vertices.length - unique.length;
  10669. this.vertices = unique;
  10670. return diff;
  10671. },
  10672. setFromPoints: function ( points ) {
  10673. this.vertices = [];
  10674. for ( var i = 0, l = points.length; i < l; i ++ ) {
  10675. var point = points[ i ];
  10676. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  10677. }
  10678. return this;
  10679. },
  10680. sortFacesByMaterialIndex: function () {
  10681. var faces = this.faces;
  10682. var length = faces.length;
  10683. // tag faces
  10684. for ( var i = 0; i < length; i ++ ) {
  10685. faces[ i ]._id = i;
  10686. }
  10687. // sort faces
  10688. function materialIndexSort( a, b ) {
  10689. return a.materialIndex - b.materialIndex;
  10690. }
  10691. faces.sort( materialIndexSort );
  10692. // sort uvs
  10693. var uvs1 = this.faceVertexUvs[ 0 ];
  10694. var uvs2 = this.faceVertexUvs[ 1 ];
  10695. var newUvs1, newUvs2;
  10696. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  10697. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  10698. for ( var i = 0; i < length; i ++ ) {
  10699. var id = faces[ i ]._id;
  10700. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  10701. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  10702. }
  10703. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  10704. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  10705. },
  10706. toJSON: function () {
  10707. var data = {
  10708. metadata: {
  10709. version: 4.5,
  10710. type: 'Geometry',
  10711. generator: 'Geometry.toJSON'
  10712. }
  10713. };
  10714. // standard Geometry serialization
  10715. data.uuid = this.uuid;
  10716. data.type = this.type;
  10717. if ( this.name !== '' ) data.name = this.name;
  10718. if ( this.parameters !== undefined ) {
  10719. var parameters = this.parameters;
  10720. for ( var key in parameters ) {
  10721. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  10722. }
  10723. return data;
  10724. }
  10725. var vertices = [];
  10726. for ( var i = 0; i < this.vertices.length; i ++ ) {
  10727. var vertex = this.vertices[ i ];
  10728. vertices.push( vertex.x, vertex.y, vertex.z );
  10729. }
  10730. var faces = [];
  10731. var normals = [];
  10732. var normalsHash = {};
  10733. var colors = [];
  10734. var colorsHash = {};
  10735. var uvs = [];
  10736. var uvsHash = {};
  10737. for ( var i = 0; i < this.faces.length; i ++ ) {
  10738. var face = this.faces[ i ];
  10739. var hasMaterial = true;
  10740. var hasFaceUv = false; // deprecated
  10741. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  10742. var hasFaceNormal = face.normal.length() > 0;
  10743. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  10744. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  10745. var hasFaceVertexColor = face.vertexColors.length > 0;
  10746. var faceType = 0;
  10747. faceType = setBit( faceType, 0, 0 ); // isQuad
  10748. faceType = setBit( faceType, 1, hasMaterial );
  10749. faceType = setBit( faceType, 2, hasFaceUv );
  10750. faceType = setBit( faceType, 3, hasFaceVertexUv );
  10751. faceType = setBit( faceType, 4, hasFaceNormal );
  10752. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  10753. faceType = setBit( faceType, 6, hasFaceColor );
  10754. faceType = setBit( faceType, 7, hasFaceVertexColor );
  10755. faces.push( faceType );
  10756. faces.push( face.a, face.b, face.c );
  10757. faces.push( face.materialIndex );
  10758. if ( hasFaceVertexUv ) {
  10759. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  10760. faces.push(
  10761. getUvIndex( faceVertexUvs[ 0 ] ),
  10762. getUvIndex( faceVertexUvs[ 1 ] ),
  10763. getUvIndex( faceVertexUvs[ 2 ] )
  10764. );
  10765. }
  10766. if ( hasFaceNormal ) {
  10767. faces.push( getNormalIndex( face.normal ) );
  10768. }
  10769. if ( hasFaceVertexNormal ) {
  10770. var vertexNormals = face.vertexNormals;
  10771. faces.push(
  10772. getNormalIndex( vertexNormals[ 0 ] ),
  10773. getNormalIndex( vertexNormals[ 1 ] ),
  10774. getNormalIndex( vertexNormals[ 2 ] )
  10775. );
  10776. }
  10777. if ( hasFaceColor ) {
  10778. faces.push( getColorIndex( face.color ) );
  10779. }
  10780. if ( hasFaceVertexColor ) {
  10781. var vertexColors = face.vertexColors;
  10782. faces.push(
  10783. getColorIndex( vertexColors[ 0 ] ),
  10784. getColorIndex( vertexColors[ 1 ] ),
  10785. getColorIndex( vertexColors[ 2 ] )
  10786. );
  10787. }
  10788. }
  10789. function setBit( value, position, enabled ) {
  10790. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  10791. }
  10792. function getNormalIndex( normal ) {
  10793. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  10794. if ( normalsHash[ hash ] !== undefined ) {
  10795. return normalsHash[ hash ];
  10796. }
  10797. normalsHash[ hash ] = normals.length / 3;
  10798. normals.push( normal.x, normal.y, normal.z );
  10799. return normalsHash[ hash ];
  10800. }
  10801. function getColorIndex( color ) {
  10802. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  10803. if ( colorsHash[ hash ] !== undefined ) {
  10804. return colorsHash[ hash ];
  10805. }
  10806. colorsHash[ hash ] = colors.length;
  10807. colors.push( color.getHex() );
  10808. return colorsHash[ hash ];
  10809. }
  10810. function getUvIndex( uv ) {
  10811. var hash = uv.x.toString() + uv.y.toString();
  10812. if ( uvsHash[ hash ] !== undefined ) {
  10813. return uvsHash[ hash ];
  10814. }
  10815. uvsHash[ hash ] = uvs.length / 2;
  10816. uvs.push( uv.x, uv.y );
  10817. return uvsHash[ hash ];
  10818. }
  10819. data.data = {};
  10820. data.data.vertices = vertices;
  10821. data.data.normals = normals;
  10822. if ( colors.length > 0 ) data.data.colors = colors;
  10823. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  10824. data.data.faces = faces;
  10825. return data;
  10826. },
  10827. clone: function () {
  10828. /*
  10829. // Handle primitives
  10830. var parameters = this.parameters;
  10831. if ( parameters !== undefined ) {
  10832. var values = [];
  10833. for ( var key in parameters ) {
  10834. values.push( parameters[ key ] );
  10835. }
  10836. var geometry = Object.create( this.constructor.prototype );
  10837. this.constructor.apply( geometry, values );
  10838. return geometry;
  10839. }
  10840. return new this.constructor().copy( this );
  10841. */
  10842. return new Geometry().copy( this );
  10843. },
  10844. copy: function ( source ) {
  10845. var i, il, j, jl, k, kl;
  10846. // reset
  10847. this.vertices = [];
  10848. this.colors = [];
  10849. this.faces = [];
  10850. this.faceVertexUvs = [[]];
  10851. this.morphTargets = [];
  10852. this.morphNormals = [];
  10853. this.skinWeights = [];
  10854. this.skinIndices = [];
  10855. this.lineDistances = [];
  10856. this.boundingBox = null;
  10857. this.boundingSphere = null;
  10858. // name
  10859. this.name = source.name;
  10860. // vertices
  10861. var vertices = source.vertices;
  10862. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10863. this.vertices.push( vertices[ i ].clone() );
  10864. }
  10865. // colors
  10866. var colors = source.colors;
  10867. for ( i = 0, il = colors.length; i < il; i ++ ) {
  10868. this.colors.push( colors[ i ].clone() );
  10869. }
  10870. // faces
  10871. var faces = source.faces;
  10872. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10873. this.faces.push( faces[ i ].clone() );
  10874. }
  10875. // face vertex uvs
  10876. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  10877. var faceVertexUvs = source.faceVertexUvs[ i ];
  10878. if ( this.faceVertexUvs[ i ] === undefined ) {
  10879. this.faceVertexUvs[ i ] = [];
  10880. }
  10881. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  10882. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  10883. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  10884. var uv = uvs[ k ];
  10885. uvsCopy.push( uv.clone() );
  10886. }
  10887. this.faceVertexUvs[ i ].push( uvsCopy );
  10888. }
  10889. }
  10890. // morph targets
  10891. var morphTargets = source.morphTargets;
  10892. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  10893. var morphTarget = {};
  10894. morphTarget.name = morphTargets[ i ].name;
  10895. // vertices
  10896. if ( morphTargets[ i ].vertices !== undefined ) {
  10897. morphTarget.vertices = [];
  10898. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  10899. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  10900. }
  10901. }
  10902. // normals
  10903. if ( morphTargets[ i ].normals !== undefined ) {
  10904. morphTarget.normals = [];
  10905. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  10906. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  10907. }
  10908. }
  10909. this.morphTargets.push( morphTarget );
  10910. }
  10911. // morph normals
  10912. var morphNormals = source.morphNormals;
  10913. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  10914. var morphNormal = {};
  10915. // vertex normals
  10916. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  10917. morphNormal.vertexNormals = [];
  10918. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  10919. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  10920. var destVertexNormal = {};
  10921. destVertexNormal.a = srcVertexNormal.a.clone();
  10922. destVertexNormal.b = srcVertexNormal.b.clone();
  10923. destVertexNormal.c = srcVertexNormal.c.clone();
  10924. morphNormal.vertexNormals.push( destVertexNormal );
  10925. }
  10926. }
  10927. // face normals
  10928. if ( morphNormals[ i ].faceNormals !== undefined ) {
  10929. morphNormal.faceNormals = [];
  10930. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  10931. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  10932. }
  10933. }
  10934. this.morphNormals.push( morphNormal );
  10935. }
  10936. // skin weights
  10937. var skinWeights = source.skinWeights;
  10938. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  10939. this.skinWeights.push( skinWeights[ i ].clone() );
  10940. }
  10941. // skin indices
  10942. var skinIndices = source.skinIndices;
  10943. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  10944. this.skinIndices.push( skinIndices[ i ].clone() );
  10945. }
  10946. // line distances
  10947. var lineDistances = source.lineDistances;
  10948. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  10949. this.lineDistances.push( lineDistances[ i ] );
  10950. }
  10951. // bounding box
  10952. var boundingBox = source.boundingBox;
  10953. if ( boundingBox !== null ) {
  10954. this.boundingBox = boundingBox.clone();
  10955. }
  10956. // bounding sphere
  10957. var boundingSphere = source.boundingSphere;
  10958. if ( boundingSphere !== null ) {
  10959. this.boundingSphere = boundingSphere.clone();
  10960. }
  10961. // update flags
  10962. this.elementsNeedUpdate = source.elementsNeedUpdate;
  10963. this.verticesNeedUpdate = source.verticesNeedUpdate;
  10964. this.uvsNeedUpdate = source.uvsNeedUpdate;
  10965. this.normalsNeedUpdate = source.normalsNeedUpdate;
  10966. this.colorsNeedUpdate = source.colorsNeedUpdate;
  10967. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  10968. this.groupsNeedUpdate = source.groupsNeedUpdate;
  10969. return this;
  10970. },
  10971. dispose: function () {
  10972. this.dispatchEvent( { type: 'dispose' } );
  10973. }
  10974. } );
  10975. /**
  10976. * @author mrdoob / http://mrdoob.com/
  10977. */
  10978. function BufferAttribute( array, itemSize, normalized ) {
  10979. if ( Array.isArray( array ) ) {
  10980. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  10981. }
  10982. this.name = '';
  10983. this.array = array;
  10984. this.itemSize = itemSize;
  10985. this.count = array !== undefined ? array.length / itemSize : 0;
  10986. this.normalized = normalized === true;
  10987. this.dynamic = false;
  10988. this.updateRange = { offset: 0, count: - 1 };
  10989. this.version = 0;
  10990. }
  10991. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  10992. set: function ( value ) {
  10993. if ( value === true ) this.version ++;
  10994. }
  10995. } );
  10996. Object.assign( BufferAttribute.prototype, {
  10997. isBufferAttribute: true,
  10998. onUploadCallback: function () {},
  10999. setArray: function ( array ) {
  11000. if ( Array.isArray( array ) ) {
  11001. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11002. }
  11003. this.count = array !== undefined ? array.length / this.itemSize : 0;
  11004. this.array = array;
  11005. return this;
  11006. },
  11007. setDynamic: function ( value ) {
  11008. this.dynamic = value;
  11009. return this;
  11010. },
  11011. copy: function ( source ) {
  11012. this.name = source.name;
  11013. this.array = new source.array.constructor( source.array );
  11014. this.itemSize = source.itemSize;
  11015. this.count = source.count;
  11016. this.normalized = source.normalized;
  11017. this.dynamic = source.dynamic;
  11018. return this;
  11019. },
  11020. copyAt: function ( index1, attribute, index2 ) {
  11021. index1 *= this.itemSize;
  11022. index2 *= attribute.itemSize;
  11023. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11024. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11025. }
  11026. return this;
  11027. },
  11028. copyArray: function ( array ) {
  11029. this.array.set( array );
  11030. return this;
  11031. },
  11032. copyColorsArray: function ( colors ) {
  11033. var array = this.array, offset = 0;
  11034. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11035. var color = colors[ i ];
  11036. if ( color === undefined ) {
  11037. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11038. color = new Color();
  11039. }
  11040. array[ offset ++ ] = color.r;
  11041. array[ offset ++ ] = color.g;
  11042. array[ offset ++ ] = color.b;
  11043. }
  11044. return this;
  11045. },
  11046. copyVector2sArray: function ( vectors ) {
  11047. var array = this.array, offset = 0;
  11048. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11049. var vector = vectors[ i ];
  11050. if ( vector === undefined ) {
  11051. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11052. vector = new Vector2();
  11053. }
  11054. array[ offset ++ ] = vector.x;
  11055. array[ offset ++ ] = vector.y;
  11056. }
  11057. return this;
  11058. },
  11059. copyVector3sArray: function ( vectors ) {
  11060. var array = this.array, offset = 0;
  11061. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11062. var vector = vectors[ i ];
  11063. if ( vector === undefined ) {
  11064. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11065. vector = new Vector3();
  11066. }
  11067. array[ offset ++ ] = vector.x;
  11068. array[ offset ++ ] = vector.y;
  11069. array[ offset ++ ] = vector.z;
  11070. }
  11071. return this;
  11072. },
  11073. copyVector4sArray: function ( vectors ) {
  11074. var array = this.array, offset = 0;
  11075. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11076. var vector = vectors[ i ];
  11077. if ( vector === undefined ) {
  11078. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11079. vector = new Vector4();
  11080. }
  11081. array[ offset ++ ] = vector.x;
  11082. array[ offset ++ ] = vector.y;
  11083. array[ offset ++ ] = vector.z;
  11084. array[ offset ++ ] = vector.w;
  11085. }
  11086. return this;
  11087. },
  11088. set: function ( value, offset ) {
  11089. if ( offset === undefined ) offset = 0;
  11090. this.array.set( value, offset );
  11091. return this;
  11092. },
  11093. getX: function ( index ) {
  11094. return this.array[ index * this.itemSize ];
  11095. },
  11096. setX: function ( index, x ) {
  11097. this.array[ index * this.itemSize ] = x;
  11098. return this;
  11099. },
  11100. getY: function ( index ) {
  11101. return this.array[ index * this.itemSize + 1 ];
  11102. },
  11103. setY: function ( index, y ) {
  11104. this.array[ index * this.itemSize + 1 ] = y;
  11105. return this;
  11106. },
  11107. getZ: function ( index ) {
  11108. return this.array[ index * this.itemSize + 2 ];
  11109. },
  11110. setZ: function ( index, z ) {
  11111. this.array[ index * this.itemSize + 2 ] = z;
  11112. return this;
  11113. },
  11114. getW: function ( index ) {
  11115. return this.array[ index * this.itemSize + 3 ];
  11116. },
  11117. setW: function ( index, w ) {
  11118. this.array[ index * this.itemSize + 3 ] = w;
  11119. return this;
  11120. },
  11121. setXY: function ( index, x, y ) {
  11122. index *= this.itemSize;
  11123. this.array[ index + 0 ] = x;
  11124. this.array[ index + 1 ] = y;
  11125. return this;
  11126. },
  11127. setXYZ: function ( index, x, y, z ) {
  11128. index *= this.itemSize;
  11129. this.array[ index + 0 ] = x;
  11130. this.array[ index + 1 ] = y;
  11131. this.array[ index + 2 ] = z;
  11132. return this;
  11133. },
  11134. setXYZW: function ( index, x, y, z, w ) {
  11135. index *= this.itemSize;
  11136. this.array[ index + 0 ] = x;
  11137. this.array[ index + 1 ] = y;
  11138. this.array[ index + 2 ] = z;
  11139. this.array[ index + 3 ] = w;
  11140. return this;
  11141. },
  11142. onUpload: function ( callback ) {
  11143. this.onUploadCallback = callback;
  11144. return this;
  11145. },
  11146. clone: function () {
  11147. return new this.constructor( this.array, this.itemSize ).copy( this );
  11148. }
  11149. } );
  11150. //
  11151. function Int8BufferAttribute( array, itemSize, normalized ) {
  11152. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  11153. }
  11154. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11155. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11156. function Uint8BufferAttribute( array, itemSize, normalized ) {
  11157. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  11158. }
  11159. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11160. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11161. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  11162. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  11163. }
  11164. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11165. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11166. function Int16BufferAttribute( array, itemSize, normalized ) {
  11167. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  11168. }
  11169. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11170. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11171. function Uint16BufferAttribute( array, itemSize, normalized ) {
  11172. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  11173. }
  11174. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11175. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11176. function Int32BufferAttribute( array, itemSize, normalized ) {
  11177. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  11178. }
  11179. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11180. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11181. function Uint32BufferAttribute( array, itemSize, normalized ) {
  11182. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  11183. }
  11184. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11185. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11186. function Float32BufferAttribute( array, itemSize, normalized ) {
  11187. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  11188. }
  11189. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11190. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11191. function Float64BufferAttribute( array, itemSize, normalized ) {
  11192. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  11193. }
  11194. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11195. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11196. /**
  11197. * @author mrdoob / http://mrdoob.com/
  11198. */
  11199. function DirectGeometry() {
  11200. this.vertices = [];
  11201. this.normals = [];
  11202. this.colors = [];
  11203. this.uvs = [];
  11204. this.uvs2 = [];
  11205. this.groups = [];
  11206. this.morphTargets = {};
  11207. this.skinWeights = [];
  11208. this.skinIndices = [];
  11209. // this.lineDistances = [];
  11210. this.boundingBox = null;
  11211. this.boundingSphere = null;
  11212. // update flags
  11213. this.verticesNeedUpdate = false;
  11214. this.normalsNeedUpdate = false;
  11215. this.colorsNeedUpdate = false;
  11216. this.uvsNeedUpdate = false;
  11217. this.groupsNeedUpdate = false;
  11218. }
  11219. Object.assign( DirectGeometry.prototype, {
  11220. computeGroups: function ( geometry ) {
  11221. var group;
  11222. var groups = [];
  11223. var materialIndex = undefined;
  11224. var faces = geometry.faces;
  11225. for ( var i = 0; i < faces.length; i ++ ) {
  11226. var face = faces[ i ];
  11227. // materials
  11228. if ( face.materialIndex !== materialIndex ) {
  11229. materialIndex = face.materialIndex;
  11230. if ( group !== undefined ) {
  11231. group.count = ( i * 3 ) - group.start;
  11232. groups.push( group );
  11233. }
  11234. group = {
  11235. start: i * 3,
  11236. materialIndex: materialIndex
  11237. };
  11238. }
  11239. }
  11240. if ( group !== undefined ) {
  11241. group.count = ( i * 3 ) - group.start;
  11242. groups.push( group );
  11243. }
  11244. this.groups = groups;
  11245. },
  11246. fromGeometry: function ( geometry ) {
  11247. var faces = geometry.faces;
  11248. var vertices = geometry.vertices;
  11249. var faceVertexUvs = geometry.faceVertexUvs;
  11250. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11251. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11252. // morphs
  11253. var morphTargets = geometry.morphTargets;
  11254. var morphTargetsLength = morphTargets.length;
  11255. var morphTargetsPosition;
  11256. if ( morphTargetsLength > 0 ) {
  11257. morphTargetsPosition = [];
  11258. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11259. morphTargetsPosition[ i ] = {
  11260. name: morphTargets[ i ].name,
  11261. data: []
  11262. };
  11263. }
  11264. this.morphTargets.position = morphTargetsPosition;
  11265. }
  11266. var morphNormals = geometry.morphNormals;
  11267. var morphNormalsLength = morphNormals.length;
  11268. var morphTargetsNormal;
  11269. if ( morphNormalsLength > 0 ) {
  11270. morphTargetsNormal = [];
  11271. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11272. morphTargetsNormal[ i ] = {
  11273. name: morphNormals[ i ].name,
  11274. data: []
  11275. };
  11276. }
  11277. this.morphTargets.normal = morphTargetsNormal;
  11278. }
  11279. // skins
  11280. var skinIndices = geometry.skinIndices;
  11281. var skinWeights = geometry.skinWeights;
  11282. var hasSkinIndices = skinIndices.length === vertices.length;
  11283. var hasSkinWeights = skinWeights.length === vertices.length;
  11284. //
  11285. if ( vertices.length > 0 && faces.length === 0 ) {
  11286. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  11287. }
  11288. for ( var i = 0; i < faces.length; i ++ ) {
  11289. var face = faces[ i ];
  11290. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11291. var vertexNormals = face.vertexNormals;
  11292. if ( vertexNormals.length === 3 ) {
  11293. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11294. } else {
  11295. var normal = face.normal;
  11296. this.normals.push( normal, normal, normal );
  11297. }
  11298. var vertexColors = face.vertexColors;
  11299. if ( vertexColors.length === 3 ) {
  11300. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11301. } else {
  11302. var color = face.color;
  11303. this.colors.push( color, color, color );
  11304. }
  11305. if ( hasFaceVertexUv === true ) {
  11306. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  11307. if ( vertexUvs !== undefined ) {
  11308. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11309. } else {
  11310. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  11311. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11312. }
  11313. }
  11314. if ( hasFaceVertexUv2 === true ) {
  11315. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  11316. if ( vertexUvs !== undefined ) {
  11317. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11318. } else {
  11319. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  11320. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11321. }
  11322. }
  11323. // morphs
  11324. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11325. var morphTarget = morphTargets[ j ].vertices;
  11326. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11327. }
  11328. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  11329. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  11330. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  11331. }
  11332. // skins
  11333. if ( hasSkinIndices ) {
  11334. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11335. }
  11336. if ( hasSkinWeights ) {
  11337. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11338. }
  11339. }
  11340. this.computeGroups( geometry );
  11341. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11342. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11343. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11344. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11345. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11346. return this;
  11347. }
  11348. } );
  11349. /**
  11350. * @author mrdoob / http://mrdoob.com/
  11351. */
  11352. function arrayMax( array ) {
  11353. if ( array.length === 0 ) return - Infinity;
  11354. var max = array[ 0 ];
  11355. for ( var i = 1, l = array.length; i < l; ++ i ) {
  11356. if ( array[ i ] > max ) max = array[ i ];
  11357. }
  11358. return max;
  11359. }
  11360. /**
  11361. * @author alteredq / http://alteredqualia.com/
  11362. * @author mrdoob / http://mrdoob.com/
  11363. */
  11364. var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  11365. function BufferGeometry() {
  11366. Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } );
  11367. this.uuid = _Math.generateUUID();
  11368. this.name = '';
  11369. this.type = 'BufferGeometry';
  11370. this.index = null;
  11371. this.attributes = {};
  11372. this.morphAttributes = {};
  11373. this.groups = [];
  11374. this.boundingBox = null;
  11375. this.boundingSphere = null;
  11376. this.drawRange = { start: 0, count: Infinity };
  11377. this.userData = {};
  11378. }
  11379. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11380. constructor: BufferGeometry,
  11381. isBufferGeometry: true,
  11382. getIndex: function () {
  11383. return this.index;
  11384. },
  11385. setIndex: function ( index ) {
  11386. if ( Array.isArray( index ) ) {
  11387. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11388. } else {
  11389. this.index = index;
  11390. }
  11391. },
  11392. addAttribute: function ( name, attribute ) {
  11393. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  11394. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  11395. return this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  11396. }
  11397. if ( name === 'index' ) {
  11398. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  11399. this.setIndex( attribute );
  11400. return this;
  11401. }
  11402. this.attributes[ name ] = attribute;
  11403. return this;
  11404. },
  11405. getAttribute: function ( name ) {
  11406. return this.attributes[ name ];
  11407. },
  11408. removeAttribute: function ( name ) {
  11409. delete this.attributes[ name ];
  11410. return this;
  11411. },
  11412. addGroup: function ( start, count, materialIndex ) {
  11413. this.groups.push( {
  11414. start: start,
  11415. count: count,
  11416. materialIndex: materialIndex !== undefined ? materialIndex : 0
  11417. } );
  11418. },
  11419. clearGroups: function () {
  11420. this.groups = [];
  11421. },
  11422. setDrawRange: function ( start, count ) {
  11423. this.drawRange.start = start;
  11424. this.drawRange.count = count;
  11425. },
  11426. applyMatrix: function ( matrix ) {
  11427. var position = this.attributes.position;
  11428. if ( position !== undefined ) {
  11429. matrix.applyToBufferAttribute( position );
  11430. position.needsUpdate = true;
  11431. }
  11432. var normal = this.attributes.normal;
  11433. if ( normal !== undefined ) {
  11434. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11435. normalMatrix.applyToBufferAttribute( normal );
  11436. normal.needsUpdate = true;
  11437. }
  11438. var tangent = this.attributes.tangent;
  11439. if ( tangent !== undefined ) {
  11440. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11441. // Tangent is vec4, but the '.w' component is a sign value (+1/-1).
  11442. normalMatrix.applyToBufferAttribute( tangent );
  11443. tangent.needsUpdate = true;
  11444. }
  11445. if ( this.boundingBox !== null ) {
  11446. this.computeBoundingBox();
  11447. }
  11448. if ( this.boundingSphere !== null ) {
  11449. this.computeBoundingSphere();
  11450. }
  11451. return this;
  11452. },
  11453. rotateX: function () {
  11454. // rotate geometry around world x-axis
  11455. var m1 = new Matrix4();
  11456. return function rotateX( angle ) {
  11457. m1.makeRotationX( angle );
  11458. this.applyMatrix( m1 );
  11459. return this;
  11460. };
  11461. }(),
  11462. rotateY: function () {
  11463. // rotate geometry around world y-axis
  11464. var m1 = new Matrix4();
  11465. return function rotateY( angle ) {
  11466. m1.makeRotationY( angle );
  11467. this.applyMatrix( m1 );
  11468. return this;
  11469. };
  11470. }(),
  11471. rotateZ: function () {
  11472. // rotate geometry around world z-axis
  11473. var m1 = new Matrix4();
  11474. return function rotateZ( angle ) {
  11475. m1.makeRotationZ( angle );
  11476. this.applyMatrix( m1 );
  11477. return this;
  11478. };
  11479. }(),
  11480. translate: function () {
  11481. // translate geometry
  11482. var m1 = new Matrix4();
  11483. return function translate( x, y, z ) {
  11484. m1.makeTranslation( x, y, z );
  11485. this.applyMatrix( m1 );
  11486. return this;
  11487. };
  11488. }(),
  11489. scale: function () {
  11490. // scale geometry
  11491. var m1 = new Matrix4();
  11492. return function scale( x, y, z ) {
  11493. m1.makeScale( x, y, z );
  11494. this.applyMatrix( m1 );
  11495. return this;
  11496. };
  11497. }(),
  11498. lookAt: function () {
  11499. var obj = new Object3D();
  11500. return function lookAt( vector ) {
  11501. obj.lookAt( vector );
  11502. obj.updateMatrix();
  11503. this.applyMatrix( obj.matrix );
  11504. };
  11505. }(),
  11506. center: function () {
  11507. var offset = new Vector3();
  11508. return function center() {
  11509. this.computeBoundingBox();
  11510. this.boundingBox.getCenter( offset ).negate();
  11511. this.translate( offset.x, offset.y, offset.z );
  11512. return this;
  11513. };
  11514. }(),
  11515. setFromObject: function ( object ) {
  11516. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  11517. var geometry = object.geometry;
  11518. if ( object.isPoints || object.isLine ) {
  11519. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  11520. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  11521. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  11522. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  11523. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  11524. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  11525. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  11526. }
  11527. if ( geometry.boundingSphere !== null ) {
  11528. this.boundingSphere = geometry.boundingSphere.clone();
  11529. }
  11530. if ( geometry.boundingBox !== null ) {
  11531. this.boundingBox = geometry.boundingBox.clone();
  11532. }
  11533. } else if ( object.isMesh ) {
  11534. if ( geometry && geometry.isGeometry ) {
  11535. this.fromGeometry( geometry );
  11536. }
  11537. }
  11538. return this;
  11539. },
  11540. setFromPoints: function ( points ) {
  11541. var position = [];
  11542. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11543. var point = points[ i ];
  11544. position.push( point.x, point.y, point.z || 0 );
  11545. }
  11546. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11547. return this;
  11548. },
  11549. updateFromObject: function ( object ) {
  11550. var geometry = object.geometry;
  11551. if ( object.isMesh ) {
  11552. var direct = geometry.__directGeometry;
  11553. if ( geometry.elementsNeedUpdate === true ) {
  11554. direct = undefined;
  11555. geometry.elementsNeedUpdate = false;
  11556. }
  11557. if ( direct === undefined ) {
  11558. return this.fromGeometry( geometry );
  11559. }
  11560. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11561. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11562. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11563. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11564. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11565. geometry.verticesNeedUpdate = false;
  11566. geometry.normalsNeedUpdate = false;
  11567. geometry.colorsNeedUpdate = false;
  11568. geometry.uvsNeedUpdate = false;
  11569. geometry.groupsNeedUpdate = false;
  11570. geometry = direct;
  11571. }
  11572. var attribute;
  11573. if ( geometry.verticesNeedUpdate === true ) {
  11574. attribute = this.attributes.position;
  11575. if ( attribute !== undefined ) {
  11576. attribute.copyVector3sArray( geometry.vertices );
  11577. attribute.needsUpdate = true;
  11578. }
  11579. geometry.verticesNeedUpdate = false;
  11580. }
  11581. if ( geometry.normalsNeedUpdate === true ) {
  11582. attribute = this.attributes.normal;
  11583. if ( attribute !== undefined ) {
  11584. attribute.copyVector3sArray( geometry.normals );
  11585. attribute.needsUpdate = true;
  11586. }
  11587. geometry.normalsNeedUpdate = false;
  11588. }
  11589. if ( geometry.colorsNeedUpdate === true ) {
  11590. attribute = this.attributes.color;
  11591. if ( attribute !== undefined ) {
  11592. attribute.copyColorsArray( geometry.colors );
  11593. attribute.needsUpdate = true;
  11594. }
  11595. geometry.colorsNeedUpdate = false;
  11596. }
  11597. if ( geometry.uvsNeedUpdate ) {
  11598. attribute = this.attributes.uv;
  11599. if ( attribute !== undefined ) {
  11600. attribute.copyVector2sArray( geometry.uvs );
  11601. attribute.needsUpdate = true;
  11602. }
  11603. geometry.uvsNeedUpdate = false;
  11604. }
  11605. if ( geometry.lineDistancesNeedUpdate ) {
  11606. attribute = this.attributes.lineDistance;
  11607. if ( attribute !== undefined ) {
  11608. attribute.copyArray( geometry.lineDistances );
  11609. attribute.needsUpdate = true;
  11610. }
  11611. geometry.lineDistancesNeedUpdate = false;
  11612. }
  11613. if ( geometry.groupsNeedUpdate ) {
  11614. geometry.computeGroups( object.geometry );
  11615. this.groups = geometry.groups;
  11616. geometry.groupsNeedUpdate = false;
  11617. }
  11618. return this;
  11619. },
  11620. fromGeometry: function ( geometry ) {
  11621. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  11622. return this.fromDirectGeometry( geometry.__directGeometry );
  11623. },
  11624. fromDirectGeometry: function ( geometry ) {
  11625. var positions = new Float32Array( geometry.vertices.length * 3 );
  11626. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  11627. if ( geometry.normals.length > 0 ) {
  11628. var normals = new Float32Array( geometry.normals.length * 3 );
  11629. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  11630. }
  11631. if ( geometry.colors.length > 0 ) {
  11632. var colors = new Float32Array( geometry.colors.length * 3 );
  11633. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  11634. }
  11635. if ( geometry.uvs.length > 0 ) {
  11636. var uvs = new Float32Array( geometry.uvs.length * 2 );
  11637. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  11638. }
  11639. if ( geometry.uvs2.length > 0 ) {
  11640. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  11641. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  11642. }
  11643. // groups
  11644. this.groups = geometry.groups;
  11645. // morphs
  11646. for ( var name in geometry.morphTargets ) {
  11647. var array = [];
  11648. var morphTargets = geometry.morphTargets[ name ];
  11649. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  11650. var morphTarget = morphTargets[ i ];
  11651. var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  11652. attribute.name = morphTarget.name;
  11653. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  11654. }
  11655. this.morphAttributes[ name ] = array;
  11656. }
  11657. // skinning
  11658. if ( geometry.skinIndices.length > 0 ) {
  11659. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  11660. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  11661. }
  11662. if ( geometry.skinWeights.length > 0 ) {
  11663. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  11664. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  11665. }
  11666. //
  11667. if ( geometry.boundingSphere !== null ) {
  11668. this.boundingSphere = geometry.boundingSphere.clone();
  11669. }
  11670. if ( geometry.boundingBox !== null ) {
  11671. this.boundingBox = geometry.boundingBox.clone();
  11672. }
  11673. return this;
  11674. },
  11675. computeBoundingBox: function () {
  11676. var box = new Box3();
  11677. return function computeBoundingBox() {
  11678. if ( this.boundingBox === null ) {
  11679. this.boundingBox = new Box3();
  11680. }
  11681. var position = this.attributes.position;
  11682. var morphAttributesPosition = this.morphAttributes.position;
  11683. if ( position !== undefined ) {
  11684. this.boundingBox.setFromBufferAttribute( position );
  11685. // process morph attributes if present
  11686. if ( morphAttributesPosition ) {
  11687. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11688. var morphAttribute = morphAttributesPosition[ i ];
  11689. box.setFromBufferAttribute( morphAttribute );
  11690. this.boundingBox.expandByPoint( box.min );
  11691. this.boundingBox.expandByPoint( box.max );
  11692. }
  11693. }
  11694. } else {
  11695. this.boundingBox.makeEmpty();
  11696. }
  11697. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11698. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11699. }
  11700. };
  11701. }(),
  11702. computeBoundingSphere: function () {
  11703. var box = new Box3();
  11704. var boxMorphTargets = new Box3();
  11705. var vector = new Vector3();
  11706. return function computeBoundingSphere() {
  11707. if ( this.boundingSphere === null ) {
  11708. this.boundingSphere = new Sphere();
  11709. }
  11710. var position = this.attributes.position;
  11711. var morphAttributesPosition = this.morphAttributes.position;
  11712. if ( position ) {
  11713. // first, find the center of the bounding sphere
  11714. var center = this.boundingSphere.center;
  11715. box.setFromBufferAttribute( position );
  11716. // process morph attributes if present
  11717. if ( morphAttributesPosition ) {
  11718. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11719. var morphAttribute = morphAttributesPosition[ i ];
  11720. boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11721. box.expandByPoint( boxMorphTargets.min );
  11722. box.expandByPoint( boxMorphTargets.max );
  11723. }
  11724. }
  11725. box.getCenter( center );
  11726. // second, try to find a boundingSphere with a radius smaller than the
  11727. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11728. var maxRadiusSq = 0;
  11729. for ( var i = 0, il = position.count; i < il; i ++ ) {
  11730. vector.fromBufferAttribute( position, i );
  11731. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  11732. }
  11733. // process morph attributes if present
  11734. if ( morphAttributesPosition ) {
  11735. for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11736. var morphAttribute = morphAttributesPosition[ i ];
  11737. for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11738. vector.fromBufferAttribute( morphAttribute, i );
  11739. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  11740. }
  11741. }
  11742. }
  11743. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11744. if ( isNaN( this.boundingSphere.radius ) ) {
  11745. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11746. }
  11747. }
  11748. };
  11749. }(),
  11750. computeFaceNormals: function () {
  11751. // backwards compatibility
  11752. },
  11753. computeVertexNormals: function () {
  11754. var index = this.index;
  11755. var attributes = this.attributes;
  11756. if ( attributes.position ) {
  11757. var positions = attributes.position.array;
  11758. if ( attributes.normal === undefined ) {
  11759. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  11760. } else {
  11761. // reset existing normals to zero
  11762. var array = attributes.normal.array;
  11763. for ( var i = 0, il = array.length; i < il; i ++ ) {
  11764. array[ i ] = 0;
  11765. }
  11766. }
  11767. var normals = attributes.normal.array;
  11768. var vA, vB, vC;
  11769. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11770. var cb = new Vector3(), ab = new Vector3();
  11771. // indexed elements
  11772. if ( index ) {
  11773. var indices = index.array;
  11774. for ( var i = 0, il = index.count; i < il; i += 3 ) {
  11775. vA = indices[ i + 0 ] * 3;
  11776. vB = indices[ i + 1 ] * 3;
  11777. vC = indices[ i + 2 ] * 3;
  11778. pA.fromArray( positions, vA );
  11779. pB.fromArray( positions, vB );
  11780. pC.fromArray( positions, vC );
  11781. cb.subVectors( pC, pB );
  11782. ab.subVectors( pA, pB );
  11783. cb.cross( ab );
  11784. normals[ vA ] += cb.x;
  11785. normals[ vA + 1 ] += cb.y;
  11786. normals[ vA + 2 ] += cb.z;
  11787. normals[ vB ] += cb.x;
  11788. normals[ vB + 1 ] += cb.y;
  11789. normals[ vB + 2 ] += cb.z;
  11790. normals[ vC ] += cb.x;
  11791. normals[ vC + 1 ] += cb.y;
  11792. normals[ vC + 2 ] += cb.z;
  11793. }
  11794. } else {
  11795. // non-indexed elements (unconnected triangle soup)
  11796. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  11797. pA.fromArray( positions, i );
  11798. pB.fromArray( positions, i + 3 );
  11799. pC.fromArray( positions, i + 6 );
  11800. cb.subVectors( pC, pB );
  11801. ab.subVectors( pA, pB );
  11802. cb.cross( ab );
  11803. normals[ i ] = cb.x;
  11804. normals[ i + 1 ] = cb.y;
  11805. normals[ i + 2 ] = cb.z;
  11806. normals[ i + 3 ] = cb.x;
  11807. normals[ i + 4 ] = cb.y;
  11808. normals[ i + 5 ] = cb.z;
  11809. normals[ i + 6 ] = cb.x;
  11810. normals[ i + 7 ] = cb.y;
  11811. normals[ i + 8 ] = cb.z;
  11812. }
  11813. }
  11814. this.normalizeNormals();
  11815. attributes.normal.needsUpdate = true;
  11816. }
  11817. },
  11818. merge: function ( geometry, offset ) {
  11819. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  11820. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  11821. return;
  11822. }
  11823. if ( offset === undefined ) {
  11824. offset = 0;
  11825. console.warn(
  11826. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  11827. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  11828. );
  11829. }
  11830. var attributes = this.attributes;
  11831. for ( var key in attributes ) {
  11832. if ( geometry.attributes[ key ] === undefined ) continue;
  11833. var attribute1 = attributes[ key ];
  11834. var attributeArray1 = attribute1.array;
  11835. var attribute2 = geometry.attributes[ key ];
  11836. var attributeArray2 = attribute2.array;
  11837. var attributeSize = attribute2.itemSize;
  11838. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  11839. attributeArray1[ j ] = attributeArray2[ i ];
  11840. }
  11841. }
  11842. return this;
  11843. },
  11844. normalizeNormals: function () {
  11845. var vector = new Vector3();
  11846. return function normalizeNormals() {
  11847. var normals = this.attributes.normal;
  11848. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  11849. vector.x = normals.getX( i );
  11850. vector.y = normals.getY( i );
  11851. vector.z = normals.getZ( i );
  11852. vector.normalize();
  11853. normals.setXYZ( i, vector.x, vector.y, vector.z );
  11854. }
  11855. };
  11856. }(),
  11857. toNonIndexed: function () {
  11858. function convertBufferAttribute( attribute, indices ) {
  11859. var array = attribute.array;
  11860. var itemSize = attribute.itemSize;
  11861. var array2 = new array.constructor( indices.length * itemSize );
  11862. var index = 0, index2 = 0;
  11863. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11864. index = indices[ i ] * itemSize;
  11865. for ( var j = 0; j < itemSize; j ++ ) {
  11866. array2[ index2 ++ ] = array[ index ++ ];
  11867. }
  11868. }
  11869. return new BufferAttribute( array2, itemSize );
  11870. }
  11871. //
  11872. if ( this.index === null ) {
  11873. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  11874. return this;
  11875. }
  11876. var geometry2 = new BufferGeometry();
  11877. var indices = this.index.array;
  11878. var attributes = this.attributes;
  11879. // attributes
  11880. for ( var name in attributes ) {
  11881. var attribute = attributes[ name ];
  11882. var newAttribute = convertBufferAttribute( attribute, indices );
  11883. geometry2.addAttribute( name, newAttribute );
  11884. }
  11885. // morph attributes
  11886. var morphAttributes = this.morphAttributes;
  11887. for ( name in morphAttributes ) {
  11888. var morphArray = [];
  11889. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11890. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11891. var attribute = morphAttribute[ i ];
  11892. var newAttribute = convertBufferAttribute( attribute, indices );
  11893. morphArray.push( newAttribute );
  11894. }
  11895. geometry2.morphAttributes[ name ] = morphArray;
  11896. }
  11897. // groups
  11898. var groups = this.groups;
  11899. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  11900. var group = groups[ i ];
  11901. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11902. }
  11903. return geometry2;
  11904. },
  11905. toJSON: function () {
  11906. var data = {
  11907. metadata: {
  11908. version: 4.5,
  11909. type: 'BufferGeometry',
  11910. generator: 'BufferGeometry.toJSON'
  11911. }
  11912. };
  11913. // standard BufferGeometry serialization
  11914. data.uuid = this.uuid;
  11915. data.type = this.type;
  11916. if ( this.name !== '' ) data.name = this.name;
  11917. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11918. if ( this.parameters !== undefined ) {
  11919. var parameters = this.parameters;
  11920. for ( var key in parameters ) {
  11921. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11922. }
  11923. return data;
  11924. }
  11925. data.data = { attributes: {} };
  11926. var index = this.index;
  11927. if ( index !== null ) {
  11928. data.data.index = {
  11929. type: index.array.constructor.name,
  11930. array: Array.prototype.slice.call( index.array )
  11931. };
  11932. }
  11933. var attributes = this.attributes;
  11934. for ( var key in attributes ) {
  11935. var attribute = attributes[ key ];
  11936. var attributeData = {
  11937. itemSize: attribute.itemSize,
  11938. type: attribute.array.constructor.name,
  11939. array: Array.prototype.slice.call( attribute.array ),
  11940. normalized: attribute.normalized
  11941. };
  11942. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  11943. data.data.attributes[ key ] = attributeData;
  11944. }
  11945. var morphAttributes = {};
  11946. var hasMorphAttributes = false;
  11947. for ( var key in this.morphAttributes ) {
  11948. var attributeArray = this.morphAttributes[ key ];
  11949. var array = [];
  11950. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  11951. var attribute = attributeArray[ i ];
  11952. var attributeData = {
  11953. itemSize: attribute.itemSize,
  11954. type: attribute.array.constructor.name,
  11955. array: Array.prototype.slice.call( attribute.array ),
  11956. normalized: attribute.normalized
  11957. };
  11958. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  11959. array.push( attributeData );
  11960. }
  11961. if ( array.length > 0 ) {
  11962. morphAttributes[ key ] = array;
  11963. hasMorphAttributes = true;
  11964. }
  11965. }
  11966. if ( hasMorphAttributes ) data.data.morphAttributes = morphAttributes;
  11967. var groups = this.groups;
  11968. if ( groups.length > 0 ) {
  11969. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11970. }
  11971. var boundingSphere = this.boundingSphere;
  11972. if ( boundingSphere !== null ) {
  11973. data.data.boundingSphere = {
  11974. center: boundingSphere.center.toArray(),
  11975. radius: boundingSphere.radius
  11976. };
  11977. }
  11978. return data;
  11979. },
  11980. clone: function () {
  11981. /*
  11982. // Handle primitives
  11983. var parameters = this.parameters;
  11984. if ( parameters !== undefined ) {
  11985. var values = [];
  11986. for ( var key in parameters ) {
  11987. values.push( parameters[ key ] );
  11988. }
  11989. var geometry = Object.create( this.constructor.prototype );
  11990. this.constructor.apply( geometry, values );
  11991. return geometry;
  11992. }
  11993. return new this.constructor().copy( this );
  11994. */
  11995. return new BufferGeometry().copy( this );
  11996. },
  11997. copy: function ( source ) {
  11998. var name, i, l;
  11999. // reset
  12000. this.index = null;
  12001. this.attributes = {};
  12002. this.morphAttributes = {};
  12003. this.groups = [];
  12004. this.boundingBox = null;
  12005. this.boundingSphere = null;
  12006. // name
  12007. this.name = source.name;
  12008. // index
  12009. var index = source.index;
  12010. if ( index !== null ) {
  12011. this.setIndex( index.clone() );
  12012. }
  12013. // attributes
  12014. var attributes = source.attributes;
  12015. for ( name in attributes ) {
  12016. var attribute = attributes[ name ];
  12017. this.addAttribute( name, attribute.clone() );
  12018. }
  12019. // morph attributes
  12020. var morphAttributes = source.morphAttributes;
  12021. for ( name in morphAttributes ) {
  12022. var array = [];
  12023. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  12024. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  12025. array.push( morphAttribute[ i ].clone() );
  12026. }
  12027. this.morphAttributes[ name ] = array;
  12028. }
  12029. // groups
  12030. var groups = source.groups;
  12031. for ( i = 0, l = groups.length; i < l; i ++ ) {
  12032. var group = groups[ i ];
  12033. this.addGroup( group.start, group.count, group.materialIndex );
  12034. }
  12035. // bounding box
  12036. var boundingBox = source.boundingBox;
  12037. if ( boundingBox !== null ) {
  12038. this.boundingBox = boundingBox.clone();
  12039. }
  12040. // bounding sphere
  12041. var boundingSphere = source.boundingSphere;
  12042. if ( boundingSphere !== null ) {
  12043. this.boundingSphere = boundingSphere.clone();
  12044. }
  12045. // draw range
  12046. this.drawRange.start = source.drawRange.start;
  12047. this.drawRange.count = source.drawRange.count;
  12048. // user data
  12049. this.userData = source.userData;
  12050. return this;
  12051. },
  12052. dispose: function () {
  12053. this.dispatchEvent( { type: 'dispose' } );
  12054. }
  12055. } );
  12056. /**
  12057. * @author mrdoob / http://mrdoob.com/
  12058. * @author Mugen87 / https://github.com/Mugen87
  12059. */
  12060. // BoxGeometry
  12061. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  12062. Geometry.call( this );
  12063. this.type = 'BoxGeometry';
  12064. this.parameters = {
  12065. width: width,
  12066. height: height,
  12067. depth: depth,
  12068. widthSegments: widthSegments,
  12069. heightSegments: heightSegments,
  12070. depthSegments: depthSegments
  12071. };
  12072. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  12073. this.mergeVertices();
  12074. }
  12075. BoxGeometry.prototype = Object.create( Geometry.prototype );
  12076. BoxGeometry.prototype.constructor = BoxGeometry;
  12077. // BoxBufferGeometry
  12078. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  12079. BufferGeometry.call( this );
  12080. this.type = 'BoxBufferGeometry';
  12081. this.parameters = {
  12082. width: width,
  12083. height: height,
  12084. depth: depth,
  12085. widthSegments: widthSegments,
  12086. heightSegments: heightSegments,
  12087. depthSegments: depthSegments
  12088. };
  12089. var scope = this;
  12090. width = width || 1;
  12091. height = height || 1;
  12092. depth = depth || 1;
  12093. // segments
  12094. widthSegments = Math.floor( widthSegments ) || 1;
  12095. heightSegments = Math.floor( heightSegments ) || 1;
  12096. depthSegments = Math.floor( depthSegments ) || 1;
  12097. // buffers
  12098. var indices = [];
  12099. var vertices = [];
  12100. var normals = [];
  12101. var uvs = [];
  12102. // helper variables
  12103. var numberOfVertices = 0;
  12104. var groupStart = 0;
  12105. // build each side of the box geometry
  12106. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  12107. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  12108. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  12109. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  12110. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  12111. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  12112. // build geometry
  12113. this.setIndex( indices );
  12114. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12115. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12116. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12117. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  12118. var segmentWidth = width / gridX;
  12119. var segmentHeight = height / gridY;
  12120. var widthHalf = width / 2;
  12121. var heightHalf = height / 2;
  12122. var depthHalf = depth / 2;
  12123. var gridX1 = gridX + 1;
  12124. var gridY1 = gridY + 1;
  12125. var vertexCounter = 0;
  12126. var groupCount = 0;
  12127. var ix, iy;
  12128. var vector = new Vector3();
  12129. // generate vertices, normals and uvs
  12130. for ( iy = 0; iy < gridY1; iy ++ ) {
  12131. var y = iy * segmentHeight - heightHalf;
  12132. for ( ix = 0; ix < gridX1; ix ++ ) {
  12133. var x = ix * segmentWidth - widthHalf;
  12134. // set values to correct vector component
  12135. vector[ u ] = x * udir;
  12136. vector[ v ] = y * vdir;
  12137. vector[ w ] = depthHalf;
  12138. // now apply vector to vertex buffer
  12139. vertices.push( vector.x, vector.y, vector.z );
  12140. // set values to correct vector component
  12141. vector[ u ] = 0;
  12142. vector[ v ] = 0;
  12143. vector[ w ] = depth > 0 ? 1 : - 1;
  12144. // now apply vector to normal buffer
  12145. normals.push( vector.x, vector.y, vector.z );
  12146. // uvs
  12147. uvs.push( ix / gridX );
  12148. uvs.push( 1 - ( iy / gridY ) );
  12149. // counters
  12150. vertexCounter += 1;
  12151. }
  12152. }
  12153. // indices
  12154. // 1. you need three indices to draw a single face
  12155. // 2. a single segment consists of two faces
  12156. // 3. so we need to generate six (2*3) indices per segment
  12157. for ( iy = 0; iy < gridY; iy ++ ) {
  12158. for ( ix = 0; ix < gridX; ix ++ ) {
  12159. var a = numberOfVertices + ix + gridX1 * iy;
  12160. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  12161. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  12162. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  12163. // faces
  12164. indices.push( a, b, d );
  12165. indices.push( b, c, d );
  12166. // increase counter
  12167. groupCount += 6;
  12168. }
  12169. }
  12170. // add a group to the geometry. this will ensure multi material support
  12171. scope.addGroup( groupStart, groupCount, materialIndex );
  12172. // calculate new start value for groups
  12173. groupStart += groupCount;
  12174. // update total number of vertices
  12175. numberOfVertices += vertexCounter;
  12176. }
  12177. }
  12178. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  12179. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  12180. /**
  12181. * @author mrdoob / http://mrdoob.com/
  12182. * @author Mugen87 / https://github.com/Mugen87
  12183. */
  12184. // PlaneGeometry
  12185. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  12186. Geometry.call( this );
  12187. this.type = 'PlaneGeometry';
  12188. this.parameters = {
  12189. width: width,
  12190. height: height,
  12191. widthSegments: widthSegments,
  12192. heightSegments: heightSegments
  12193. };
  12194. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  12195. this.mergeVertices();
  12196. }
  12197. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  12198. PlaneGeometry.prototype.constructor = PlaneGeometry;
  12199. // PlaneBufferGeometry
  12200. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  12201. BufferGeometry.call( this );
  12202. this.type = 'PlaneBufferGeometry';
  12203. this.parameters = {
  12204. width: width,
  12205. height: height,
  12206. widthSegments: widthSegments,
  12207. heightSegments: heightSegments
  12208. };
  12209. width = width || 1;
  12210. height = height || 1;
  12211. var width_half = width / 2;
  12212. var height_half = height / 2;
  12213. var gridX = Math.floor( widthSegments ) || 1;
  12214. var gridY = Math.floor( heightSegments ) || 1;
  12215. var gridX1 = gridX + 1;
  12216. var gridY1 = gridY + 1;
  12217. var segment_width = width / gridX;
  12218. var segment_height = height / gridY;
  12219. var ix, iy;
  12220. // buffers
  12221. var indices = [];
  12222. var vertices = [];
  12223. var normals = [];
  12224. var uvs = [];
  12225. // generate vertices, normals and uvs
  12226. for ( iy = 0; iy < gridY1; iy ++ ) {
  12227. var y = iy * segment_height - height_half;
  12228. for ( ix = 0; ix < gridX1; ix ++ ) {
  12229. var x = ix * segment_width - width_half;
  12230. vertices.push( x, - y, 0 );
  12231. normals.push( 0, 0, 1 );
  12232. uvs.push( ix / gridX );
  12233. uvs.push( 1 - ( iy / gridY ) );
  12234. }
  12235. }
  12236. // indices
  12237. for ( iy = 0; iy < gridY; iy ++ ) {
  12238. for ( ix = 0; ix < gridX; ix ++ ) {
  12239. var a = ix + gridX1 * iy;
  12240. var b = ix + gridX1 * ( iy + 1 );
  12241. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  12242. var d = ( ix + 1 ) + gridX1 * iy;
  12243. // faces
  12244. indices.push( a, b, d );
  12245. indices.push( b, c, d );
  12246. }
  12247. }
  12248. // build geometry
  12249. this.setIndex( indices );
  12250. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12251. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12252. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12253. }
  12254. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  12255. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  12256. /**
  12257. * @author mrdoob / http://mrdoob.com/
  12258. * @author alteredq / http://alteredqualia.com/
  12259. */
  12260. var materialId = 0;
  12261. function Material() {
  12262. Object.defineProperty( this, 'id', { value: materialId ++ } );
  12263. this.uuid = _Math.generateUUID();
  12264. this.name = '';
  12265. this.type = 'Material';
  12266. this.fog = true;
  12267. this.lights = true;
  12268. this.blending = NormalBlending;
  12269. this.side = FrontSide;
  12270. this.flatShading = false;
  12271. this.vertexTangents = false;
  12272. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  12273. this.opacity = 1;
  12274. this.transparent = false;
  12275. this.blendSrc = SrcAlphaFactor;
  12276. this.blendDst = OneMinusSrcAlphaFactor;
  12277. this.blendEquation = AddEquation;
  12278. this.blendSrcAlpha = null;
  12279. this.blendDstAlpha = null;
  12280. this.blendEquationAlpha = null;
  12281. this.depthFunc = LessEqualDepth;
  12282. this.depthTest = true;
  12283. this.depthWrite = true;
  12284. this.clippingPlanes = null;
  12285. this.clipIntersection = false;
  12286. this.clipShadows = false;
  12287. this.shadowSide = null;
  12288. this.colorWrite = true;
  12289. this.precision = null; // override the renderer's default precision for this material
  12290. this.polygonOffset = false;
  12291. this.polygonOffsetFactor = 0;
  12292. this.polygonOffsetUnits = 0;
  12293. this.dithering = false;
  12294. this.alphaTest = 0;
  12295. this.premultipliedAlpha = false;
  12296. this.visible = true;
  12297. this.userData = {};
  12298. this.needsUpdate = true;
  12299. }
  12300. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  12301. constructor: Material,
  12302. isMaterial: true,
  12303. onBeforeCompile: function () {},
  12304. setValues: function ( values ) {
  12305. if ( values === undefined ) return;
  12306. for ( var key in values ) {
  12307. var newValue = values[ key ];
  12308. if ( newValue === undefined ) {
  12309. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  12310. continue;
  12311. }
  12312. // for backward compatability if shading is set in the constructor
  12313. if ( key === 'shading' ) {
  12314. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  12315. this.flatShading = ( newValue === FlatShading ) ? true : false;
  12316. continue;
  12317. }
  12318. var currentValue = this[ key ];
  12319. if ( currentValue === undefined ) {
  12320. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  12321. continue;
  12322. }
  12323. if ( currentValue && currentValue.isColor ) {
  12324. currentValue.set( newValue );
  12325. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12326. currentValue.copy( newValue );
  12327. } else {
  12328. this[ key ] = newValue;
  12329. }
  12330. }
  12331. },
  12332. toJSON: function ( meta ) {
  12333. var isRoot = ( meta === undefined || typeof meta === 'string' );
  12334. if ( isRoot ) {
  12335. meta = {
  12336. textures: {},
  12337. images: {}
  12338. };
  12339. }
  12340. var data = {
  12341. metadata: {
  12342. version: 4.5,
  12343. type: 'Material',
  12344. generator: 'Material.toJSON'
  12345. }
  12346. };
  12347. // standard Material serialization
  12348. data.uuid = this.uuid;
  12349. data.type = this.type;
  12350. if ( this.name !== '' ) data.name = this.name;
  12351. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12352. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12353. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12354. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12355. if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12356. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12357. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12358. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  12359. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  12360. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12361. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12362. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12363. if ( this.aoMap && this.aoMap.isTexture ) {
  12364. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12365. data.aoMapIntensity = this.aoMapIntensity;
  12366. }
  12367. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12368. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12369. data.bumpScale = this.bumpScale;
  12370. }
  12371. if ( this.normalMap && this.normalMap.isTexture ) {
  12372. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12373. data.normalMapType = this.normalMapType;
  12374. data.normalScale = this.normalScale.toArray();
  12375. }
  12376. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12377. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12378. data.displacementScale = this.displacementScale;
  12379. data.displacementBias = this.displacementBias;
  12380. }
  12381. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12382. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12383. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12384. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12385. if ( this.envMap && this.envMap.isTexture ) {
  12386. data.envMap = this.envMap.toJSON( meta ).uuid;
  12387. data.reflectivity = this.reflectivity; // Scale behind envMap
  12388. if ( this.combine !== undefined ) data.combine = this.combine;
  12389. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12390. }
  12391. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12392. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12393. }
  12394. if ( this.size !== undefined ) data.size = this.size;
  12395. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12396. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12397. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  12398. if ( this.side !== FrontSide ) data.side = this.side;
  12399. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  12400. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12401. if ( this.transparent === true ) data.transparent = this.transparent;
  12402. data.depthFunc = this.depthFunc;
  12403. data.depthTest = this.depthTest;
  12404. data.depthWrite = this.depthWrite;
  12405. // rotation (SpriteMaterial)
  12406. if ( this.rotation !== 0 ) data.rotation = this.rotation;
  12407. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12408. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12409. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12410. if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12411. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12412. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12413. if ( this.scale !== undefined ) data.scale = this.scale;
  12414. if ( this.dithering === true ) data.dithering = true;
  12415. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12416. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  12417. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  12418. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12419. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12420. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12421. if ( this.morphTargets === true ) data.morphTargets = true;
  12422. if ( this.skinning === true ) data.skinning = true;
  12423. if ( this.visible === false ) data.visible = false;
  12424. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  12425. // TODO: Copied from Object3D.toJSON
  12426. function extractFromCache( cache ) {
  12427. var values = [];
  12428. for ( var key in cache ) {
  12429. var data = cache[ key ];
  12430. delete data.metadata;
  12431. values.push( data );
  12432. }
  12433. return values;
  12434. }
  12435. if ( isRoot ) {
  12436. var textures = extractFromCache( meta.textures );
  12437. var images = extractFromCache( meta.images );
  12438. if ( textures.length > 0 ) data.textures = textures;
  12439. if ( images.length > 0 ) data.images = images;
  12440. }
  12441. return data;
  12442. },
  12443. clone: function () {
  12444. return new this.constructor().copy( this );
  12445. },
  12446. copy: function ( source ) {
  12447. this.name = source.name;
  12448. this.fog = source.fog;
  12449. this.lights = source.lights;
  12450. this.blending = source.blending;
  12451. this.side = source.side;
  12452. this.flatShading = source.flatShading;
  12453. this.vertexColors = source.vertexColors;
  12454. this.opacity = source.opacity;
  12455. this.transparent = source.transparent;
  12456. this.blendSrc = source.blendSrc;
  12457. this.blendDst = source.blendDst;
  12458. this.blendEquation = source.blendEquation;
  12459. this.blendSrcAlpha = source.blendSrcAlpha;
  12460. this.blendDstAlpha = source.blendDstAlpha;
  12461. this.blendEquationAlpha = source.blendEquationAlpha;
  12462. this.depthFunc = source.depthFunc;
  12463. this.depthTest = source.depthTest;
  12464. this.depthWrite = source.depthWrite;
  12465. this.colorWrite = source.colorWrite;
  12466. this.precision = source.precision;
  12467. this.polygonOffset = source.polygonOffset;
  12468. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12469. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12470. this.dithering = source.dithering;
  12471. this.alphaTest = source.alphaTest;
  12472. this.premultipliedAlpha = source.premultipliedAlpha;
  12473. this.visible = source.visible;
  12474. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12475. this.clipShadows = source.clipShadows;
  12476. this.clipIntersection = source.clipIntersection;
  12477. var srcPlanes = source.clippingPlanes,
  12478. dstPlanes = null;
  12479. if ( srcPlanes !== null ) {
  12480. var n = srcPlanes.length;
  12481. dstPlanes = new Array( n );
  12482. for ( var i = 0; i !== n; ++ i )
  12483. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12484. }
  12485. this.clippingPlanes = dstPlanes;
  12486. this.shadowSide = source.shadowSide;
  12487. return this;
  12488. },
  12489. dispose: function () {
  12490. this.dispatchEvent( { type: 'dispose' } );
  12491. }
  12492. } );
  12493. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12494. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12495. /**
  12496. * @author alteredq / http://alteredqualia.com/
  12497. *
  12498. * parameters = {
  12499. * defines: { "label" : "value" },
  12500. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  12501. *
  12502. * fragmentShader: <string>,
  12503. * vertexShader: <string>,
  12504. *
  12505. * wireframe: <boolean>,
  12506. * wireframeLinewidth: <float>,
  12507. *
  12508. * lights: <bool>,
  12509. *
  12510. * skinning: <bool>,
  12511. * morphTargets: <bool>,
  12512. * morphNormals: <bool>
  12513. * }
  12514. */
  12515. function ShaderMaterial( parameters ) {
  12516. Material.call( this );
  12517. this.type = 'ShaderMaterial';
  12518. this.defines = {};
  12519. this.uniforms = {};
  12520. this.vertexShader = default_vertex;
  12521. this.fragmentShader = default_fragment;
  12522. this.linewidth = 1;
  12523. this.wireframe = false;
  12524. this.wireframeLinewidth = 1;
  12525. this.fog = false; // set to use scene fog
  12526. this.lights = false; // set to use scene lights
  12527. this.clipping = false; // set to use user-defined clipping planes
  12528. this.skinning = false; // set to use skinning attribute streams
  12529. this.morphTargets = false; // set to use morph targets
  12530. this.morphNormals = false; // set to use morph normals
  12531. this.extensions = {
  12532. derivatives: false, // set to use derivatives
  12533. fragDepth: false, // set to use fragment depth values
  12534. drawBuffers: false, // set to use draw buffers
  12535. shaderTextureLOD: false // set to use shader texture LOD
  12536. };
  12537. // When rendered geometry doesn't include these attributes but the material does,
  12538. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12539. this.defaultAttributeValues = {
  12540. 'color': [ 1, 1, 1 ],
  12541. 'uv': [ 0, 0 ],
  12542. 'uv2': [ 0, 0 ]
  12543. };
  12544. this.index0AttributeName = undefined;
  12545. this.uniformsNeedUpdate = false;
  12546. if ( parameters !== undefined ) {
  12547. if ( parameters.attributes !== undefined ) {
  12548. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12549. }
  12550. this.setValues( parameters );
  12551. }
  12552. }
  12553. ShaderMaterial.prototype = Object.create( Material.prototype );
  12554. ShaderMaterial.prototype.constructor = ShaderMaterial;
  12555. ShaderMaterial.prototype.isShaderMaterial = true;
  12556. ShaderMaterial.prototype.copy = function ( source ) {
  12557. Material.prototype.copy.call( this, source );
  12558. this.fragmentShader = source.fragmentShader;
  12559. this.vertexShader = source.vertexShader;
  12560. this.uniforms = cloneUniforms( source.uniforms );
  12561. this.defines = Object.assign( {}, source.defines );
  12562. this.wireframe = source.wireframe;
  12563. this.wireframeLinewidth = source.wireframeLinewidth;
  12564. this.lights = source.lights;
  12565. this.clipping = source.clipping;
  12566. this.skinning = source.skinning;
  12567. this.morphTargets = source.morphTargets;
  12568. this.morphNormals = source.morphNormals;
  12569. this.extensions = source.extensions;
  12570. return this;
  12571. };
  12572. ShaderMaterial.prototype.toJSON = function ( meta ) {
  12573. var data = Material.prototype.toJSON.call( this, meta );
  12574. data.uniforms = {};
  12575. for ( var name in this.uniforms ) {
  12576. var uniform = this.uniforms[ name ];
  12577. var value = uniform.value;
  12578. if ( value && value.isTexture ) {
  12579. data.uniforms[ name ] = {
  12580. type: 't',
  12581. value: value.toJSON( meta ).uuid
  12582. };
  12583. } else if ( value && value.isColor ) {
  12584. data.uniforms[ name ] = {
  12585. type: 'c',
  12586. value: value.getHex()
  12587. };
  12588. } else if ( value && value.isVector2 ) {
  12589. data.uniforms[ name ] = {
  12590. type: 'v2',
  12591. value: value.toArray()
  12592. };
  12593. } else if ( value && value.isVector3 ) {
  12594. data.uniforms[ name ] = {
  12595. type: 'v3',
  12596. value: value.toArray()
  12597. };
  12598. } else if ( value && value.isVector4 ) {
  12599. data.uniforms[ name ] = {
  12600. type: 'v4',
  12601. value: value.toArray()
  12602. };
  12603. } else if ( value && value.isMatrix3 ) {
  12604. data.uniforms[ name ] = {
  12605. type: 'm3',
  12606. value: value.toArray()
  12607. };
  12608. } else if ( value && value.isMatrix4 ) {
  12609. data.uniforms[ name ] = {
  12610. type: 'm4',
  12611. value: value.toArray()
  12612. };
  12613. } else {
  12614. data.uniforms[ name ] = {
  12615. value: value
  12616. };
  12617. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12618. }
  12619. }
  12620. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  12621. data.vertexShader = this.vertexShader;
  12622. data.fragmentShader = this.fragmentShader;
  12623. var extensions = {};
  12624. for ( var key in this.extensions ) {
  12625. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  12626. }
  12627. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  12628. return data;
  12629. };
  12630. /**
  12631. * @author bhouston / http://clara.io
  12632. */
  12633. function Ray( origin, direction ) {
  12634. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  12635. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  12636. }
  12637. Object.assign( Ray.prototype, {
  12638. set: function ( origin, direction ) {
  12639. this.origin.copy( origin );
  12640. this.direction.copy( direction );
  12641. return this;
  12642. },
  12643. clone: function () {
  12644. return new this.constructor().copy( this );
  12645. },
  12646. copy: function ( ray ) {
  12647. this.origin.copy( ray.origin );
  12648. this.direction.copy( ray.direction );
  12649. return this;
  12650. },
  12651. at: function ( t, target ) {
  12652. if ( target === undefined ) {
  12653. console.warn( 'THREE.Ray: .at() target is now required' );
  12654. target = new Vector3();
  12655. }
  12656. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  12657. },
  12658. lookAt: function ( v ) {
  12659. this.direction.copy( v ).sub( this.origin ).normalize();
  12660. return this;
  12661. },
  12662. recast: function () {
  12663. var v1 = new Vector3();
  12664. return function recast( t ) {
  12665. this.origin.copy( this.at( t, v1 ) );
  12666. return this;
  12667. };
  12668. }(),
  12669. closestPointToPoint: function ( point, target ) {
  12670. if ( target === undefined ) {
  12671. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  12672. target = new Vector3();
  12673. }
  12674. target.subVectors( point, this.origin );
  12675. var directionDistance = target.dot( this.direction );
  12676. if ( directionDistance < 0 ) {
  12677. return target.copy( this.origin );
  12678. }
  12679. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  12680. },
  12681. distanceToPoint: function ( point ) {
  12682. return Math.sqrt( this.distanceSqToPoint( point ) );
  12683. },
  12684. distanceSqToPoint: function () {
  12685. var v1 = new Vector3();
  12686. return function distanceSqToPoint( point ) {
  12687. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  12688. // point behind the ray
  12689. if ( directionDistance < 0 ) {
  12690. return this.origin.distanceToSquared( point );
  12691. }
  12692. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  12693. return v1.distanceToSquared( point );
  12694. };
  12695. }(),
  12696. distanceSqToSegment: function () {
  12697. var segCenter = new Vector3();
  12698. var segDir = new Vector3();
  12699. var diff = new Vector3();
  12700. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  12701. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  12702. // It returns the min distance between the ray and the segment
  12703. // defined by v0 and v1
  12704. // It can also set two optional targets :
  12705. // - The closest point on the ray
  12706. // - The closest point on the segment
  12707. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  12708. segDir.copy( v1 ).sub( v0 ).normalize();
  12709. diff.copy( this.origin ).sub( segCenter );
  12710. var segExtent = v0.distanceTo( v1 ) * 0.5;
  12711. var a01 = - this.direction.dot( segDir );
  12712. var b0 = diff.dot( this.direction );
  12713. var b1 = - diff.dot( segDir );
  12714. var c = diff.lengthSq();
  12715. var det = Math.abs( 1 - a01 * a01 );
  12716. var s0, s1, sqrDist, extDet;
  12717. if ( det > 0 ) {
  12718. // The ray and segment are not parallel.
  12719. s0 = a01 * b1 - b0;
  12720. s1 = a01 * b0 - b1;
  12721. extDet = segExtent * det;
  12722. if ( s0 >= 0 ) {
  12723. if ( s1 >= - extDet ) {
  12724. if ( s1 <= extDet ) {
  12725. // region 0
  12726. // Minimum at interior points of ray and segment.
  12727. var invDet = 1 / det;
  12728. s0 *= invDet;
  12729. s1 *= invDet;
  12730. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  12731. } else {
  12732. // region 1
  12733. s1 = segExtent;
  12734. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12735. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12736. }
  12737. } else {
  12738. // region 5
  12739. s1 = - segExtent;
  12740. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12741. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12742. }
  12743. } else {
  12744. if ( s1 <= - extDet ) {
  12745. // region 4
  12746. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  12747. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12748. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12749. } else if ( s1 <= extDet ) {
  12750. // region 3
  12751. s0 = 0;
  12752. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12753. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  12754. } else {
  12755. // region 2
  12756. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  12757. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  12758. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12759. }
  12760. }
  12761. } else {
  12762. // Ray and segment are parallel.
  12763. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  12764. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  12765. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  12766. }
  12767. if ( optionalPointOnRay ) {
  12768. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  12769. }
  12770. if ( optionalPointOnSegment ) {
  12771. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  12772. }
  12773. return sqrDist;
  12774. };
  12775. }(),
  12776. intersectSphere: function () {
  12777. var v1 = new Vector3();
  12778. return function intersectSphere( sphere, target ) {
  12779. v1.subVectors( sphere.center, this.origin );
  12780. var tca = v1.dot( this.direction );
  12781. var d2 = v1.dot( v1 ) - tca * tca;
  12782. var radius2 = sphere.radius * sphere.radius;
  12783. if ( d2 > radius2 ) return null;
  12784. var thc = Math.sqrt( radius2 - d2 );
  12785. // t0 = first intersect point - entrance on front of sphere
  12786. var t0 = tca - thc;
  12787. // t1 = second intersect point - exit point on back of sphere
  12788. var t1 = tca + thc;
  12789. // test to see if both t0 and t1 are behind the ray - if so, return null
  12790. if ( t0 < 0 && t1 < 0 ) return null;
  12791. // test to see if t0 is behind the ray:
  12792. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  12793. // in order to always return an intersect point that is in front of the ray.
  12794. if ( t0 < 0 ) return this.at( t1, target );
  12795. // else t0 is in front of the ray, so return the first collision point scaled by t0
  12796. return this.at( t0, target );
  12797. };
  12798. }(),
  12799. intersectsSphere: function ( sphere ) {
  12800. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  12801. },
  12802. distanceToPlane: function ( plane ) {
  12803. var denominator = plane.normal.dot( this.direction );
  12804. if ( denominator === 0 ) {
  12805. // line is coplanar, return origin
  12806. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  12807. return 0;
  12808. }
  12809. // Null is preferable to undefined since undefined means.... it is undefined
  12810. return null;
  12811. }
  12812. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  12813. // Return if the ray never intersects the plane
  12814. return t >= 0 ? t : null;
  12815. },
  12816. intersectPlane: function ( plane, target ) {
  12817. var t = this.distanceToPlane( plane );
  12818. if ( t === null ) {
  12819. return null;
  12820. }
  12821. return this.at( t, target );
  12822. },
  12823. intersectsPlane: function ( plane ) {
  12824. // check if the ray lies on the plane first
  12825. var distToPoint = plane.distanceToPoint( this.origin );
  12826. if ( distToPoint === 0 ) {
  12827. return true;
  12828. }
  12829. var denominator = plane.normal.dot( this.direction );
  12830. if ( denominator * distToPoint < 0 ) {
  12831. return true;
  12832. }
  12833. // ray origin is behind the plane (and is pointing behind it)
  12834. return false;
  12835. },
  12836. intersectBox: function ( box, target ) {
  12837. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  12838. var invdirx = 1 / this.direction.x,
  12839. invdiry = 1 / this.direction.y,
  12840. invdirz = 1 / this.direction.z;
  12841. var origin = this.origin;
  12842. if ( invdirx >= 0 ) {
  12843. tmin = ( box.min.x - origin.x ) * invdirx;
  12844. tmax = ( box.max.x - origin.x ) * invdirx;
  12845. } else {
  12846. tmin = ( box.max.x - origin.x ) * invdirx;
  12847. tmax = ( box.min.x - origin.x ) * invdirx;
  12848. }
  12849. if ( invdiry >= 0 ) {
  12850. tymin = ( box.min.y - origin.y ) * invdiry;
  12851. tymax = ( box.max.y - origin.y ) * invdiry;
  12852. } else {
  12853. tymin = ( box.max.y - origin.y ) * invdiry;
  12854. tymax = ( box.min.y - origin.y ) * invdiry;
  12855. }
  12856. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  12857. // These lines also handle the case where tmin or tmax is NaN
  12858. // (result of 0 * Infinity). x !== x returns true if x is NaN
  12859. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  12860. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  12861. if ( invdirz >= 0 ) {
  12862. tzmin = ( box.min.z - origin.z ) * invdirz;
  12863. tzmax = ( box.max.z - origin.z ) * invdirz;
  12864. } else {
  12865. tzmin = ( box.max.z - origin.z ) * invdirz;
  12866. tzmax = ( box.min.z - origin.z ) * invdirz;
  12867. }
  12868. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  12869. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  12870. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  12871. //return point closest to the ray (positive side)
  12872. if ( tmax < 0 ) return null;
  12873. return this.at( tmin >= 0 ? tmin : tmax, target );
  12874. },
  12875. intersectsBox: ( function () {
  12876. var v = new Vector3();
  12877. return function intersectsBox( box ) {
  12878. return this.intersectBox( box, v ) !== null;
  12879. };
  12880. } )(),
  12881. intersectTriangle: function () {
  12882. // Compute the offset origin, edges, and normal.
  12883. var diff = new Vector3();
  12884. var edge1 = new Vector3();
  12885. var edge2 = new Vector3();
  12886. var normal = new Vector3();
  12887. return function intersectTriangle( a, b, c, backfaceCulling, target ) {
  12888. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  12889. edge1.subVectors( b, a );
  12890. edge2.subVectors( c, a );
  12891. normal.crossVectors( edge1, edge2 );
  12892. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  12893. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  12894. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  12895. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  12896. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  12897. var DdN = this.direction.dot( normal );
  12898. var sign;
  12899. if ( DdN > 0 ) {
  12900. if ( backfaceCulling ) return null;
  12901. sign = 1;
  12902. } else if ( DdN < 0 ) {
  12903. sign = - 1;
  12904. DdN = - DdN;
  12905. } else {
  12906. return null;
  12907. }
  12908. diff.subVectors( this.origin, a );
  12909. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  12910. // b1 < 0, no intersection
  12911. if ( DdQxE2 < 0 ) {
  12912. return null;
  12913. }
  12914. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  12915. // b2 < 0, no intersection
  12916. if ( DdE1xQ < 0 ) {
  12917. return null;
  12918. }
  12919. // b1+b2 > 1, no intersection
  12920. if ( DdQxE2 + DdE1xQ > DdN ) {
  12921. return null;
  12922. }
  12923. // Line intersects triangle, check if ray does.
  12924. var QdN = - sign * diff.dot( normal );
  12925. // t < 0, no intersection
  12926. if ( QdN < 0 ) {
  12927. return null;
  12928. }
  12929. // Ray intersects triangle.
  12930. return this.at( QdN / DdN, target );
  12931. };
  12932. }(),
  12933. applyMatrix4: function ( matrix4 ) {
  12934. this.origin.applyMatrix4( matrix4 );
  12935. this.direction.transformDirection( matrix4 );
  12936. return this;
  12937. },
  12938. equals: function ( ray ) {
  12939. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  12940. }
  12941. } );
  12942. /**
  12943. * @author bhouston / http://clara.io
  12944. * @author mrdoob / http://mrdoob.com/
  12945. */
  12946. function Triangle( a, b, c ) {
  12947. this.a = ( a !== undefined ) ? a : new Vector3();
  12948. this.b = ( b !== undefined ) ? b : new Vector3();
  12949. this.c = ( c !== undefined ) ? c : new Vector3();
  12950. }
  12951. Object.assign( Triangle, {
  12952. getNormal: function () {
  12953. var v0 = new Vector3();
  12954. return function getNormal( a, b, c, target ) {
  12955. if ( target === undefined ) {
  12956. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  12957. target = new Vector3();
  12958. }
  12959. target.subVectors( c, b );
  12960. v0.subVectors( a, b );
  12961. target.cross( v0 );
  12962. var targetLengthSq = target.lengthSq();
  12963. if ( targetLengthSq > 0 ) {
  12964. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  12965. }
  12966. return target.set( 0, 0, 0 );
  12967. };
  12968. }(),
  12969. // static/instance method to calculate barycentric coordinates
  12970. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  12971. getBarycoord: function () {
  12972. var v0 = new Vector3();
  12973. var v1 = new Vector3();
  12974. var v2 = new Vector3();
  12975. return function getBarycoord( point, a, b, c, target ) {
  12976. v0.subVectors( c, a );
  12977. v1.subVectors( b, a );
  12978. v2.subVectors( point, a );
  12979. var dot00 = v0.dot( v0 );
  12980. var dot01 = v0.dot( v1 );
  12981. var dot02 = v0.dot( v2 );
  12982. var dot11 = v1.dot( v1 );
  12983. var dot12 = v1.dot( v2 );
  12984. var denom = ( dot00 * dot11 - dot01 * dot01 );
  12985. if ( target === undefined ) {
  12986. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  12987. target = new Vector3();
  12988. }
  12989. // collinear or singular triangle
  12990. if ( denom === 0 ) {
  12991. // arbitrary location outside of triangle?
  12992. // not sure if this is the best idea, maybe should be returning undefined
  12993. return target.set( - 2, - 1, - 1 );
  12994. }
  12995. var invDenom = 1 / denom;
  12996. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  12997. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  12998. // barycentric coordinates must always sum to 1
  12999. return target.set( 1 - u - v, v, u );
  13000. };
  13001. }(),
  13002. containsPoint: function () {
  13003. var v1 = new Vector3();
  13004. return function containsPoint( point, a, b, c ) {
  13005. Triangle.getBarycoord( point, a, b, c, v1 );
  13006. return ( v1.x >= 0 ) && ( v1.y >= 0 ) && ( ( v1.x + v1.y ) <= 1 );
  13007. };
  13008. }(),
  13009. getUV: function () {
  13010. var barycoord = new Vector3();
  13011. return function getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  13012. this.getBarycoord( point, p1, p2, p3, barycoord );
  13013. target.set( 0, 0 );
  13014. target.addScaledVector( uv1, barycoord.x );
  13015. target.addScaledVector( uv2, barycoord.y );
  13016. target.addScaledVector( uv3, barycoord.z );
  13017. return target;
  13018. };
  13019. }()
  13020. } );
  13021. Object.assign( Triangle.prototype, {
  13022. set: function ( a, b, c ) {
  13023. this.a.copy( a );
  13024. this.b.copy( b );
  13025. this.c.copy( c );
  13026. return this;
  13027. },
  13028. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  13029. this.a.copy( points[ i0 ] );
  13030. this.b.copy( points[ i1 ] );
  13031. this.c.copy( points[ i2 ] );
  13032. return this;
  13033. },
  13034. clone: function () {
  13035. return new this.constructor().copy( this );
  13036. },
  13037. copy: function ( triangle ) {
  13038. this.a.copy( triangle.a );
  13039. this.b.copy( triangle.b );
  13040. this.c.copy( triangle.c );
  13041. return this;
  13042. },
  13043. getArea: function () {
  13044. var v0 = new Vector3();
  13045. var v1 = new Vector3();
  13046. return function getArea() {
  13047. v0.subVectors( this.c, this.b );
  13048. v1.subVectors( this.a, this.b );
  13049. return v0.cross( v1 ).length() * 0.5;
  13050. };
  13051. }(),
  13052. getMidpoint: function ( target ) {
  13053. if ( target === undefined ) {
  13054. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  13055. target = new Vector3();
  13056. }
  13057. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  13058. },
  13059. getNormal: function ( target ) {
  13060. return Triangle.getNormal( this.a, this.b, this.c, target );
  13061. },
  13062. getPlane: function ( target ) {
  13063. if ( target === undefined ) {
  13064. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  13065. target = new Vector3();
  13066. }
  13067. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  13068. },
  13069. getBarycoord: function ( point, target ) {
  13070. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  13071. },
  13072. containsPoint: function ( point ) {
  13073. return Triangle.containsPoint( point, this.a, this.b, this.c );
  13074. },
  13075. getUV: function ( point, uv1, uv2, uv3, result ) {
  13076. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, result );
  13077. },
  13078. intersectsBox: function ( box ) {
  13079. return box.intersectsTriangle( this );
  13080. },
  13081. closestPointToPoint: function () {
  13082. var vab = new Vector3();
  13083. var vac = new Vector3();
  13084. var vbc = new Vector3();
  13085. var vap = new Vector3();
  13086. var vbp = new Vector3();
  13087. var vcp = new Vector3();
  13088. return function closestPointToPoint( p, target ) {
  13089. if ( target === undefined ) {
  13090. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  13091. target = new Vector3();
  13092. }
  13093. var a = this.a, b = this.b, c = this.c;
  13094. var v, w;
  13095. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  13096. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  13097. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  13098. // basically, we're distinguishing which of the voronoi regions of the triangle
  13099. // the point lies in with the minimum amount of redundant computation.
  13100. vab.subVectors( b, a );
  13101. vac.subVectors( c, a );
  13102. vap.subVectors( p, a );
  13103. var d1 = vab.dot( vap );
  13104. var d2 = vac.dot( vap );
  13105. if ( d1 <= 0 && d2 <= 0 ) {
  13106. // vertex region of A; barycentric coords (1, 0, 0)
  13107. return target.copy( a );
  13108. }
  13109. vbp.subVectors( p, b );
  13110. var d3 = vab.dot( vbp );
  13111. var d4 = vac.dot( vbp );
  13112. if ( d3 >= 0 && d4 <= d3 ) {
  13113. // vertex region of B; barycentric coords (0, 1, 0)
  13114. return target.copy( b );
  13115. }
  13116. var vc = d1 * d4 - d3 * d2;
  13117. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  13118. v = d1 / ( d1 - d3 );
  13119. // edge region of AB; barycentric coords (1-v, v, 0)
  13120. return target.copy( a ).addScaledVector( vab, v );
  13121. }
  13122. vcp.subVectors( p, c );
  13123. var d5 = vab.dot( vcp );
  13124. var d6 = vac.dot( vcp );
  13125. if ( d6 >= 0 && d5 <= d6 ) {
  13126. // vertex region of C; barycentric coords (0, 0, 1)
  13127. return target.copy( c );
  13128. }
  13129. var vb = d5 * d2 - d1 * d6;
  13130. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  13131. w = d2 / ( d2 - d6 );
  13132. // edge region of AC; barycentric coords (1-w, 0, w)
  13133. return target.copy( a ).addScaledVector( vac, w );
  13134. }
  13135. var va = d3 * d6 - d5 * d4;
  13136. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  13137. vbc.subVectors( c, b );
  13138. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  13139. // edge region of BC; barycentric coords (0, 1-w, w)
  13140. return target.copy( b ).addScaledVector( vbc, w ); // edge region of BC
  13141. }
  13142. // face region
  13143. var denom = 1 / ( va + vb + vc );
  13144. // u = va * denom
  13145. v = vb * denom;
  13146. w = vc * denom;
  13147. return target.copy( a ).addScaledVector( vab, v ).addScaledVector( vac, w );
  13148. };
  13149. }(),
  13150. equals: function ( triangle ) {
  13151. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  13152. }
  13153. } );
  13154. /**
  13155. * @author mrdoob / http://mrdoob.com/
  13156. * @author alteredq / http://alteredqualia.com/
  13157. *
  13158. * parameters = {
  13159. * color: <hex>,
  13160. * opacity: <float>,
  13161. * map: new THREE.Texture( <Image> ),
  13162. *
  13163. * lightMap: new THREE.Texture( <Image> ),
  13164. * lightMapIntensity: <float>
  13165. *
  13166. * aoMap: new THREE.Texture( <Image> ),
  13167. * aoMapIntensity: <float>
  13168. *
  13169. * specularMap: new THREE.Texture( <Image> ),
  13170. *
  13171. * alphaMap: new THREE.Texture( <Image> ),
  13172. *
  13173. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  13174. * combine: THREE.Multiply,
  13175. * reflectivity: <float>,
  13176. * refractionRatio: <float>,
  13177. *
  13178. * depthTest: <bool>,
  13179. * depthWrite: <bool>,
  13180. *
  13181. * wireframe: <boolean>,
  13182. * wireframeLinewidth: <float>,
  13183. *
  13184. * skinning: <bool>,
  13185. * morphTargets: <bool>
  13186. * }
  13187. */
  13188. function MeshBasicMaterial( parameters ) {
  13189. Material.call( this );
  13190. this.type = 'MeshBasicMaterial';
  13191. this.color = new Color( 0xffffff ); // emissive
  13192. this.map = null;
  13193. this.lightMap = null;
  13194. this.lightMapIntensity = 1.0;
  13195. this.aoMap = null;
  13196. this.aoMapIntensity = 1.0;
  13197. this.specularMap = null;
  13198. this.alphaMap = null;
  13199. this.envMap = null;
  13200. this.combine = MultiplyOperation;
  13201. this.reflectivity = 1;
  13202. this.refractionRatio = 0.98;
  13203. this.wireframe = false;
  13204. this.wireframeLinewidth = 1;
  13205. this.wireframeLinecap = 'round';
  13206. this.wireframeLinejoin = 'round';
  13207. this.skinning = false;
  13208. this.morphTargets = false;
  13209. this.lights = false;
  13210. this.setValues( parameters );
  13211. }
  13212. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  13213. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  13214. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  13215. MeshBasicMaterial.prototype.copy = function ( source ) {
  13216. Material.prototype.copy.call( this, source );
  13217. this.color.copy( source.color );
  13218. this.map = source.map;
  13219. this.lightMap = source.lightMap;
  13220. this.lightMapIntensity = source.lightMapIntensity;
  13221. this.aoMap = source.aoMap;
  13222. this.aoMapIntensity = source.aoMapIntensity;
  13223. this.specularMap = source.specularMap;
  13224. this.alphaMap = source.alphaMap;
  13225. this.envMap = source.envMap;
  13226. this.combine = source.combine;
  13227. this.reflectivity = source.reflectivity;
  13228. this.refractionRatio = source.refractionRatio;
  13229. this.wireframe = source.wireframe;
  13230. this.wireframeLinewidth = source.wireframeLinewidth;
  13231. this.wireframeLinecap = source.wireframeLinecap;
  13232. this.wireframeLinejoin = source.wireframeLinejoin;
  13233. this.skinning = source.skinning;
  13234. this.morphTargets = source.morphTargets;
  13235. return this;
  13236. };
  13237. /**
  13238. * @author mrdoob / http://mrdoob.com/
  13239. * @author alteredq / http://alteredqualia.com/
  13240. * @author mikael emtinger / http://gomo.se/
  13241. * @author jonobr1 / http://jonobr1.com/
  13242. */
  13243. function Mesh( geometry, material ) {
  13244. Object3D.call( this );
  13245. this.type = 'Mesh';
  13246. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13247. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13248. this.drawMode = TrianglesDrawMode;
  13249. this.updateMorphTargets();
  13250. }
  13251. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13252. constructor: Mesh,
  13253. isMesh: true,
  13254. setDrawMode: function ( value ) {
  13255. this.drawMode = value;
  13256. },
  13257. copy: function ( source ) {
  13258. Object3D.prototype.copy.call( this, source );
  13259. this.drawMode = source.drawMode;
  13260. if ( source.morphTargetInfluences !== undefined ) {
  13261. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  13262. }
  13263. if ( source.morphTargetDictionary !== undefined ) {
  13264. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  13265. }
  13266. return this;
  13267. },
  13268. updateMorphTargets: function () {
  13269. var geometry = this.geometry;
  13270. var m, ml, name;
  13271. if ( geometry.isBufferGeometry ) {
  13272. var morphAttributes = geometry.morphAttributes;
  13273. var keys = Object.keys( morphAttributes );
  13274. if ( keys.length > 0 ) {
  13275. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  13276. if ( morphAttribute !== undefined ) {
  13277. this.morphTargetInfluences = [];
  13278. this.morphTargetDictionary = {};
  13279. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  13280. name = morphAttribute[ m ].name || String( m );
  13281. this.morphTargetInfluences.push( 0 );
  13282. this.morphTargetDictionary[ name ] = m;
  13283. }
  13284. }
  13285. }
  13286. } else {
  13287. var morphTargets = geometry.morphTargets;
  13288. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  13289. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  13290. }
  13291. }
  13292. },
  13293. raycast: ( function () {
  13294. var inverseMatrix = new Matrix4();
  13295. var ray = new Ray();
  13296. var sphere = new Sphere();
  13297. var vA = new Vector3();
  13298. var vB = new Vector3();
  13299. var vC = new Vector3();
  13300. var tempA = new Vector3();
  13301. var tempB = new Vector3();
  13302. var tempC = new Vector3();
  13303. var morphA = new Vector3();
  13304. var morphB = new Vector3();
  13305. var morphC = new Vector3();
  13306. var uvA = new Vector2();
  13307. var uvB = new Vector2();
  13308. var uvC = new Vector2();
  13309. var intersectionPoint = new Vector3();
  13310. var intersectionPointWorld = new Vector3();
  13311. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  13312. var intersect;
  13313. if ( material.side === BackSide ) {
  13314. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13315. } else {
  13316. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  13317. }
  13318. if ( intersect === null ) return null;
  13319. intersectionPointWorld.copy( point );
  13320. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13321. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13322. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13323. return {
  13324. distance: distance,
  13325. point: intersectionPointWorld.clone(),
  13326. object: object
  13327. };
  13328. }
  13329. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, uv, a, b, c ) {
  13330. vA.fromBufferAttribute( position, a );
  13331. vB.fromBufferAttribute( position, b );
  13332. vC.fromBufferAttribute( position, c );
  13333. var morphInfluences = object.morphTargetInfluences;
  13334. if ( material.morphTargets && morphPosition && morphInfluences ) {
  13335. morphA.set( 0, 0, 0 );
  13336. morphB.set( 0, 0, 0 );
  13337. morphC.set( 0, 0, 0 );
  13338. for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {
  13339. var influence = morphInfluences[ i ];
  13340. var morphAttribute = morphPosition[ i ];
  13341. if ( influence === 0 ) continue;
  13342. tempA.fromBufferAttribute( morphAttribute, a );
  13343. tempB.fromBufferAttribute( morphAttribute, b );
  13344. tempC.fromBufferAttribute( morphAttribute, c );
  13345. morphA.addScaledVector( tempA.sub( vA ), influence );
  13346. morphB.addScaledVector( tempB.sub( vB ), influence );
  13347. morphC.addScaledVector( tempC.sub( vC ), influence );
  13348. }
  13349. vA.add( morphA );
  13350. vB.add( morphB );
  13351. vC.add( morphC );
  13352. }
  13353. var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );
  13354. if ( intersection ) {
  13355. if ( uv ) {
  13356. uvA.fromBufferAttribute( uv, a );
  13357. uvB.fromBufferAttribute( uv, b );
  13358. uvC.fromBufferAttribute( uv, c );
  13359. intersection.uv = Triangle.getUV( intersectionPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() );
  13360. }
  13361. var face = new Face3( a, b, c );
  13362. Triangle.getNormal( vA, vB, vC, face.normal );
  13363. intersection.face = face;
  13364. }
  13365. return intersection;
  13366. }
  13367. return function raycast( raycaster, intersects ) {
  13368. var geometry = this.geometry;
  13369. var material = this.material;
  13370. var matrixWorld = this.matrixWorld;
  13371. if ( material === undefined ) return;
  13372. // Checking boundingSphere distance to ray
  13373. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13374. sphere.copy( geometry.boundingSphere );
  13375. sphere.applyMatrix4( matrixWorld );
  13376. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13377. //
  13378. inverseMatrix.getInverse( matrixWorld );
  13379. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13380. // Check boundingBox before continuing
  13381. if ( geometry.boundingBox !== null ) {
  13382. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13383. }
  13384. var intersection;
  13385. if ( geometry.isBufferGeometry ) {
  13386. var a, b, c;
  13387. var index = geometry.index;
  13388. var position = geometry.attributes.position;
  13389. var morphPosition = geometry.morphAttributes.position;
  13390. var uv = geometry.attributes.uv;
  13391. var groups = geometry.groups;
  13392. var drawRange = geometry.drawRange;
  13393. var i, j, il, jl;
  13394. var group, groupMaterial;
  13395. var start, end;
  13396. if ( index !== null ) {
  13397. // indexed buffer geometry
  13398. if ( Array.isArray( material ) ) {
  13399. for ( i = 0, il = groups.length; i < il; i ++ ) {
  13400. group = groups[ i ];
  13401. groupMaterial = material[ group.materialIndex ];
  13402. start = Math.max( group.start, drawRange.start );
  13403. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  13404. for ( j = start, jl = end; j < jl; j += 3 ) {
  13405. a = index.getX( j );
  13406. b = index.getX( j + 1 );
  13407. c = index.getX( j + 2 );
  13408. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, morphPosition, uv, a, b, c );
  13409. if ( intersection ) {
  13410. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  13411. intersection.face.materialIndex = group.materialIndex;
  13412. intersects.push( intersection );
  13413. }
  13414. }
  13415. }
  13416. } else {
  13417. start = Math.max( 0, drawRange.start );
  13418. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  13419. for ( i = start, il = end; i < il; i += 3 ) {
  13420. a = index.getX( i );
  13421. b = index.getX( i + 1 );
  13422. c = index.getX( i + 2 );
  13423. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, morphPosition, uv, a, b, c );
  13424. if ( intersection ) {
  13425. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  13426. intersects.push( intersection );
  13427. }
  13428. }
  13429. }
  13430. } else if ( position !== undefined ) {
  13431. // non-indexed buffer geometry
  13432. if ( Array.isArray( material ) ) {
  13433. for ( i = 0, il = groups.length; i < il; i ++ ) {
  13434. group = groups[ i ];
  13435. groupMaterial = material[ group.materialIndex ];
  13436. start = Math.max( group.start, drawRange.start );
  13437. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  13438. for ( j = start, jl = end; j < jl; j += 3 ) {
  13439. a = j;
  13440. b = j + 1;
  13441. c = j + 2;
  13442. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, morphPosition, uv, a, b, c );
  13443. if ( intersection ) {
  13444. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  13445. intersection.face.materialIndex = group.materialIndex;
  13446. intersects.push( intersection );
  13447. }
  13448. }
  13449. }
  13450. } else {
  13451. start = Math.max( 0, drawRange.start );
  13452. end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  13453. for ( i = start, il = end; i < il; i += 3 ) {
  13454. a = i;
  13455. b = i + 1;
  13456. c = i + 2;
  13457. intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, morphPosition, uv, a, b, c );
  13458. if ( intersection ) {
  13459. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  13460. intersects.push( intersection );
  13461. }
  13462. }
  13463. }
  13464. }
  13465. } else if ( geometry.isGeometry ) {
  13466. var fvA, fvB, fvC;
  13467. var isMultiMaterial = Array.isArray( material );
  13468. var vertices = geometry.vertices;
  13469. var faces = geometry.faces;
  13470. var uvs;
  13471. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13472. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13473. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13474. var face = faces[ f ];
  13475. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  13476. if ( faceMaterial === undefined ) continue;
  13477. fvA = vertices[ face.a ];
  13478. fvB = vertices[ face.b ];
  13479. fvC = vertices[ face.c ];
  13480. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13481. if ( intersection ) {
  13482. if ( uvs && uvs[ f ] ) {
  13483. var uvs_f = uvs[ f ];
  13484. uvA.copy( uvs_f[ 0 ] );
  13485. uvB.copy( uvs_f[ 1 ] );
  13486. uvC.copy( uvs_f[ 2 ] );
  13487. intersection.uv = Triangle.getUV( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC, new Vector2() );
  13488. }
  13489. intersection.face = face;
  13490. intersection.faceIndex = f;
  13491. intersects.push( intersection );
  13492. }
  13493. }
  13494. }
  13495. };
  13496. }() ),
  13497. clone: function () {
  13498. return new this.constructor( this.geometry, this.material ).copy( this );
  13499. }
  13500. } );
  13501. /**
  13502. * @author mrdoob / http://mrdoob.com/
  13503. */
  13504. function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {
  13505. var clearColor = new Color( 0x000000 );
  13506. var clearAlpha = 0;
  13507. var planeMesh;
  13508. var boxMesh;
  13509. // Store the current background texture and its `version`
  13510. // so we can recompile the material accordingly.
  13511. var currentBackground = null;
  13512. var currentBackgroundVersion = 0;
  13513. function render( renderList, scene, camera, forceClear ) {
  13514. var background = scene.background;
  13515. // Ignore background in AR
  13516. // TODO: Reconsider this.
  13517. var vr = renderer.vr;
  13518. var session = vr.getSession && vr.getSession();
  13519. if ( session && session.environmentBlendMode === 'additive' ) {
  13520. background = null;
  13521. }
  13522. if ( background === null ) {
  13523. setClear( clearColor, clearAlpha );
  13524. currentBackground = null;
  13525. currentBackgroundVersion = 0;
  13526. } else if ( background && background.isColor ) {
  13527. setClear( background, 1 );
  13528. forceClear = true;
  13529. currentBackground = null;
  13530. currentBackgroundVersion = 0;
  13531. }
  13532. if ( renderer.autoClear || forceClear ) {
  13533. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  13534. }
  13535. if ( background && ( background.isCubeTexture || background.isWebGLRenderTargetCube ) ) {
  13536. if ( boxMesh === undefined ) {
  13537. boxMesh = new Mesh(
  13538. new BoxBufferGeometry( 1, 1, 1 ),
  13539. new ShaderMaterial( {
  13540. type: 'BackgroundCubeMaterial',
  13541. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  13542. vertexShader: ShaderLib.cube.vertexShader,
  13543. fragmentShader: ShaderLib.cube.fragmentShader,
  13544. side: BackSide,
  13545. depthTest: false,
  13546. depthWrite: false,
  13547. fog: false
  13548. } )
  13549. );
  13550. boxMesh.geometry.removeAttribute( 'normal' );
  13551. boxMesh.geometry.removeAttribute( 'uv' );
  13552. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  13553. this.matrixWorld.copyPosition( camera.matrixWorld );
  13554. };
  13555. // enable code injection for non-built-in material
  13556. Object.defineProperty( boxMesh.material, 'map', {
  13557. get: function () {
  13558. return this.uniforms.tCube.value;
  13559. }
  13560. } );
  13561. objects.update( boxMesh );
  13562. }
  13563. var texture = background.isWebGLRenderTargetCube ? background.texture : background;
  13564. boxMesh.material.uniforms.tCube.value = texture;
  13565. boxMesh.material.uniforms.tFlip.value = ( background.isWebGLRenderTargetCube ) ? 1 : - 1;
  13566. if ( currentBackground !== background ||
  13567. currentBackgroundVersion !== texture.version ) {
  13568. boxMesh.material.needsUpdate = true;
  13569. currentBackground = background;
  13570. currentBackgroundVersion = texture.version;
  13571. }
  13572. // push to the pre-sorted opaque render list
  13573. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  13574. } else if ( background && background.isTexture ) {
  13575. if ( planeMesh === undefined ) {
  13576. planeMesh = new Mesh(
  13577. new PlaneBufferGeometry( 2, 2 ),
  13578. new ShaderMaterial( {
  13579. type: 'BackgroundMaterial',
  13580. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  13581. vertexShader: ShaderLib.background.vertexShader,
  13582. fragmentShader: ShaderLib.background.fragmentShader,
  13583. side: FrontSide,
  13584. depthTest: false,
  13585. depthWrite: false,
  13586. fog: false
  13587. } )
  13588. );
  13589. planeMesh.geometry.removeAttribute( 'normal' );
  13590. // enable code injection for non-built-in material
  13591. Object.defineProperty( planeMesh.material, 'map', {
  13592. get: function () {
  13593. return this.uniforms.t2D.value;
  13594. }
  13595. } );
  13596. objects.update( planeMesh );
  13597. }
  13598. planeMesh.material.uniforms.t2D.value = background;
  13599. if ( background.matrixAutoUpdate === true ) {
  13600. background.updateMatrix();
  13601. }
  13602. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  13603. if ( currentBackground !== background ||
  13604. currentBackgroundVersion !== background.version ) {
  13605. planeMesh.material.needsUpdate = true;
  13606. currentBackground = background;
  13607. currentBackgroundVersion = background.version;
  13608. }
  13609. // push to the pre-sorted opaque render list
  13610. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  13611. }
  13612. }
  13613. function setClear( color, alpha ) {
  13614. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  13615. }
  13616. return {
  13617. getClearColor: function () {
  13618. return clearColor;
  13619. },
  13620. setClearColor: function ( color, alpha ) {
  13621. clearColor.set( color );
  13622. clearAlpha = alpha !== undefined ? alpha : 1;
  13623. setClear( clearColor, clearAlpha );
  13624. },
  13625. getClearAlpha: function () {
  13626. return clearAlpha;
  13627. },
  13628. setClearAlpha: function ( alpha ) {
  13629. clearAlpha = alpha;
  13630. setClear( clearColor, clearAlpha );
  13631. },
  13632. render: render
  13633. };
  13634. }
  13635. /**
  13636. * @author mrdoob / http://mrdoob.com/
  13637. */
  13638. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  13639. var mode;
  13640. function setMode( value ) {
  13641. mode = value;
  13642. }
  13643. function render( start, count ) {
  13644. gl.drawArrays( mode, start, count );
  13645. info.update( count, mode );
  13646. }
  13647. function renderInstances( geometry, start, count ) {
  13648. var extension;
  13649. if ( capabilities.isWebGL2 ) {
  13650. extension = gl;
  13651. } else {
  13652. extension = extensions.get( 'ANGLE_instanced_arrays' );
  13653. if ( extension === null ) {
  13654. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13655. return;
  13656. }
  13657. }
  13658. extension[ capabilities.isWebGL2 ? 'drawArraysInstanced' : 'drawArraysInstancedANGLE' ]( mode, start, count, geometry.maxInstancedCount );
  13659. info.update( count, mode, geometry.maxInstancedCount );
  13660. }
  13661. //
  13662. this.setMode = setMode;
  13663. this.render = render;
  13664. this.renderInstances = renderInstances;
  13665. }
  13666. /**
  13667. * @author mrdoob / http://mrdoob.com/
  13668. */
  13669. function WebGLCapabilities( gl, extensions, parameters ) {
  13670. var maxAnisotropy;
  13671. function getMaxAnisotropy() {
  13672. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  13673. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13674. if ( extension !== null ) {
  13675. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  13676. } else {
  13677. maxAnisotropy = 0;
  13678. }
  13679. return maxAnisotropy;
  13680. }
  13681. function getMaxPrecision( precision ) {
  13682. if ( precision === 'highp' ) {
  13683. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  13684. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  13685. return 'highp';
  13686. }
  13687. precision = 'mediump';
  13688. }
  13689. if ( precision === 'mediump' ) {
  13690. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  13691. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  13692. return 'mediump';
  13693. }
  13694. }
  13695. return 'lowp';
  13696. }
  13697. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  13698. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  13699. var maxPrecision = getMaxPrecision( precision );
  13700. if ( maxPrecision !== precision ) {
  13701. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  13702. precision = maxPrecision;
  13703. }
  13704. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  13705. var maxTextures = gl.getParameter( 34930 );
  13706. var maxVertexTextures = gl.getParameter( 35660 );
  13707. var maxTextureSize = gl.getParameter( 3379 );
  13708. var maxCubemapSize = gl.getParameter( 34076 );
  13709. var maxAttributes = gl.getParameter( 34921 );
  13710. var maxVertexUniforms = gl.getParameter( 36347 );
  13711. var maxVaryings = gl.getParameter( 36348 );
  13712. var maxFragmentUniforms = gl.getParameter( 36349 );
  13713. var vertexTextures = maxVertexTextures > 0;
  13714. var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  13715. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  13716. var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  13717. return {
  13718. isWebGL2: isWebGL2,
  13719. getMaxAnisotropy: getMaxAnisotropy,
  13720. getMaxPrecision: getMaxPrecision,
  13721. precision: precision,
  13722. logarithmicDepthBuffer: logarithmicDepthBuffer,
  13723. maxTextures: maxTextures,
  13724. maxVertexTextures: maxVertexTextures,
  13725. maxTextureSize: maxTextureSize,
  13726. maxCubemapSize: maxCubemapSize,
  13727. maxAttributes: maxAttributes,
  13728. maxVertexUniforms: maxVertexUniforms,
  13729. maxVaryings: maxVaryings,
  13730. maxFragmentUniforms: maxFragmentUniforms,
  13731. vertexTextures: vertexTextures,
  13732. floatFragmentTextures: floatFragmentTextures,
  13733. floatVertexTextures: floatVertexTextures,
  13734. maxSamples: maxSamples
  13735. };
  13736. }
  13737. /**
  13738. * @author tschw
  13739. */
  13740. function WebGLClipping() {
  13741. var scope = this,
  13742. globalState = null,
  13743. numGlobalPlanes = 0,
  13744. localClippingEnabled = false,
  13745. renderingShadows = false,
  13746. plane = new Plane(),
  13747. viewNormalMatrix = new Matrix3(),
  13748. uniform = { value: null, needsUpdate: false };
  13749. this.uniform = uniform;
  13750. this.numPlanes = 0;
  13751. this.numIntersection = 0;
  13752. this.init = function ( planes, enableLocalClipping, camera ) {
  13753. var enabled =
  13754. planes.length !== 0 ||
  13755. enableLocalClipping ||
  13756. // enable state of previous frame - the clipping code has to
  13757. // run another frame in order to reset the state:
  13758. numGlobalPlanes !== 0 ||
  13759. localClippingEnabled;
  13760. localClippingEnabled = enableLocalClipping;
  13761. globalState = projectPlanes( planes, camera, 0 );
  13762. numGlobalPlanes = planes.length;
  13763. return enabled;
  13764. };
  13765. this.beginShadows = function () {
  13766. renderingShadows = true;
  13767. projectPlanes( null );
  13768. };
  13769. this.endShadows = function () {
  13770. renderingShadows = false;
  13771. resetGlobalState();
  13772. };
  13773. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  13774. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  13775. // there's no local clipping
  13776. if ( renderingShadows ) {
  13777. // there's no global clipping
  13778. projectPlanes( null );
  13779. } else {
  13780. resetGlobalState();
  13781. }
  13782. } else {
  13783. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  13784. lGlobal = nGlobal * 4,
  13785. dstArray = cache.clippingState || null;
  13786. uniform.value = dstArray; // ensure unique state
  13787. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  13788. for ( var i = 0; i !== lGlobal; ++ i ) {
  13789. dstArray[ i ] = globalState[ i ];
  13790. }
  13791. cache.clippingState = dstArray;
  13792. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  13793. this.numPlanes += nGlobal;
  13794. }
  13795. };
  13796. function resetGlobalState() {
  13797. if ( uniform.value !== globalState ) {
  13798. uniform.value = globalState;
  13799. uniform.needsUpdate = numGlobalPlanes > 0;
  13800. }
  13801. scope.numPlanes = numGlobalPlanes;
  13802. scope.numIntersection = 0;
  13803. }
  13804. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  13805. var nPlanes = planes !== null ? planes.length : 0,
  13806. dstArray = null;
  13807. if ( nPlanes !== 0 ) {
  13808. dstArray = uniform.value;
  13809. if ( skipTransform !== true || dstArray === null ) {
  13810. var flatSize = dstOffset + nPlanes * 4,
  13811. viewMatrix = camera.matrixWorldInverse;
  13812. viewNormalMatrix.getNormalMatrix( viewMatrix );
  13813. if ( dstArray === null || dstArray.length < flatSize ) {
  13814. dstArray = new Float32Array( flatSize );
  13815. }
  13816. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  13817. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  13818. plane.normal.toArray( dstArray, i4 );
  13819. dstArray[ i4 + 3 ] = plane.constant;
  13820. }
  13821. }
  13822. uniform.value = dstArray;
  13823. uniform.needsUpdate = true;
  13824. }
  13825. scope.numPlanes = nPlanes;
  13826. return dstArray;
  13827. }
  13828. }
  13829. /**
  13830. * @author mrdoob / http://mrdoob.com/
  13831. */
  13832. function WebGLExtensions( gl ) {
  13833. var extensions = {};
  13834. return {
  13835. get: function ( name ) {
  13836. if ( extensions[ name ] !== undefined ) {
  13837. return extensions[ name ];
  13838. }
  13839. var extension;
  13840. switch ( name ) {
  13841. case 'WEBGL_depth_texture':
  13842. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  13843. break;
  13844. case 'EXT_texture_filter_anisotropic':
  13845. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13846. break;
  13847. case 'WEBGL_compressed_texture_s3tc':
  13848. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13849. break;
  13850. case 'WEBGL_compressed_texture_pvrtc':
  13851. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  13852. break;
  13853. default:
  13854. extension = gl.getExtension( name );
  13855. }
  13856. if ( extension === null ) {
  13857. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  13858. }
  13859. extensions[ name ] = extension;
  13860. return extension;
  13861. }
  13862. };
  13863. }
  13864. /**
  13865. * @author mrdoob / http://mrdoob.com/
  13866. */
  13867. function WebGLGeometries( gl, attributes, info ) {
  13868. var geometries = {};
  13869. var wireframeAttributes = {};
  13870. function onGeometryDispose( event ) {
  13871. var geometry = event.target;
  13872. var buffergeometry = geometries[ geometry.id ];
  13873. if ( buffergeometry.index !== null ) {
  13874. attributes.remove( buffergeometry.index );
  13875. }
  13876. for ( var name in buffergeometry.attributes ) {
  13877. attributes.remove( buffergeometry.attributes[ name ] );
  13878. }
  13879. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13880. delete geometries[ geometry.id ];
  13881. var attribute = wireframeAttributes[ buffergeometry.id ];
  13882. if ( attribute ) {
  13883. attributes.remove( attribute );
  13884. delete wireframeAttributes[ buffergeometry.id ];
  13885. }
  13886. //
  13887. info.memory.geometries --;
  13888. }
  13889. function get( object, geometry ) {
  13890. var buffergeometry = geometries[ geometry.id ];
  13891. if ( buffergeometry ) return buffergeometry;
  13892. geometry.addEventListener( 'dispose', onGeometryDispose );
  13893. if ( geometry.isBufferGeometry ) {
  13894. buffergeometry = geometry;
  13895. } else if ( geometry.isGeometry ) {
  13896. if ( geometry._bufferGeometry === undefined ) {
  13897. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  13898. }
  13899. buffergeometry = geometry._bufferGeometry;
  13900. }
  13901. geometries[ geometry.id ] = buffergeometry;
  13902. info.memory.geometries ++;
  13903. return buffergeometry;
  13904. }
  13905. function update( geometry ) {
  13906. var index = geometry.index;
  13907. var geometryAttributes = geometry.attributes;
  13908. if ( index !== null ) {
  13909. attributes.update( index, 34963 );
  13910. }
  13911. for ( var name in geometryAttributes ) {
  13912. attributes.update( geometryAttributes[ name ], 34962 );
  13913. }
  13914. // morph targets
  13915. var morphAttributes = geometry.morphAttributes;
  13916. for ( var name in morphAttributes ) {
  13917. var array = morphAttributes[ name ];
  13918. for ( var i = 0, l = array.length; i < l; i ++ ) {
  13919. attributes.update( array[ i ], 34962 );
  13920. }
  13921. }
  13922. }
  13923. function getWireframeAttribute( geometry ) {
  13924. var attribute = wireframeAttributes[ geometry.id ];
  13925. if ( attribute ) return attribute;
  13926. var indices = [];
  13927. var geometryIndex = geometry.index;
  13928. var geometryAttributes = geometry.attributes;
  13929. // console.time( 'wireframe' );
  13930. if ( geometryIndex !== null ) {
  13931. var array = geometryIndex.array;
  13932. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  13933. var a = array[ i + 0 ];
  13934. var b = array[ i + 1 ];
  13935. var c = array[ i + 2 ];
  13936. indices.push( a, b, b, c, c, a );
  13937. }
  13938. } else {
  13939. var array = geometryAttributes.position.array;
  13940. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  13941. var a = i + 0;
  13942. var b = i + 1;
  13943. var c = i + 2;
  13944. indices.push( a, b, b, c, c, a );
  13945. }
  13946. }
  13947. // console.timeEnd( 'wireframe' );
  13948. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  13949. attributes.update( attribute, 34963 );
  13950. wireframeAttributes[ geometry.id ] = attribute;
  13951. return attribute;
  13952. }
  13953. return {
  13954. get: get,
  13955. update: update,
  13956. getWireframeAttribute: getWireframeAttribute
  13957. };
  13958. }
  13959. /**
  13960. * @author mrdoob / http://mrdoob.com/
  13961. */
  13962. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  13963. var mode;
  13964. function setMode( value ) {
  13965. mode = value;
  13966. }
  13967. var type, bytesPerElement;
  13968. function setIndex( value ) {
  13969. type = value.type;
  13970. bytesPerElement = value.bytesPerElement;
  13971. }
  13972. function render( start, count ) {
  13973. gl.drawElements( mode, count, type, start * bytesPerElement );
  13974. info.update( count, mode );
  13975. }
  13976. function renderInstances( geometry, start, count ) {
  13977. var extension;
  13978. if ( capabilities.isWebGL2 ) {
  13979. extension = gl;
  13980. } else {
  13981. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13982. if ( extension === null ) {
  13983. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13984. return;
  13985. }
  13986. }
  13987. extension[ capabilities.isWebGL2 ? 'drawElementsInstanced' : 'drawElementsInstancedANGLE' ]( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  13988. info.update( count, mode, geometry.maxInstancedCount );
  13989. }
  13990. //
  13991. this.setMode = setMode;
  13992. this.setIndex = setIndex;
  13993. this.render = render;
  13994. this.renderInstances = renderInstances;
  13995. }
  13996. /**
  13997. * @author Mugen87 / https://github.com/Mugen87
  13998. */
  13999. function WebGLInfo( gl ) {
  14000. var memory = {
  14001. geometries: 0,
  14002. textures: 0
  14003. };
  14004. var render = {
  14005. frame: 0,
  14006. calls: 0,
  14007. triangles: 0,
  14008. points: 0,
  14009. lines: 0
  14010. };
  14011. function update( count, mode, instanceCount ) {
  14012. instanceCount = instanceCount || 1;
  14013. render.calls ++;
  14014. switch ( mode ) {
  14015. case 4:
  14016. render.triangles += instanceCount * ( count / 3 );
  14017. break;
  14018. case 5:
  14019. case 6:
  14020. render.triangles += instanceCount * ( count - 2 );
  14021. break;
  14022. case 1:
  14023. render.lines += instanceCount * ( count / 2 );
  14024. break;
  14025. case 3:
  14026. render.lines += instanceCount * ( count - 1 );
  14027. break;
  14028. case 2:
  14029. render.lines += instanceCount * count;
  14030. break;
  14031. case 0:
  14032. render.points += instanceCount * count;
  14033. break;
  14034. default:
  14035. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  14036. break;
  14037. }
  14038. }
  14039. function reset() {
  14040. render.frame ++;
  14041. render.calls = 0;
  14042. render.triangles = 0;
  14043. render.points = 0;
  14044. render.lines = 0;
  14045. }
  14046. return {
  14047. memory: memory,
  14048. render: render,
  14049. programs: null,
  14050. autoReset: true,
  14051. reset: reset,
  14052. update: update
  14053. };
  14054. }
  14055. /**
  14056. * @author mrdoob / http://mrdoob.com/
  14057. */
  14058. function absNumericalSort( a, b ) {
  14059. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  14060. }
  14061. function WebGLMorphtargets( gl ) {
  14062. var influencesList = {};
  14063. var morphInfluences = new Float32Array( 8 );
  14064. function update( object, geometry, material, program ) {
  14065. var objectInfluences = object.morphTargetInfluences;
  14066. var length = objectInfluences.length;
  14067. var influences = influencesList[ geometry.id ];
  14068. if ( influences === undefined ) {
  14069. // initialise list
  14070. influences = [];
  14071. for ( var i = 0; i < length; i ++ ) {
  14072. influences[ i ] = [ i, 0 ];
  14073. }
  14074. influencesList[ geometry.id ] = influences;
  14075. }
  14076. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  14077. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  14078. // Remove current morphAttributes
  14079. for ( var i = 0; i < length; i ++ ) {
  14080. var influence = influences[ i ];
  14081. if ( influence[ 1 ] !== 0 ) {
  14082. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  14083. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  14084. }
  14085. }
  14086. // Collect influences
  14087. for ( var i = 0; i < length; i ++ ) {
  14088. var influence = influences[ i ];
  14089. influence[ 0 ] = i;
  14090. influence[ 1 ] = objectInfluences[ i ];
  14091. }
  14092. influences.sort( absNumericalSort );
  14093. // Add morphAttributes
  14094. for ( var i = 0; i < 8; i ++ ) {
  14095. var influence = influences[ i ];
  14096. if ( influence ) {
  14097. var index = influence[ 0 ];
  14098. var value = influence[ 1 ];
  14099. if ( value ) {
  14100. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  14101. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  14102. morphInfluences[ i ] = value;
  14103. continue;
  14104. }
  14105. }
  14106. morphInfluences[ i ] = 0;
  14107. }
  14108. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  14109. }
  14110. return {
  14111. update: update
  14112. };
  14113. }
  14114. /**
  14115. * @author mrdoob / http://mrdoob.com/
  14116. */
  14117. function WebGLObjects( geometries, info ) {
  14118. var updateList = {};
  14119. function update( object ) {
  14120. var frame = info.render.frame;
  14121. var geometry = object.geometry;
  14122. var buffergeometry = geometries.get( object, geometry );
  14123. // Update once per frame
  14124. if ( updateList[ buffergeometry.id ] !== frame ) {
  14125. if ( geometry.isGeometry ) {
  14126. buffergeometry.updateFromObject( object );
  14127. }
  14128. geometries.update( buffergeometry );
  14129. updateList[ buffergeometry.id ] = frame;
  14130. }
  14131. return buffergeometry;
  14132. }
  14133. function dispose() {
  14134. updateList = {};
  14135. }
  14136. return {
  14137. update: update,
  14138. dispose: dispose
  14139. };
  14140. }
  14141. /**
  14142. * @author mrdoob / http://mrdoob.com/
  14143. */
  14144. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  14145. images = images !== undefined ? images : [];
  14146. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  14147. format = format !== undefined ? format : RGBFormat;
  14148. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  14149. this.flipY = false;
  14150. }
  14151. CubeTexture.prototype = Object.create( Texture.prototype );
  14152. CubeTexture.prototype.constructor = CubeTexture;
  14153. CubeTexture.prototype.isCubeTexture = true;
  14154. Object.defineProperty( CubeTexture.prototype, 'images', {
  14155. get: function () {
  14156. return this.image;
  14157. },
  14158. set: function ( value ) {
  14159. this.image = value;
  14160. }
  14161. } );
  14162. /**
  14163. * @author Takahiro https://github.com/takahirox
  14164. */
  14165. function DataTexture2DArray( data, width, height, depth ) {
  14166. Texture.call( this, null );
  14167. this.image = { data: data, width: width, height: height, depth: depth };
  14168. this.magFilter = NearestFilter;
  14169. this.minFilter = NearestFilter;
  14170. this.wrapR = ClampToEdgeWrapping;
  14171. this.generateMipmaps = false;
  14172. this.flipY = false;
  14173. }
  14174. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  14175. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  14176. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  14177. /**
  14178. * @author Artur Trzesiok
  14179. */
  14180. function DataTexture3D( data, width, height, depth ) {
  14181. // We're going to add .setXXX() methods for setting properties later.
  14182. // Users can still set in DataTexture3D directly.
  14183. //
  14184. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  14185. // texture.anisotropy = 16;
  14186. //
  14187. // See #14839
  14188. Texture.call( this, null );
  14189. this.image = { data: data, width: width, height: height, depth: depth };
  14190. this.magFilter = NearestFilter;
  14191. this.minFilter = NearestFilter;
  14192. this.wrapR = ClampToEdgeWrapping;
  14193. this.generateMipmaps = false;
  14194. this.flipY = false;
  14195. }
  14196. DataTexture3D.prototype = Object.create( Texture.prototype );
  14197. DataTexture3D.prototype.constructor = DataTexture3D;
  14198. DataTexture3D.prototype.isDataTexture3D = true;
  14199. /**
  14200. * @author tschw
  14201. * @author Mugen87 / https://github.com/Mugen87
  14202. * @author mrdoob / http://mrdoob.com/
  14203. *
  14204. * Uniforms of a program.
  14205. * Those form a tree structure with a special top-level container for the root,
  14206. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  14207. *
  14208. *
  14209. * Properties of inner nodes including the top-level container:
  14210. *
  14211. * .seq - array of nested uniforms
  14212. * .map - nested uniforms by name
  14213. *
  14214. *
  14215. * Methods of all nodes except the top-level container:
  14216. *
  14217. * .setValue( gl, value, [renderer] )
  14218. *
  14219. * uploads a uniform value(s)
  14220. * the 'renderer' parameter is needed for sampler uniforms
  14221. *
  14222. *
  14223. * Static methods of the top-level container (renderer factorizations):
  14224. *
  14225. * .upload( gl, seq, values, renderer )
  14226. *
  14227. * sets uniforms in 'seq' to 'values[id].value'
  14228. *
  14229. * .seqWithValue( seq, values ) : filteredSeq
  14230. *
  14231. * filters 'seq' entries with corresponding entry in values
  14232. *
  14233. *
  14234. * Methods of the top-level container (renderer factorizations):
  14235. *
  14236. * .setValue( gl, name, value )
  14237. *
  14238. * sets uniform with name 'name' to 'value'
  14239. *
  14240. * .set( gl, obj, prop )
  14241. *
  14242. * sets uniform from object and property with same name than uniform
  14243. *
  14244. * .setOptional( gl, obj, prop )
  14245. *
  14246. * like .set for an optional property of the object
  14247. *
  14248. */
  14249. var emptyTexture = new Texture();
  14250. var emptyTexture2dArray = new DataTexture2DArray();
  14251. var emptyTexture3d = new DataTexture3D();
  14252. var emptyCubeTexture = new CubeTexture();
  14253. // --- Base for inner nodes (including the root) ---
  14254. function UniformContainer() {
  14255. this.seq = [];
  14256. this.map = {};
  14257. }
  14258. // --- Utilities ---
  14259. // Array Caches (provide typed arrays for temporary by size)
  14260. var arrayCacheF32 = [];
  14261. var arrayCacheI32 = [];
  14262. // Float32Array caches used for uploading Matrix uniforms
  14263. var mat4array = new Float32Array( 16 );
  14264. var mat3array = new Float32Array( 9 );
  14265. var mat2array = new Float32Array( 4 );
  14266. // Flattening for arrays of vectors and matrices
  14267. function flatten( array, nBlocks, blockSize ) {
  14268. var firstElem = array[ 0 ];
  14269. if ( firstElem <= 0 || firstElem > 0 ) return array;
  14270. // unoptimized: ! isNaN( firstElem )
  14271. // see http://jacksondunstan.com/articles/983
  14272. var n = nBlocks * blockSize,
  14273. r = arrayCacheF32[ n ];
  14274. if ( r === undefined ) {
  14275. r = new Float32Array( n );
  14276. arrayCacheF32[ n ] = r;
  14277. }
  14278. if ( nBlocks !== 0 ) {
  14279. firstElem.toArray( r, 0 );
  14280. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  14281. offset += blockSize;
  14282. array[ i ].toArray( r, offset );
  14283. }
  14284. }
  14285. return r;
  14286. }
  14287. function arraysEqual( a, b ) {
  14288. if ( a.length !== b.length ) return false;
  14289. for ( var i = 0, l = a.length; i < l; i ++ ) {
  14290. if ( a[ i ] !== b[ i ] ) return false;
  14291. }
  14292. return true;
  14293. }
  14294. function copyArray( a, b ) {
  14295. for ( var i = 0, l = b.length; i < l; i ++ ) {
  14296. a[ i ] = b[ i ];
  14297. }
  14298. }
  14299. // Texture unit allocation
  14300. function allocTexUnits( renderer, n ) {
  14301. var r = arrayCacheI32[ n ];
  14302. if ( r === undefined ) {
  14303. r = new Int32Array( n );
  14304. arrayCacheI32[ n ] = r;
  14305. }
  14306. for ( var i = 0; i !== n; ++ i )
  14307. r[ i ] = renderer.allocTextureUnit();
  14308. return r;
  14309. }
  14310. // --- Setters ---
  14311. // Note: Defining these methods externally, because they come in a bunch
  14312. // and this way their names minify.
  14313. // Single scalar
  14314. function setValue1f( gl, v ) {
  14315. var cache = this.cache;
  14316. if ( cache[ 0 ] === v ) return;
  14317. gl.uniform1f( this.addr, v );
  14318. cache[ 0 ] = v;
  14319. }
  14320. function setValue1i( gl, v ) {
  14321. var cache = this.cache;
  14322. if ( cache[ 0 ] === v ) return;
  14323. gl.uniform1i( this.addr, v );
  14324. cache[ 0 ] = v;
  14325. }
  14326. // Single float vector (from flat array or THREE.VectorN)
  14327. function setValue2fv( gl, v ) {
  14328. var cache = this.cache;
  14329. if ( v.x !== undefined ) {
  14330. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  14331. gl.uniform2f( this.addr, v.x, v.y );
  14332. cache[ 0 ] = v.x;
  14333. cache[ 1 ] = v.y;
  14334. }
  14335. } else {
  14336. if ( arraysEqual( cache, v ) ) return;
  14337. gl.uniform2fv( this.addr, v );
  14338. copyArray( cache, v );
  14339. }
  14340. }
  14341. function setValue3fv( gl, v ) {
  14342. var cache = this.cache;
  14343. if ( v.x !== undefined ) {
  14344. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  14345. gl.uniform3f( this.addr, v.x, v.y, v.z );
  14346. cache[ 0 ] = v.x;
  14347. cache[ 1 ] = v.y;
  14348. cache[ 2 ] = v.z;
  14349. }
  14350. } else if ( v.r !== undefined ) {
  14351. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  14352. gl.uniform3f( this.addr, v.r, v.g, v.b );
  14353. cache[ 0 ] = v.r;
  14354. cache[ 1 ] = v.g;
  14355. cache[ 2 ] = v.b;
  14356. }
  14357. } else {
  14358. if ( arraysEqual( cache, v ) ) return;
  14359. gl.uniform3fv( this.addr, v );
  14360. copyArray( cache, v );
  14361. }
  14362. }
  14363. function setValue4fv( gl, v ) {
  14364. var cache = this.cache;
  14365. if ( v.x !== undefined ) {
  14366. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  14367. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  14368. cache[ 0 ] = v.x;
  14369. cache[ 1 ] = v.y;
  14370. cache[ 2 ] = v.z;
  14371. cache[ 3 ] = v.w;
  14372. }
  14373. } else {
  14374. if ( arraysEqual( cache, v ) ) return;
  14375. gl.uniform4fv( this.addr, v );
  14376. copyArray( cache, v );
  14377. }
  14378. }
  14379. // Single matrix (from flat array or MatrixN)
  14380. function setValue2fm( gl, v ) {
  14381. var cache = this.cache;
  14382. var elements = v.elements;
  14383. if ( elements === undefined ) {
  14384. if ( arraysEqual( cache, v ) ) return;
  14385. gl.uniformMatrix2fv( this.addr, false, v );
  14386. copyArray( cache, v );
  14387. } else {
  14388. if ( arraysEqual( cache, elements ) ) return;
  14389. mat2array.set( elements );
  14390. gl.uniformMatrix2fv( this.addr, false, mat2array );
  14391. copyArray( cache, elements );
  14392. }
  14393. }
  14394. function setValue3fm( gl, v ) {
  14395. var cache = this.cache;
  14396. var elements = v.elements;
  14397. if ( elements === undefined ) {
  14398. if ( arraysEqual( cache, v ) ) return;
  14399. gl.uniformMatrix3fv( this.addr, false, v );
  14400. copyArray( cache, v );
  14401. } else {
  14402. if ( arraysEqual( cache, elements ) ) return;
  14403. mat3array.set( elements );
  14404. gl.uniformMatrix3fv( this.addr, false, mat3array );
  14405. copyArray( cache, elements );
  14406. }
  14407. }
  14408. function setValue4fm( gl, v ) {
  14409. var cache = this.cache;
  14410. var elements = v.elements;
  14411. if ( elements === undefined ) {
  14412. if ( arraysEqual( cache, v ) ) return;
  14413. gl.uniformMatrix4fv( this.addr, false, v );
  14414. copyArray( cache, v );
  14415. } else {
  14416. if ( arraysEqual( cache, elements ) ) return;
  14417. mat4array.set( elements );
  14418. gl.uniformMatrix4fv( this.addr, false, mat4array );
  14419. copyArray( cache, elements );
  14420. }
  14421. }
  14422. // Single texture (2D / Cube)
  14423. function setValueT1( gl, v, renderer ) {
  14424. var cache = this.cache;
  14425. var unit = renderer.allocTextureUnit();
  14426. if ( cache[ 0 ] !== unit ) {
  14427. gl.uniform1i( this.addr, unit );
  14428. cache[ 0 ] = unit;
  14429. }
  14430. renderer.setTexture2D( v || emptyTexture, unit );
  14431. }
  14432. function setValueT2DArray1( gl, v, renderer ) {
  14433. var cache = this.cache;
  14434. var unit = renderer.allocTextureUnit();
  14435. if ( cache[ 0 ] !== unit ) {
  14436. gl.uniform1i( this.addr, unit );
  14437. cache[ 0 ] = unit;
  14438. }
  14439. renderer.setTexture2DArray( v || emptyTexture2dArray, unit );
  14440. }
  14441. function setValueT3D1( gl, v, renderer ) {
  14442. var cache = this.cache;
  14443. var unit = renderer.allocTextureUnit();
  14444. if ( cache[ 0 ] !== unit ) {
  14445. gl.uniform1i( this.addr, unit );
  14446. cache[ 0 ] = unit;
  14447. }
  14448. renderer.setTexture3D( v || emptyTexture3d, unit );
  14449. }
  14450. function setValueT6( gl, v, renderer ) {
  14451. var cache = this.cache;
  14452. var unit = renderer.allocTextureUnit();
  14453. if ( cache[ 0 ] !== unit ) {
  14454. gl.uniform1i( this.addr, unit );
  14455. cache[ 0 ] = unit;
  14456. }
  14457. renderer.setTextureCube( v || emptyCubeTexture, unit );
  14458. }
  14459. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  14460. function setValue2iv( gl, v ) {
  14461. var cache = this.cache;
  14462. if ( arraysEqual( cache, v ) ) return;
  14463. gl.uniform2iv( this.addr, v );
  14464. copyArray( cache, v );
  14465. }
  14466. function setValue3iv( gl, v ) {
  14467. var cache = this.cache;
  14468. if ( arraysEqual( cache, v ) ) return;
  14469. gl.uniform3iv( this.addr, v );
  14470. copyArray( cache, v );
  14471. }
  14472. function setValue4iv( gl, v ) {
  14473. var cache = this.cache;
  14474. if ( arraysEqual( cache, v ) ) return;
  14475. gl.uniform4iv( this.addr, v );
  14476. copyArray( cache, v );
  14477. }
  14478. // Helper to pick the right setter for the singular case
  14479. function getSingularSetter( type ) {
  14480. switch ( type ) {
  14481. case 0x1406: return setValue1f; // FLOAT
  14482. case 0x8b50: return setValue2fv; // _VEC2
  14483. case 0x8b51: return setValue3fv; // _VEC3
  14484. case 0x8b52: return setValue4fv; // _VEC4
  14485. case 0x8b5a: return setValue2fm; // _MAT2
  14486. case 0x8b5b: return setValue3fm; // _MAT3
  14487. case 0x8b5c: return setValue4fm; // _MAT4
  14488. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  14489. case 0x8b5f: return setValueT3D1; // SAMPLER_3D
  14490. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  14491. case 0x8DC1: return setValueT2DArray1; // SAMPLER_2D_ARRAY
  14492. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  14493. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  14494. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  14495. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  14496. }
  14497. }
  14498. // Array of scalars
  14499. function setValue1fv( gl, v ) {
  14500. var cache = this.cache;
  14501. if ( arraysEqual( cache, v ) ) return;
  14502. gl.uniform1fv( this.addr, v );
  14503. copyArray( cache, v );
  14504. }
  14505. function setValue1iv( gl, v ) {
  14506. var cache = this.cache;
  14507. if ( arraysEqual( cache, v ) ) return;
  14508. gl.uniform1iv( this.addr, v );
  14509. copyArray( cache, v );
  14510. }
  14511. // Array of vectors (flat or from THREE classes)
  14512. function setValueV2a( gl, v ) {
  14513. var cache = this.cache;
  14514. var data = flatten( v, this.size, 2 );
  14515. if ( arraysEqual( cache, data ) ) return;
  14516. gl.uniform2fv( this.addr, data );
  14517. this.updateCache( data );
  14518. }
  14519. function setValueV3a( gl, v ) {
  14520. var cache = this.cache;
  14521. var data = flatten( v, this.size, 3 );
  14522. if ( arraysEqual( cache, data ) ) return;
  14523. gl.uniform3fv( this.addr, data );
  14524. this.updateCache( data );
  14525. }
  14526. function setValueV4a( gl, v ) {
  14527. var cache = this.cache;
  14528. var data = flatten( v, this.size, 4 );
  14529. if ( arraysEqual( cache, data ) ) return;
  14530. gl.uniform4fv( this.addr, data );
  14531. this.updateCache( data );
  14532. }
  14533. // Array of matrices (flat or from THREE clases)
  14534. function setValueM2a( gl, v ) {
  14535. var cache = this.cache;
  14536. var data = flatten( v, this.size, 4 );
  14537. if ( arraysEqual( cache, data ) ) return;
  14538. gl.uniformMatrix2fv( this.addr, false, data );
  14539. this.updateCache( data );
  14540. }
  14541. function setValueM3a( gl, v ) {
  14542. var cache = this.cache;
  14543. var data = flatten( v, this.size, 9 );
  14544. if ( arraysEqual( cache, data ) ) return;
  14545. gl.uniformMatrix3fv( this.addr, false, data );
  14546. this.updateCache( data );
  14547. }
  14548. function setValueM4a( gl, v ) {
  14549. var cache = this.cache;
  14550. var data = flatten( v, this.size, 16 );
  14551. if ( arraysEqual( cache, data ) ) return;
  14552. gl.uniformMatrix4fv( this.addr, false, data );
  14553. this.updateCache( data );
  14554. }
  14555. // Array of textures (2D / Cube)
  14556. function setValueT1a( gl, v, renderer ) {
  14557. var cache = this.cache;
  14558. var n = v.length;
  14559. var units = allocTexUnits( renderer, n );
  14560. if ( arraysEqual( cache, units ) === false ) {
  14561. gl.uniform1iv( this.addr, units );
  14562. copyArray( cache, units );
  14563. }
  14564. for ( var i = 0; i !== n; ++ i ) {
  14565. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  14566. }
  14567. }
  14568. function setValueT6a( gl, v, renderer ) {
  14569. var cache = this.cache;
  14570. var n = v.length;
  14571. var units = allocTexUnits( renderer, n );
  14572. if ( arraysEqual( cache, units ) === false ) {
  14573. gl.uniform1iv( this.addr, units );
  14574. copyArray( cache, units );
  14575. }
  14576. for ( var i = 0; i !== n; ++ i ) {
  14577. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  14578. }
  14579. }
  14580. // Helper to pick the right setter for a pure (bottom-level) array
  14581. function getPureArraySetter( type ) {
  14582. switch ( type ) {
  14583. case 0x1406: return setValue1fv; // FLOAT
  14584. case 0x8b50: return setValueV2a; // _VEC2
  14585. case 0x8b51: return setValueV3a; // _VEC3
  14586. case 0x8b52: return setValueV4a; // _VEC4
  14587. case 0x8b5a: return setValueM2a; // _MAT2
  14588. case 0x8b5b: return setValueM3a; // _MAT3
  14589. case 0x8b5c: return setValueM4a; // _MAT4
  14590. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  14591. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  14592. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  14593. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  14594. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  14595. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  14596. }
  14597. }
  14598. // --- Uniform Classes ---
  14599. function SingleUniform( id, activeInfo, addr ) {
  14600. this.id = id;
  14601. this.addr = addr;
  14602. this.cache = [];
  14603. this.setValue = getSingularSetter( activeInfo.type );
  14604. // this.path = activeInfo.name; // DEBUG
  14605. }
  14606. function PureArrayUniform( id, activeInfo, addr ) {
  14607. this.id = id;
  14608. this.addr = addr;
  14609. this.cache = [];
  14610. this.size = activeInfo.size;
  14611. this.setValue = getPureArraySetter( activeInfo.type );
  14612. // this.path = activeInfo.name; // DEBUG
  14613. }
  14614. PureArrayUniform.prototype.updateCache = function ( data ) {
  14615. var cache = this.cache;
  14616. if ( data instanceof Float32Array && cache.length !== data.length ) {
  14617. this.cache = new Float32Array( data.length );
  14618. }
  14619. copyArray( cache, data );
  14620. };
  14621. function StructuredUniform( id ) {
  14622. this.id = id;
  14623. UniformContainer.call( this ); // mix-in
  14624. }
  14625. StructuredUniform.prototype.setValue = function ( gl, value, renderer ) {
  14626. var seq = this.seq;
  14627. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  14628. var u = seq[ i ];
  14629. u.setValue( gl, value[ u.id ], renderer );
  14630. }
  14631. };
  14632. // --- Top-level ---
  14633. // Parser - builds up the property tree from the path strings
  14634. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  14635. // extracts
  14636. // - the identifier (member name or array index)
  14637. // - followed by an optional right bracket (found when array index)
  14638. // - followed by an optional left bracket or dot (type of subscript)
  14639. //
  14640. // Note: These portions can be read in a non-overlapping fashion and
  14641. // allow straightforward parsing of the hierarchy that WebGL encodes
  14642. // in the uniform names.
  14643. function addUniform( container, uniformObject ) {
  14644. container.seq.push( uniformObject );
  14645. container.map[ uniformObject.id ] = uniformObject;
  14646. }
  14647. function parseUniform( activeInfo, addr, container ) {
  14648. var path = activeInfo.name,
  14649. pathLength = path.length;
  14650. // reset RegExp object, because of the early exit of a previous run
  14651. RePathPart.lastIndex = 0;
  14652. while ( true ) {
  14653. var match = RePathPart.exec( path ),
  14654. matchEnd = RePathPart.lastIndex,
  14655. id = match[ 1 ],
  14656. idIsIndex = match[ 2 ] === ']',
  14657. subscript = match[ 3 ];
  14658. if ( idIsIndex ) id = id | 0; // convert to integer
  14659. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  14660. // bare name or "pure" bottom-level array "[0]" suffix
  14661. addUniform( container, subscript === undefined ?
  14662. new SingleUniform( id, activeInfo, addr ) :
  14663. new PureArrayUniform( id, activeInfo, addr ) );
  14664. break;
  14665. } else {
  14666. // step into inner node / create it in case it doesn't exist
  14667. var map = container.map, next = map[ id ];
  14668. if ( next === undefined ) {
  14669. next = new StructuredUniform( id );
  14670. addUniform( container, next );
  14671. }
  14672. container = next;
  14673. }
  14674. }
  14675. }
  14676. // Root Container
  14677. function WebGLUniforms( gl, program, renderer ) {
  14678. UniformContainer.call( this );
  14679. this.renderer = renderer;
  14680. var n = gl.getProgramParameter( program, 35718 );
  14681. for ( var i = 0; i < n; ++ i ) {
  14682. var info = gl.getActiveUniform( program, i ),
  14683. addr = gl.getUniformLocation( program, info.name );
  14684. parseUniform( info, addr, this );
  14685. }
  14686. }
  14687. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  14688. var u = this.map[ name ];
  14689. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  14690. };
  14691. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  14692. var v = object[ name ];
  14693. if ( v !== undefined ) this.setValue( gl, name, v );
  14694. };
  14695. // Static interface
  14696. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  14697. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  14698. var u = seq[ i ],
  14699. v = values[ u.id ];
  14700. if ( v.needsUpdate !== false ) {
  14701. // note: always updating when .needsUpdate is undefined
  14702. u.setValue( gl, v.value, renderer );
  14703. }
  14704. }
  14705. };
  14706. WebGLUniforms.seqWithValue = function ( seq, values ) {
  14707. var r = [];
  14708. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  14709. var u = seq[ i ];
  14710. if ( u.id in values ) r.push( u );
  14711. }
  14712. return r;
  14713. };
  14714. /**
  14715. * @author mrdoob / http://mrdoob.com/
  14716. */
  14717. function addLineNumbers( string ) {
  14718. var lines = string.split( '\n' );
  14719. for ( var i = 0; i < lines.length; i ++ ) {
  14720. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14721. }
  14722. return lines.join( '\n' );
  14723. }
  14724. function WebGLShader( gl, type, string ) {
  14725. var shader = gl.createShader( type );
  14726. gl.shaderSource( shader, string );
  14727. gl.compileShader( shader );
  14728. if ( gl.getShaderParameter( shader, 35713 ) === false ) {
  14729. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14730. }
  14731. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14732. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === 35633 ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14733. }
  14734. // --enable-privileged-webgl-extension
  14735. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14736. return shader;
  14737. }
  14738. /**
  14739. * @author mrdoob / http://mrdoob.com/
  14740. */
  14741. var programIdCount = 0;
  14742. function getEncodingComponents( encoding ) {
  14743. switch ( encoding ) {
  14744. case LinearEncoding:
  14745. return [ 'Linear', '( value )' ];
  14746. case sRGBEncoding:
  14747. return [ 'sRGB', '( value )' ];
  14748. case RGBEEncoding:
  14749. return [ 'RGBE', '( value )' ];
  14750. case RGBM7Encoding:
  14751. return [ 'RGBM', '( value, 7.0 )' ];
  14752. case RGBM16Encoding:
  14753. return [ 'RGBM', '( value, 16.0 )' ];
  14754. case RGBDEncoding:
  14755. return [ 'RGBD', '( value, 256.0 )' ];
  14756. case GammaEncoding:
  14757. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  14758. default:
  14759. throw new Error( 'unsupported encoding: ' + encoding );
  14760. }
  14761. }
  14762. function getTexelDecodingFunction( functionName, encoding ) {
  14763. var components = getEncodingComponents( encoding );
  14764. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  14765. }
  14766. function getTexelEncodingFunction( functionName, encoding ) {
  14767. var components = getEncodingComponents( encoding );
  14768. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  14769. }
  14770. function getToneMappingFunction( functionName, toneMapping ) {
  14771. var toneMappingName;
  14772. switch ( toneMapping ) {
  14773. case LinearToneMapping:
  14774. toneMappingName = 'Linear';
  14775. break;
  14776. case ReinhardToneMapping:
  14777. toneMappingName = 'Reinhard';
  14778. break;
  14779. case Uncharted2ToneMapping:
  14780. toneMappingName = 'Uncharted2';
  14781. break;
  14782. case CineonToneMapping:
  14783. toneMappingName = 'OptimizedCineon';
  14784. break;
  14785. case ACESFilmicToneMapping:
  14786. toneMappingName = 'ACESFilmic';
  14787. break;
  14788. default:
  14789. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  14790. }
  14791. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  14792. }
  14793. function generateExtensions( extensions, parameters, rendererExtensions ) {
  14794. extensions = extensions || {};
  14795. var chunks = [
  14796. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || ( parameters.normalMap && ! parameters.objectSpaceNormalMap ) || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14797. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  14798. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  14799. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  14800. ];
  14801. return chunks.filter( filterEmptyLine ).join( '\n' );
  14802. }
  14803. function generateDefines( defines ) {
  14804. var chunks = [];
  14805. for ( var name in defines ) {
  14806. var value = defines[ name ];
  14807. if ( value === false ) continue;
  14808. chunks.push( '#define ' + name + ' ' + value );
  14809. }
  14810. return chunks.join( '\n' );
  14811. }
  14812. function fetchAttributeLocations( gl, program ) {
  14813. var attributes = {};
  14814. var n = gl.getProgramParameter( program, 35721 );
  14815. for ( var i = 0; i < n; i ++ ) {
  14816. var info = gl.getActiveAttrib( program, i );
  14817. var name = info.name;
  14818. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  14819. attributes[ name ] = gl.getAttribLocation( program, name );
  14820. }
  14821. return attributes;
  14822. }
  14823. function filterEmptyLine( string ) {
  14824. return string !== '';
  14825. }
  14826. function replaceLightNums( string, parameters ) {
  14827. return string
  14828. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  14829. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  14830. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  14831. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  14832. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  14833. }
  14834. function replaceClippingPlaneNums( string, parameters ) {
  14835. return string
  14836. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  14837. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  14838. }
  14839. function parseIncludes( string ) {
  14840. var pattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  14841. function replace( match, include ) {
  14842. var replace = ShaderChunk[ include ];
  14843. if ( replace === undefined ) {
  14844. throw new Error( 'Can not resolve #include <' + include + '>' );
  14845. }
  14846. return parseIncludes( replace );
  14847. }
  14848. return string.replace( pattern, replace );
  14849. }
  14850. function unrollLoops( string ) {
  14851. var pattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  14852. function replace( match, start, end, snippet ) {
  14853. var unroll = '';
  14854. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  14855. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  14856. }
  14857. return unroll;
  14858. }
  14859. return string.replace( pattern, replace );
  14860. }
  14861. function WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities ) {
  14862. var gl = renderer.context;
  14863. var defines = material.defines;
  14864. var vertexShader = shader.vertexShader;
  14865. var fragmentShader = shader.fragmentShader;
  14866. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14867. if ( parameters.shadowMapType === PCFShadowMap ) {
  14868. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14869. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14870. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14871. }
  14872. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14873. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14874. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14875. if ( parameters.envMap ) {
  14876. switch ( material.envMap.mapping ) {
  14877. case CubeReflectionMapping:
  14878. case CubeRefractionMapping:
  14879. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14880. break;
  14881. case CubeUVReflectionMapping:
  14882. case CubeUVRefractionMapping:
  14883. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14884. break;
  14885. case EquirectangularReflectionMapping:
  14886. case EquirectangularRefractionMapping:
  14887. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14888. break;
  14889. case SphericalReflectionMapping:
  14890. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14891. break;
  14892. }
  14893. switch ( material.envMap.mapping ) {
  14894. case CubeRefractionMapping:
  14895. case EquirectangularRefractionMapping:
  14896. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14897. break;
  14898. }
  14899. switch ( material.combine ) {
  14900. case MultiplyOperation:
  14901. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14902. break;
  14903. case MixOperation:
  14904. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14905. break;
  14906. case AddOperation:
  14907. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14908. break;
  14909. }
  14910. }
  14911. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14912. // console.log( 'building new program ' );
  14913. //
  14914. var customExtensions = capabilities.isWebGL2 ? '' : generateExtensions( material.extensions, parameters, extensions );
  14915. var customDefines = generateDefines( defines );
  14916. //
  14917. var program = gl.createProgram();
  14918. var prefixVertex, prefixFragment;
  14919. if ( material.isRawShaderMaterial ) {
  14920. prefixVertex = [
  14921. customDefines
  14922. ].filter( filterEmptyLine ).join( '\n' );
  14923. if ( prefixVertex.length > 0 ) {
  14924. prefixVertex += '\n';
  14925. }
  14926. prefixFragment = [
  14927. customExtensions,
  14928. customDefines
  14929. ].filter( filterEmptyLine ).join( '\n' );
  14930. if ( prefixFragment.length > 0 ) {
  14931. prefixFragment += '\n';
  14932. }
  14933. } else {
  14934. prefixVertex = [
  14935. 'precision ' + parameters.precision + ' float;',
  14936. 'precision ' + parameters.precision + ' int;',
  14937. '#define SHADER_NAME ' + shader.name,
  14938. customDefines,
  14939. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14940. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14941. '#define MAX_BONES ' + parameters.maxBones,
  14942. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14943. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14944. parameters.map ? '#define USE_MAP' : '',
  14945. parameters.envMap ? '#define USE_ENVMAP' : '',
  14946. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14947. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14948. parameters.aoMap ? '#define USE_AOMAP' : '',
  14949. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14950. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14951. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14952. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  14953. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  14954. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14955. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14956. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14957. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14958. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  14959. parameters.vertexColors ? '#define USE_COLOR' : '',
  14960. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14961. parameters.skinning ? '#define USE_SKINNING' : '',
  14962. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14963. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14964. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  14965. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14966. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14967. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14968. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14969. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14970. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14971. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14972. 'uniform mat4 modelMatrix;',
  14973. 'uniform mat4 modelViewMatrix;',
  14974. 'uniform mat4 projectionMatrix;',
  14975. 'uniform mat4 viewMatrix;',
  14976. 'uniform mat3 normalMatrix;',
  14977. 'uniform vec3 cameraPosition;',
  14978. 'attribute vec3 position;',
  14979. 'attribute vec3 normal;',
  14980. 'attribute vec2 uv;',
  14981. '#ifdef USE_TANGENT',
  14982. ' attribute vec4 tangent;',
  14983. '#endif',
  14984. '#ifdef USE_COLOR',
  14985. ' attribute vec3 color;',
  14986. '#endif',
  14987. '#ifdef USE_MORPHTARGETS',
  14988. ' attribute vec3 morphTarget0;',
  14989. ' attribute vec3 morphTarget1;',
  14990. ' attribute vec3 morphTarget2;',
  14991. ' attribute vec3 morphTarget3;',
  14992. ' #ifdef USE_MORPHNORMALS',
  14993. ' attribute vec3 morphNormal0;',
  14994. ' attribute vec3 morphNormal1;',
  14995. ' attribute vec3 morphNormal2;',
  14996. ' attribute vec3 morphNormal3;',
  14997. ' #else',
  14998. ' attribute vec3 morphTarget4;',
  14999. ' attribute vec3 morphTarget5;',
  15000. ' attribute vec3 morphTarget6;',
  15001. ' attribute vec3 morphTarget7;',
  15002. ' #endif',
  15003. '#endif',
  15004. '#ifdef USE_SKINNING',
  15005. ' attribute vec4 skinIndex;',
  15006. ' attribute vec4 skinWeight;',
  15007. '#endif',
  15008. '\n'
  15009. ].filter( filterEmptyLine ).join( '\n' );
  15010. prefixFragment = [
  15011. customExtensions,
  15012. 'precision ' + parameters.precision + ' float;',
  15013. 'precision ' + parameters.precision + ' int;',
  15014. '#define SHADER_NAME ' + shader.name,
  15015. customDefines,
  15016. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  15017. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15018. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15019. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15020. parameters.map ? '#define USE_MAP' : '',
  15021. parameters.matcap ? '#define USE_MATCAP' : '',
  15022. parameters.envMap ? '#define USE_ENVMAP' : '',
  15023. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  15024. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15025. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  15026. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15027. parameters.aoMap ? '#define USE_AOMAP' : '',
  15028. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15029. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15030. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15031. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  15032. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15033. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  15034. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  15035. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15036. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  15037. parameters.vertexColors ? '#define USE_COLOR' : '',
  15038. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  15039. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15040. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15041. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15042. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15043. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15044. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  15045. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  15046. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15047. parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15048. parameters.envMap && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '',
  15049. 'uniform mat4 viewMatrix;',
  15050. 'uniform vec3 cameraPosition;',
  15051. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  15052. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  15053. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  15054. parameters.dithering ? '#define DITHERING' : '',
  15055. ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ?
  15056. ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  15057. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  15058. parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  15059. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  15060. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  15061. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  15062. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  15063. '\n'
  15064. ].filter( filterEmptyLine ).join( '\n' );
  15065. }
  15066. vertexShader = parseIncludes( vertexShader );
  15067. vertexShader = replaceLightNums( vertexShader, parameters );
  15068. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  15069. fragmentShader = parseIncludes( fragmentShader );
  15070. fragmentShader = replaceLightNums( fragmentShader, parameters );
  15071. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  15072. vertexShader = unrollLoops( vertexShader );
  15073. fragmentShader = unrollLoops( fragmentShader );
  15074. if ( capabilities.isWebGL2 && ! material.isRawShaderMaterial ) {
  15075. var isGLSL3ShaderMaterial = false;
  15076. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  15077. if ( material.isShaderMaterial &&
  15078. vertexShader.match( versionRegex ) !== null &&
  15079. fragmentShader.match( versionRegex ) !== null ) {
  15080. isGLSL3ShaderMaterial = true;
  15081. vertexShader = vertexShader.replace( versionRegex, '' );
  15082. fragmentShader = fragmentShader.replace( versionRegex, '' );
  15083. }
  15084. // GLSL 3.0 conversion
  15085. prefixVertex = [
  15086. '#version 300 es\n',
  15087. '#define attribute in',
  15088. '#define varying out',
  15089. '#define texture2D texture'
  15090. ].join( '\n' ) + '\n' + prefixVertex;
  15091. prefixFragment = [
  15092. '#version 300 es\n',
  15093. '#define varying in',
  15094. isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
  15095. isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
  15096. '#define gl_FragDepthEXT gl_FragDepth',
  15097. '#define texture2D texture',
  15098. '#define textureCube texture',
  15099. '#define texture2DProj textureProj',
  15100. '#define texture2DLodEXT textureLod',
  15101. '#define texture2DProjLodEXT textureProjLod',
  15102. '#define textureCubeLodEXT textureLod',
  15103. '#define texture2DGradEXT textureGrad',
  15104. '#define texture2DProjGradEXT textureProjGrad',
  15105. '#define textureCubeGradEXT textureGrad'
  15106. ].join( '\n' ) + '\n' + prefixFragment;
  15107. }
  15108. var vertexGlsl = prefixVertex + vertexShader;
  15109. var fragmentGlsl = prefixFragment + fragmentShader;
  15110. // console.log( '*VERTEX*', vertexGlsl );
  15111. // console.log( '*FRAGMENT*', fragmentGlsl );
  15112. var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  15113. var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  15114. gl.attachShader( program, glVertexShader );
  15115. gl.attachShader( program, glFragmentShader );
  15116. // Force a particular attribute to index 0.
  15117. if ( material.index0AttributeName !== undefined ) {
  15118. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  15119. } else if ( parameters.morphTargets === true ) {
  15120. // programs with morphTargets displace position out of attribute 0
  15121. gl.bindAttribLocation( program, 0, 'position' );
  15122. }
  15123. gl.linkProgram( program );
  15124. var programLog = gl.getProgramInfoLog( program ).trim();
  15125. var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  15126. var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  15127. var runnable = true;
  15128. var haveDiagnostics = true;
  15129. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  15130. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  15131. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  15132. runnable = false;
  15133. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  15134. } else if ( programLog !== '' ) {
  15135. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  15136. } else if ( vertexLog === '' || fragmentLog === '' ) {
  15137. haveDiagnostics = false;
  15138. }
  15139. if ( haveDiagnostics ) {
  15140. this.diagnostics = {
  15141. runnable: runnable,
  15142. material: material,
  15143. programLog: programLog,
  15144. vertexShader: {
  15145. log: vertexLog,
  15146. prefix: prefixVertex
  15147. },
  15148. fragmentShader: {
  15149. log: fragmentLog,
  15150. prefix: prefixFragment
  15151. }
  15152. };
  15153. }
  15154. // clean up
  15155. gl.deleteShader( glVertexShader );
  15156. gl.deleteShader( glFragmentShader );
  15157. // set up caching for uniform locations
  15158. var cachedUniforms;
  15159. this.getUniforms = function () {
  15160. if ( cachedUniforms === undefined ) {
  15161. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  15162. }
  15163. return cachedUniforms;
  15164. };
  15165. // set up caching for attribute locations
  15166. var cachedAttributes;
  15167. this.getAttributes = function () {
  15168. if ( cachedAttributes === undefined ) {
  15169. cachedAttributes = fetchAttributeLocations( gl, program );
  15170. }
  15171. return cachedAttributes;
  15172. };
  15173. // free resource
  15174. this.destroy = function () {
  15175. gl.deleteProgram( program );
  15176. this.program = undefined;
  15177. };
  15178. // DEPRECATED
  15179. Object.defineProperties( this, {
  15180. uniforms: {
  15181. get: function () {
  15182. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  15183. return this.getUniforms();
  15184. }
  15185. },
  15186. attributes: {
  15187. get: function () {
  15188. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  15189. return this.getAttributes();
  15190. }
  15191. }
  15192. } );
  15193. //
  15194. this.name = shader.name;
  15195. this.id = programIdCount ++;
  15196. this.code = code;
  15197. this.usedTimes = 1;
  15198. this.program = program;
  15199. this.vertexShader = glVertexShader;
  15200. this.fragmentShader = glFragmentShader;
  15201. return this;
  15202. }
  15203. /**
  15204. * @author mrdoob / http://mrdoob.com/
  15205. */
  15206. function WebGLPrograms( renderer, extensions, capabilities ) {
  15207. var programs = [];
  15208. var shaderIDs = {
  15209. MeshDepthMaterial: 'depth',
  15210. MeshDistanceMaterial: 'distanceRGBA',
  15211. MeshNormalMaterial: 'normal',
  15212. MeshBasicMaterial: 'basic',
  15213. MeshLambertMaterial: 'lambert',
  15214. MeshPhongMaterial: 'phong',
  15215. MeshToonMaterial: 'phong',
  15216. MeshStandardMaterial: 'physical',
  15217. MeshPhysicalMaterial: 'physical',
  15218. MeshMatcapMaterial: 'matcap',
  15219. LineBasicMaterial: 'basic',
  15220. LineDashedMaterial: 'dashed',
  15221. PointsMaterial: 'points',
  15222. ShadowMaterial: 'shadow',
  15223. SpriteMaterial: 'sprite'
  15224. };
  15225. var parameterNames = [
  15226. "precision", "supportsVertexTextures", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding",
  15227. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "displacementMap", "specularMap",
  15228. "roughnessMap", "metalnessMap", "gradientMap",
  15229. "alphaMap", "combine", "vertexColors", "vertexTangents", "fog", "useFog", "fogExp",
  15230. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  15231. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  15232. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  15233. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  15234. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  15235. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  15236. ];
  15237. function allocateBones( object ) {
  15238. var skeleton = object.skeleton;
  15239. var bones = skeleton.bones;
  15240. if ( capabilities.floatVertexTextures ) {
  15241. return 1024;
  15242. } else {
  15243. // default for when object is not specified
  15244. // ( for example when prebuilding shader to be used with multiple objects )
  15245. //
  15246. // - leave some extra space for other uniforms
  15247. // - limit here is ANGLE's 254 max uniform vectors
  15248. // (up to 54 should be safe)
  15249. var nVertexUniforms = capabilities.maxVertexUniforms;
  15250. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15251. var maxBones = Math.min( nVertexMatrices, bones.length );
  15252. if ( maxBones < bones.length ) {
  15253. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  15254. return 0;
  15255. }
  15256. return maxBones;
  15257. }
  15258. }
  15259. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  15260. var encoding;
  15261. if ( ! map ) {
  15262. encoding = LinearEncoding;
  15263. } else if ( map.isTexture ) {
  15264. encoding = map.encoding;
  15265. } else if ( map.isWebGLRenderTarget ) {
  15266. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  15267. encoding = map.texture.encoding;
  15268. }
  15269. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  15270. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  15271. encoding = GammaEncoding;
  15272. }
  15273. return encoding;
  15274. }
  15275. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  15276. var shaderID = shaderIDs[ material.type ];
  15277. // heuristics to create shader parameters according to lights in the scene
  15278. // (not to blow over maxLights budget)
  15279. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  15280. var precision = capabilities.precision;
  15281. if ( material.precision !== null ) {
  15282. precision = capabilities.getMaxPrecision( material.precision );
  15283. if ( precision !== material.precision ) {
  15284. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  15285. }
  15286. }
  15287. var currentRenderTarget = renderer.getRenderTarget();
  15288. var parameters = {
  15289. shaderID: shaderID,
  15290. precision: precision,
  15291. supportsVertexTextures: capabilities.vertexTextures,
  15292. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  15293. map: !! material.map,
  15294. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  15295. matcap: !! material.matcap,
  15296. matcapEncoding: getTextureEncodingFromMap( material.matcap, renderer.gammaInput ),
  15297. envMap: !! material.envMap,
  15298. envMapMode: material.envMap && material.envMap.mapping,
  15299. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  15300. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  15301. lightMap: !! material.lightMap,
  15302. aoMap: !! material.aoMap,
  15303. emissiveMap: !! material.emissiveMap,
  15304. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  15305. bumpMap: !! material.bumpMap,
  15306. normalMap: !! material.normalMap,
  15307. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  15308. displacementMap: !! material.displacementMap,
  15309. roughnessMap: !! material.roughnessMap,
  15310. metalnessMap: !! material.metalnessMap,
  15311. specularMap: !! material.specularMap,
  15312. alphaMap: !! material.alphaMap,
  15313. gradientMap: !! material.gradientMap,
  15314. combine: material.combine,
  15315. vertexTangents: ( material.normalMap && material.vertexTangents ),
  15316. vertexColors: material.vertexColors,
  15317. fog: !! fog,
  15318. useFog: material.fog,
  15319. fogExp: ( fog && fog.isFogExp2 ),
  15320. flatShading: material.flatShading,
  15321. sizeAttenuation: material.sizeAttenuation,
  15322. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  15323. skinning: material.skinning && maxBones > 0,
  15324. maxBones: maxBones,
  15325. useVertexTexture: capabilities.floatVertexTextures,
  15326. morphTargets: material.morphTargets,
  15327. morphNormals: material.morphNormals,
  15328. maxMorphTargets: renderer.maxMorphTargets,
  15329. maxMorphNormals: renderer.maxMorphNormals,
  15330. numDirLights: lights.directional.length,
  15331. numPointLights: lights.point.length,
  15332. numSpotLights: lights.spot.length,
  15333. numRectAreaLights: lights.rectArea.length,
  15334. numHemiLights: lights.hemi.length,
  15335. numClippingPlanes: nClipPlanes,
  15336. numClipIntersection: nClipIntersection,
  15337. dithering: material.dithering,
  15338. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  15339. shadowMapType: renderer.shadowMap.type,
  15340. toneMapping: renderer.toneMapping,
  15341. physicallyCorrectLights: renderer.physicallyCorrectLights,
  15342. premultipliedAlpha: material.premultipliedAlpha,
  15343. alphaTest: material.alphaTest,
  15344. doubleSided: material.side === DoubleSide,
  15345. flipSided: material.side === BackSide,
  15346. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  15347. };
  15348. return parameters;
  15349. };
  15350. this.getProgramCode = function ( material, parameters ) {
  15351. var array = [];
  15352. if ( parameters.shaderID ) {
  15353. array.push( parameters.shaderID );
  15354. } else {
  15355. array.push( material.fragmentShader );
  15356. array.push( material.vertexShader );
  15357. }
  15358. if ( material.defines !== undefined ) {
  15359. for ( var name in material.defines ) {
  15360. array.push( name );
  15361. array.push( material.defines[ name ] );
  15362. }
  15363. }
  15364. for ( var i = 0; i < parameterNames.length; i ++ ) {
  15365. array.push( parameters[ parameterNames[ i ] ] );
  15366. }
  15367. array.push( material.onBeforeCompile.toString() );
  15368. array.push( renderer.gammaOutput );
  15369. array.push( renderer.gammaFactor );
  15370. return array.join();
  15371. };
  15372. this.acquireProgram = function ( material, shader, parameters, code ) {
  15373. var program;
  15374. // Check if code has been already compiled
  15375. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  15376. var programInfo = programs[ p ];
  15377. if ( programInfo.code === code ) {
  15378. program = programInfo;
  15379. ++ program.usedTimes;
  15380. break;
  15381. }
  15382. }
  15383. if ( program === undefined ) {
  15384. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters, capabilities );
  15385. programs.push( program );
  15386. }
  15387. return program;
  15388. };
  15389. this.releaseProgram = function ( program ) {
  15390. if ( -- program.usedTimes === 0 ) {
  15391. // Remove from unordered set
  15392. var i = programs.indexOf( program );
  15393. programs[ i ] = programs[ programs.length - 1 ];
  15394. programs.pop();
  15395. // Free WebGL resources
  15396. program.destroy();
  15397. }
  15398. };
  15399. // Exposed for resource monitoring & error feedback via renderer.info:
  15400. this.programs = programs;
  15401. }
  15402. /**
  15403. * @author fordacious / fordacious.github.io
  15404. */
  15405. function WebGLProperties() {
  15406. var properties = new WeakMap();
  15407. function get( object ) {
  15408. var map = properties.get( object );
  15409. if ( map === undefined ) {
  15410. map = {};
  15411. properties.set( object, map );
  15412. }
  15413. return map;
  15414. }
  15415. function remove( object ) {
  15416. properties.delete( object );
  15417. }
  15418. function update( object, key, value ) {
  15419. properties.get( object )[ key ] = value;
  15420. }
  15421. function dispose() {
  15422. properties = new WeakMap();
  15423. }
  15424. return {
  15425. get: get,
  15426. remove: remove,
  15427. update: update,
  15428. dispose: dispose
  15429. };
  15430. }
  15431. /**
  15432. * @author mrdoob / http://mrdoob.com/
  15433. */
  15434. function painterSortStable( a, b ) {
  15435. if ( a.groupOrder !== b.groupOrder ) {
  15436. return a.groupOrder - b.groupOrder;
  15437. } else if ( a.renderOrder !== b.renderOrder ) {
  15438. return a.renderOrder - b.renderOrder;
  15439. } else if ( a.program && b.program && a.program !== b.program ) {
  15440. return a.program.id - b.program.id;
  15441. } else if ( a.material.id !== b.material.id ) {
  15442. return a.material.id - b.material.id;
  15443. } else if ( a.z !== b.z ) {
  15444. return a.z - b.z;
  15445. } else {
  15446. return a.id - b.id;
  15447. }
  15448. }
  15449. function reversePainterSortStable( a, b ) {
  15450. if ( a.groupOrder !== b.groupOrder ) {
  15451. return a.groupOrder - b.groupOrder;
  15452. } else if ( a.renderOrder !== b.renderOrder ) {
  15453. return a.renderOrder - b.renderOrder;
  15454. } else if ( a.z !== b.z ) {
  15455. return b.z - a.z;
  15456. } else {
  15457. return a.id - b.id;
  15458. }
  15459. }
  15460. function WebGLRenderList() {
  15461. var renderItems = [];
  15462. var renderItemsIndex = 0;
  15463. var opaque = [];
  15464. var transparent = [];
  15465. function init() {
  15466. renderItemsIndex = 0;
  15467. opaque.length = 0;
  15468. transparent.length = 0;
  15469. }
  15470. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  15471. var renderItem = renderItems[ renderItemsIndex ];
  15472. if ( renderItem === undefined ) {
  15473. renderItem = {
  15474. id: object.id,
  15475. object: object,
  15476. geometry: geometry,
  15477. material: material,
  15478. program: material.program,
  15479. groupOrder: groupOrder,
  15480. renderOrder: object.renderOrder,
  15481. z: z,
  15482. group: group
  15483. };
  15484. renderItems[ renderItemsIndex ] = renderItem;
  15485. } else {
  15486. renderItem.id = object.id;
  15487. renderItem.object = object;
  15488. renderItem.geometry = geometry;
  15489. renderItem.material = material;
  15490. renderItem.program = material.program;
  15491. renderItem.groupOrder = groupOrder;
  15492. renderItem.renderOrder = object.renderOrder;
  15493. renderItem.z = z;
  15494. renderItem.group = group;
  15495. }
  15496. renderItemsIndex ++;
  15497. return renderItem;
  15498. }
  15499. function push( object, geometry, material, groupOrder, z, group ) {
  15500. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  15501. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  15502. }
  15503. function unshift( object, geometry, material, groupOrder, z, group ) {
  15504. var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  15505. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  15506. }
  15507. function sort() {
  15508. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  15509. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  15510. }
  15511. return {
  15512. opaque: opaque,
  15513. transparent: transparent,
  15514. init: init,
  15515. push: push,
  15516. unshift: unshift,
  15517. sort: sort
  15518. };
  15519. }
  15520. function WebGLRenderLists() {
  15521. var lists = {};
  15522. function onSceneDispose( event ) {
  15523. var scene = event.target;
  15524. scene.removeEventListener( 'dispose', onSceneDispose );
  15525. delete lists[ scene.id ];
  15526. }
  15527. function get( scene, camera ) {
  15528. var cameras = lists[ scene.id ];
  15529. var list;
  15530. if ( cameras === undefined ) {
  15531. list = new WebGLRenderList();
  15532. lists[ scene.id ] = {};
  15533. lists[ scene.id ][ camera.id ] = list;
  15534. scene.addEventListener( 'dispose', onSceneDispose );
  15535. } else {
  15536. list = cameras[ camera.id ];
  15537. if ( list === undefined ) {
  15538. list = new WebGLRenderList();
  15539. cameras[ camera.id ] = list;
  15540. }
  15541. }
  15542. return list;
  15543. }
  15544. function dispose() {
  15545. lists = {};
  15546. }
  15547. return {
  15548. get: get,
  15549. dispose: dispose
  15550. };
  15551. }
  15552. /**
  15553. * @author mrdoob / http://mrdoob.com/
  15554. */
  15555. function UniformsCache() {
  15556. var lights = {};
  15557. return {
  15558. get: function ( light ) {
  15559. if ( lights[ light.id ] !== undefined ) {
  15560. return lights[ light.id ];
  15561. }
  15562. var uniforms;
  15563. switch ( light.type ) {
  15564. case 'DirectionalLight':
  15565. uniforms = {
  15566. direction: new Vector3(),
  15567. color: new Color(),
  15568. shadow: false,
  15569. shadowBias: 0,
  15570. shadowRadius: 1,
  15571. shadowMapSize: new Vector2()
  15572. };
  15573. break;
  15574. case 'SpotLight':
  15575. uniforms = {
  15576. position: new Vector3(),
  15577. direction: new Vector3(),
  15578. color: new Color(),
  15579. distance: 0,
  15580. coneCos: 0,
  15581. penumbraCos: 0,
  15582. decay: 0,
  15583. shadow: false,
  15584. shadowBias: 0,
  15585. shadowRadius: 1,
  15586. shadowMapSize: new Vector2()
  15587. };
  15588. break;
  15589. case 'PointLight':
  15590. uniforms = {
  15591. position: new Vector3(),
  15592. color: new Color(),
  15593. distance: 0,
  15594. decay: 0,
  15595. shadow: false,
  15596. shadowBias: 0,
  15597. shadowRadius: 1,
  15598. shadowMapSize: new Vector2(),
  15599. shadowCameraNear: 1,
  15600. shadowCameraFar: 1000
  15601. };
  15602. break;
  15603. case 'HemisphereLight':
  15604. uniforms = {
  15605. direction: new Vector3(),
  15606. skyColor: new Color(),
  15607. groundColor: new Color()
  15608. };
  15609. break;
  15610. case 'RectAreaLight':
  15611. uniforms = {
  15612. color: new Color(),
  15613. position: new Vector3(),
  15614. halfWidth: new Vector3(),
  15615. halfHeight: new Vector3()
  15616. // TODO (abelnation): set RectAreaLight shadow uniforms
  15617. };
  15618. break;
  15619. }
  15620. lights[ light.id ] = uniforms;
  15621. return uniforms;
  15622. }
  15623. };
  15624. }
  15625. var count = 0;
  15626. function WebGLLights() {
  15627. var cache = new UniformsCache();
  15628. var state = {
  15629. id: count ++,
  15630. hash: {
  15631. stateID: - 1,
  15632. directionalLength: - 1,
  15633. pointLength: - 1,
  15634. spotLength: - 1,
  15635. rectAreaLength: - 1,
  15636. hemiLength: - 1,
  15637. shadowsLength: - 1
  15638. },
  15639. ambient: [ 0, 0, 0 ],
  15640. directional: [],
  15641. directionalShadowMap: [],
  15642. directionalShadowMatrix: [],
  15643. spot: [],
  15644. spotShadowMap: [],
  15645. spotShadowMatrix: [],
  15646. rectArea: [],
  15647. point: [],
  15648. pointShadowMap: [],
  15649. pointShadowMatrix: [],
  15650. hemi: []
  15651. };
  15652. var vector3 = new Vector3();
  15653. var matrix4 = new Matrix4();
  15654. var matrix42 = new Matrix4();
  15655. function setup( lights, shadows, camera ) {
  15656. var r = 0, g = 0, b = 0;
  15657. var directionalLength = 0;
  15658. var pointLength = 0;
  15659. var spotLength = 0;
  15660. var rectAreaLength = 0;
  15661. var hemiLength = 0;
  15662. var viewMatrix = camera.matrixWorldInverse;
  15663. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  15664. var light = lights[ i ];
  15665. var color = light.color;
  15666. var intensity = light.intensity;
  15667. var distance = light.distance;
  15668. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  15669. if ( light.isAmbientLight ) {
  15670. r += color.r * intensity;
  15671. g += color.g * intensity;
  15672. b += color.b * intensity;
  15673. } else if ( light.isDirectionalLight ) {
  15674. var uniforms = cache.get( light );
  15675. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15676. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15677. vector3.setFromMatrixPosition( light.target.matrixWorld );
  15678. uniforms.direction.sub( vector3 );
  15679. uniforms.direction.transformDirection( viewMatrix );
  15680. uniforms.shadow = light.castShadow;
  15681. if ( light.castShadow ) {
  15682. var shadow = light.shadow;
  15683. uniforms.shadowBias = shadow.bias;
  15684. uniforms.shadowRadius = shadow.radius;
  15685. uniforms.shadowMapSize = shadow.mapSize;
  15686. }
  15687. state.directionalShadowMap[ directionalLength ] = shadowMap;
  15688. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  15689. state.directional[ directionalLength ] = uniforms;
  15690. directionalLength ++;
  15691. } else if ( light.isSpotLight ) {
  15692. var uniforms = cache.get( light );
  15693. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15694. uniforms.position.applyMatrix4( viewMatrix );
  15695. uniforms.color.copy( color ).multiplyScalar( intensity );
  15696. uniforms.distance = distance;
  15697. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15698. vector3.setFromMatrixPosition( light.target.matrixWorld );
  15699. uniforms.direction.sub( vector3 );
  15700. uniforms.direction.transformDirection( viewMatrix );
  15701. uniforms.coneCos = Math.cos( light.angle );
  15702. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  15703. uniforms.decay = light.decay;
  15704. uniforms.shadow = light.castShadow;
  15705. if ( light.castShadow ) {
  15706. var shadow = light.shadow;
  15707. uniforms.shadowBias = shadow.bias;
  15708. uniforms.shadowRadius = shadow.radius;
  15709. uniforms.shadowMapSize = shadow.mapSize;
  15710. }
  15711. state.spotShadowMap[ spotLength ] = shadowMap;
  15712. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  15713. state.spot[ spotLength ] = uniforms;
  15714. spotLength ++;
  15715. } else if ( light.isRectAreaLight ) {
  15716. var uniforms = cache.get( light );
  15717. // (a) intensity is the total visible light emitted
  15718. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  15719. // (b) intensity is the brightness of the light
  15720. uniforms.color.copy( color ).multiplyScalar( intensity );
  15721. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15722. uniforms.position.applyMatrix4( viewMatrix );
  15723. // extract local rotation of light to derive width/height half vectors
  15724. matrix42.identity();
  15725. matrix4.copy( light.matrixWorld );
  15726. matrix4.premultiply( viewMatrix );
  15727. matrix42.extractRotation( matrix4 );
  15728. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  15729. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  15730. uniforms.halfWidth.applyMatrix4( matrix42 );
  15731. uniforms.halfHeight.applyMatrix4( matrix42 );
  15732. // TODO (abelnation): RectAreaLight distance?
  15733. // uniforms.distance = distance;
  15734. state.rectArea[ rectAreaLength ] = uniforms;
  15735. rectAreaLength ++;
  15736. } else if ( light.isPointLight ) {
  15737. var uniforms = cache.get( light );
  15738. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15739. uniforms.position.applyMatrix4( viewMatrix );
  15740. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15741. uniforms.distance = light.distance;
  15742. uniforms.decay = light.decay;
  15743. uniforms.shadow = light.castShadow;
  15744. if ( light.castShadow ) {
  15745. var shadow = light.shadow;
  15746. uniforms.shadowBias = shadow.bias;
  15747. uniforms.shadowRadius = shadow.radius;
  15748. uniforms.shadowMapSize = shadow.mapSize;
  15749. uniforms.shadowCameraNear = shadow.camera.near;
  15750. uniforms.shadowCameraFar = shadow.camera.far;
  15751. }
  15752. state.pointShadowMap[ pointLength ] = shadowMap;
  15753. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  15754. state.point[ pointLength ] = uniforms;
  15755. pointLength ++;
  15756. } else if ( light.isHemisphereLight ) {
  15757. var uniforms = cache.get( light );
  15758. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15759. uniforms.direction.transformDirection( viewMatrix );
  15760. uniforms.direction.normalize();
  15761. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  15762. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  15763. state.hemi[ hemiLength ] = uniforms;
  15764. hemiLength ++;
  15765. }
  15766. }
  15767. state.ambient[ 0 ] = r;
  15768. state.ambient[ 1 ] = g;
  15769. state.ambient[ 2 ] = b;
  15770. state.directional.length = directionalLength;
  15771. state.spot.length = spotLength;
  15772. state.rectArea.length = rectAreaLength;
  15773. state.point.length = pointLength;
  15774. state.hemi.length = hemiLength;
  15775. state.hash.stateID = state.id;
  15776. state.hash.directionalLength = directionalLength;
  15777. state.hash.pointLength = pointLength;
  15778. state.hash.spotLength = spotLength;
  15779. state.hash.rectAreaLength = rectAreaLength;
  15780. state.hash.hemiLength = hemiLength;
  15781. state.hash.shadowsLength = shadows.length;
  15782. }
  15783. return {
  15784. setup: setup,
  15785. state: state
  15786. };
  15787. }
  15788. /**
  15789. * @author Mugen87 / https://github.com/Mugen87
  15790. */
  15791. function WebGLRenderState() {
  15792. var lights = new WebGLLights();
  15793. var lightsArray = [];
  15794. var shadowsArray = [];
  15795. function init() {
  15796. lightsArray.length = 0;
  15797. shadowsArray.length = 0;
  15798. }
  15799. function pushLight( light ) {
  15800. lightsArray.push( light );
  15801. }
  15802. function pushShadow( shadowLight ) {
  15803. shadowsArray.push( shadowLight );
  15804. }
  15805. function setupLights( camera ) {
  15806. lights.setup( lightsArray, shadowsArray, camera );
  15807. }
  15808. var state = {
  15809. lightsArray: lightsArray,
  15810. shadowsArray: shadowsArray,
  15811. lights: lights
  15812. };
  15813. return {
  15814. init: init,
  15815. state: state,
  15816. setupLights: setupLights,
  15817. pushLight: pushLight,
  15818. pushShadow: pushShadow
  15819. };
  15820. }
  15821. function WebGLRenderStates() {
  15822. var renderStates = {};
  15823. function onSceneDispose( event ) {
  15824. var scene = event.target;
  15825. scene.removeEventListener( 'dispose', onSceneDispose );
  15826. delete renderStates[ scene.id ];
  15827. }
  15828. function get( scene, camera ) {
  15829. var renderState;
  15830. if ( renderStates[ scene.id ] === undefined ) {
  15831. renderState = new WebGLRenderState();
  15832. renderStates[ scene.id ] = {};
  15833. renderStates[ scene.id ][ camera.id ] = renderState;
  15834. scene.addEventListener( 'dispose', onSceneDispose );
  15835. } else {
  15836. if ( renderStates[ scene.id ][ camera.id ] === undefined ) {
  15837. renderState = new WebGLRenderState();
  15838. renderStates[ scene.id ][ camera.id ] = renderState;
  15839. } else {
  15840. renderState = renderStates[ scene.id ][ camera.id ];
  15841. }
  15842. }
  15843. return renderState;
  15844. }
  15845. function dispose() {
  15846. renderStates = {};
  15847. }
  15848. return {
  15849. get: get,
  15850. dispose: dispose
  15851. };
  15852. }
  15853. /**
  15854. * @author mrdoob / http://mrdoob.com/
  15855. * @author alteredq / http://alteredqualia.com/
  15856. * @author bhouston / https://clara.io
  15857. * @author WestLangley / http://github.com/WestLangley
  15858. *
  15859. * parameters = {
  15860. *
  15861. * opacity: <float>,
  15862. *
  15863. * map: new THREE.Texture( <Image> ),
  15864. *
  15865. * alphaMap: new THREE.Texture( <Image> ),
  15866. *
  15867. * displacementMap: new THREE.Texture( <Image> ),
  15868. * displacementScale: <float>,
  15869. * displacementBias: <float>,
  15870. *
  15871. * wireframe: <boolean>,
  15872. * wireframeLinewidth: <float>
  15873. * }
  15874. */
  15875. function MeshDepthMaterial( parameters ) {
  15876. Material.call( this );
  15877. this.type = 'MeshDepthMaterial';
  15878. this.depthPacking = BasicDepthPacking;
  15879. this.skinning = false;
  15880. this.morphTargets = false;
  15881. this.map = null;
  15882. this.alphaMap = null;
  15883. this.displacementMap = null;
  15884. this.displacementScale = 1;
  15885. this.displacementBias = 0;
  15886. this.wireframe = false;
  15887. this.wireframeLinewidth = 1;
  15888. this.fog = false;
  15889. this.lights = false;
  15890. this.setValues( parameters );
  15891. }
  15892. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  15893. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  15894. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  15895. MeshDepthMaterial.prototype.copy = function ( source ) {
  15896. Material.prototype.copy.call( this, source );
  15897. this.depthPacking = source.depthPacking;
  15898. this.skinning = source.skinning;
  15899. this.morphTargets = source.morphTargets;
  15900. this.map = source.map;
  15901. this.alphaMap = source.alphaMap;
  15902. this.displacementMap = source.displacementMap;
  15903. this.displacementScale = source.displacementScale;
  15904. this.displacementBias = source.displacementBias;
  15905. this.wireframe = source.wireframe;
  15906. this.wireframeLinewidth = source.wireframeLinewidth;
  15907. return this;
  15908. };
  15909. /**
  15910. * @author WestLangley / http://github.com/WestLangley
  15911. *
  15912. * parameters = {
  15913. *
  15914. * referencePosition: <float>,
  15915. * nearDistance: <float>,
  15916. * farDistance: <float>,
  15917. *
  15918. * skinning: <bool>,
  15919. * morphTargets: <bool>,
  15920. *
  15921. * map: new THREE.Texture( <Image> ),
  15922. *
  15923. * alphaMap: new THREE.Texture( <Image> ),
  15924. *
  15925. * displacementMap: new THREE.Texture( <Image> ),
  15926. * displacementScale: <float>,
  15927. * displacementBias: <float>
  15928. *
  15929. * }
  15930. */
  15931. function MeshDistanceMaterial( parameters ) {
  15932. Material.call( this );
  15933. this.type = 'MeshDistanceMaterial';
  15934. this.referencePosition = new Vector3();
  15935. this.nearDistance = 1;
  15936. this.farDistance = 1000;
  15937. this.skinning = false;
  15938. this.morphTargets = false;
  15939. this.map = null;
  15940. this.alphaMap = null;
  15941. this.displacementMap = null;
  15942. this.displacementScale = 1;
  15943. this.displacementBias = 0;
  15944. this.fog = false;
  15945. this.lights = false;
  15946. this.setValues( parameters );
  15947. }
  15948. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  15949. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  15950. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  15951. MeshDistanceMaterial.prototype.copy = function ( source ) {
  15952. Material.prototype.copy.call( this, source );
  15953. this.referencePosition.copy( source.referencePosition );
  15954. this.nearDistance = source.nearDistance;
  15955. this.farDistance = source.farDistance;
  15956. this.skinning = source.skinning;
  15957. this.morphTargets = source.morphTargets;
  15958. this.map = source.map;
  15959. this.alphaMap = source.alphaMap;
  15960. this.displacementMap = source.displacementMap;
  15961. this.displacementScale = source.displacementScale;
  15962. this.displacementBias = source.displacementBias;
  15963. return this;
  15964. };
  15965. /**
  15966. * @author alteredq / http://alteredqualia.com/
  15967. * @author mrdoob / http://mrdoob.com/
  15968. */
  15969. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  15970. var _frustum = new Frustum(),
  15971. _projScreenMatrix = new Matrix4(),
  15972. _shadowMapSize = new Vector2(),
  15973. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  15974. _lookTarget = new Vector3(),
  15975. _lightPositionWorld = new Vector3(),
  15976. _MorphingFlag = 1,
  15977. _SkinningFlag = 2,
  15978. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  15979. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  15980. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  15981. _materialCache = {};
  15982. var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  15983. var cubeDirections = [
  15984. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  15985. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  15986. ];
  15987. var cubeUps = [
  15988. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  15989. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  15990. ];
  15991. var cube2DViewPorts = [
  15992. new Vector4(), new Vector4(), new Vector4(),
  15993. new Vector4(), new Vector4(), new Vector4()
  15994. ];
  15995. // init
  15996. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  15997. var useMorphing = ( i & _MorphingFlag ) !== 0;
  15998. var useSkinning = ( i & _SkinningFlag ) !== 0;
  15999. var depthMaterial = new MeshDepthMaterial( {
  16000. depthPacking: RGBADepthPacking,
  16001. morphTargets: useMorphing,
  16002. skinning: useSkinning
  16003. } );
  16004. _depthMaterials[ i ] = depthMaterial;
  16005. //
  16006. var distanceMaterial = new MeshDistanceMaterial( {
  16007. morphTargets: useMorphing,
  16008. skinning: useSkinning
  16009. } );
  16010. _distanceMaterials[ i ] = distanceMaterial;
  16011. }
  16012. //
  16013. var scope = this;
  16014. this.enabled = false;
  16015. this.autoUpdate = true;
  16016. this.needsUpdate = false;
  16017. this.type = PCFShadowMap;
  16018. this.render = function ( lights, scene, camera ) {
  16019. if ( scope.enabled === false ) return;
  16020. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  16021. if ( lights.length === 0 ) return;
  16022. var currentRenderTarget = _renderer.getRenderTarget();
  16023. var _state = _renderer.state;
  16024. // Set GL state for depth map.
  16025. _state.setBlending( NoBlending );
  16026. _state.buffers.color.setClear( 1, 1, 1, 1 );
  16027. _state.buffers.depth.setTest( true );
  16028. _state.setScissorTest( false );
  16029. // render depth map
  16030. var faceCount;
  16031. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  16032. var light = lights[ i ];
  16033. var shadow = light.shadow;
  16034. var isPointLight = light && light.isPointLight;
  16035. if ( shadow === undefined ) {
  16036. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  16037. continue;
  16038. }
  16039. var shadowCamera = shadow.camera;
  16040. _shadowMapSize.copy( shadow.mapSize );
  16041. _shadowMapSize.min( _maxShadowMapSize );
  16042. if ( isPointLight ) {
  16043. var vpWidth = _shadowMapSize.x;
  16044. var vpHeight = _shadowMapSize.y;
  16045. // These viewports map a cube-map onto a 2D texture with the
  16046. // following orientation:
  16047. //
  16048. // xzXZ
  16049. // y Y
  16050. //
  16051. // X - Positive x direction
  16052. // x - Negative x direction
  16053. // Y - Positive y direction
  16054. // y - Negative y direction
  16055. // Z - Positive z direction
  16056. // z - Negative z direction
  16057. // positive X
  16058. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  16059. // negative X
  16060. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  16061. // positive Z
  16062. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  16063. // negative Z
  16064. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  16065. // positive Y
  16066. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  16067. // negative Y
  16068. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  16069. _shadowMapSize.x *= 4.0;
  16070. _shadowMapSize.y *= 2.0;
  16071. }
  16072. if ( shadow.map === null ) {
  16073. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  16074. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  16075. shadow.map.texture.name = light.name + ".shadowMap";
  16076. shadowCamera.updateProjectionMatrix();
  16077. }
  16078. if ( shadow.isSpotLightShadow ) {
  16079. shadow.update( light );
  16080. }
  16081. var shadowMap = shadow.map;
  16082. var shadowMatrix = shadow.matrix;
  16083. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16084. shadowCamera.position.copy( _lightPositionWorld );
  16085. if ( isPointLight ) {
  16086. faceCount = 6;
  16087. // for point lights we set the shadow matrix to be a translation-only matrix
  16088. // equal to inverse of the light's position
  16089. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16090. } else {
  16091. faceCount = 1;
  16092. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  16093. shadowCamera.lookAt( _lookTarget );
  16094. shadowCamera.updateMatrixWorld();
  16095. // compute shadow matrix
  16096. shadowMatrix.set(
  16097. 0.5, 0.0, 0.0, 0.5,
  16098. 0.0, 0.5, 0.0, 0.5,
  16099. 0.0, 0.0, 0.5, 0.5,
  16100. 0.0, 0.0, 0.0, 1.0
  16101. );
  16102. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  16103. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  16104. }
  16105. _renderer.setRenderTarget( shadowMap );
  16106. _renderer.clear();
  16107. // render shadow map for each cube face (if omni-directional) or
  16108. // run a single pass if not
  16109. for ( var face = 0; face < faceCount; face ++ ) {
  16110. if ( isPointLight ) {
  16111. _lookTarget.copy( shadowCamera.position );
  16112. _lookTarget.add( cubeDirections[ face ] );
  16113. shadowCamera.up.copy( cubeUps[ face ] );
  16114. shadowCamera.lookAt( _lookTarget );
  16115. shadowCamera.updateMatrixWorld();
  16116. var vpDimensions = cube2DViewPorts[ face ];
  16117. _state.viewport( vpDimensions );
  16118. }
  16119. // update camera matrices and frustum
  16120. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16121. _frustum.setFromMatrix( _projScreenMatrix );
  16122. // set object matrices & frustum culling
  16123. renderObject( scene, camera, shadowCamera, isPointLight );
  16124. }
  16125. }
  16126. scope.needsUpdate = false;
  16127. _renderer.setRenderTarget( currentRenderTarget );
  16128. };
  16129. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  16130. var geometry = object.geometry;
  16131. var result = null;
  16132. var materialVariants = _depthMaterials;
  16133. var customMaterial = object.customDepthMaterial;
  16134. if ( isPointLight ) {
  16135. materialVariants = _distanceMaterials;
  16136. customMaterial = object.customDistanceMaterial;
  16137. }
  16138. if ( ! customMaterial ) {
  16139. var useMorphing = false;
  16140. if ( material.morphTargets ) {
  16141. if ( geometry && geometry.isBufferGeometry ) {
  16142. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  16143. } else if ( geometry && geometry.isGeometry ) {
  16144. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  16145. }
  16146. }
  16147. if ( object.isSkinnedMesh && material.skinning === false ) {
  16148. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  16149. }
  16150. var useSkinning = object.isSkinnedMesh && material.skinning;
  16151. var variantIndex = 0;
  16152. if ( useMorphing ) variantIndex |= _MorphingFlag;
  16153. if ( useSkinning ) variantIndex |= _SkinningFlag;
  16154. result = materialVariants[ variantIndex ];
  16155. } else {
  16156. result = customMaterial;
  16157. }
  16158. if ( _renderer.localClippingEnabled &&
  16159. material.clipShadows === true &&
  16160. material.clippingPlanes.length !== 0 ) {
  16161. // in this case we need a unique material instance reflecting the
  16162. // appropriate state
  16163. var keyA = result.uuid, keyB = material.uuid;
  16164. var materialsForVariant = _materialCache[ keyA ];
  16165. if ( materialsForVariant === undefined ) {
  16166. materialsForVariant = {};
  16167. _materialCache[ keyA ] = materialsForVariant;
  16168. }
  16169. var cachedMaterial = materialsForVariant[ keyB ];
  16170. if ( cachedMaterial === undefined ) {
  16171. cachedMaterial = result.clone();
  16172. materialsForVariant[ keyB ] = cachedMaterial;
  16173. }
  16174. result = cachedMaterial;
  16175. }
  16176. result.visible = material.visible;
  16177. result.wireframe = material.wireframe;
  16178. result.side = ( material.shadowSide != null ) ? material.shadowSide : shadowSide[ material.side ];
  16179. result.clipShadows = material.clipShadows;
  16180. result.clippingPlanes = material.clippingPlanes;
  16181. result.clipIntersection = material.clipIntersection;
  16182. result.wireframeLinewidth = material.wireframeLinewidth;
  16183. result.linewidth = material.linewidth;
  16184. if ( isPointLight && result.isMeshDistanceMaterial ) {
  16185. result.referencePosition.copy( lightPositionWorld );
  16186. result.nearDistance = shadowCameraNear;
  16187. result.farDistance = shadowCameraFar;
  16188. }
  16189. return result;
  16190. }
  16191. function renderObject( object, camera, shadowCamera, isPointLight ) {
  16192. if ( object.visible === false ) return;
  16193. var visible = object.layers.test( camera.layers );
  16194. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  16195. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  16196. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  16197. var geometry = _objects.update( object );
  16198. var material = object.material;
  16199. if ( Array.isArray( material ) ) {
  16200. var groups = geometry.groups;
  16201. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  16202. var group = groups[ k ];
  16203. var groupMaterial = material[ group.materialIndex ];
  16204. if ( groupMaterial && groupMaterial.visible ) {
  16205. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  16206. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  16207. }
  16208. }
  16209. } else if ( material.visible ) {
  16210. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  16211. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  16212. }
  16213. }
  16214. }
  16215. var children = object.children;
  16216. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16217. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  16218. }
  16219. }
  16220. }
  16221. /**
  16222. * @author mrdoob / http://mrdoob.com/
  16223. */
  16224. function WebGLState( gl, extensions, utils, capabilities ) {
  16225. function ColorBuffer() {
  16226. var locked = false;
  16227. var color = new Vector4();
  16228. var currentColorMask = null;
  16229. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  16230. return {
  16231. setMask: function ( colorMask ) {
  16232. if ( currentColorMask !== colorMask && ! locked ) {
  16233. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  16234. currentColorMask = colorMask;
  16235. }
  16236. },
  16237. setLocked: function ( lock ) {
  16238. locked = lock;
  16239. },
  16240. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  16241. if ( premultipliedAlpha === true ) {
  16242. r *= a; g *= a; b *= a;
  16243. }
  16244. color.set( r, g, b, a );
  16245. if ( currentColorClear.equals( color ) === false ) {
  16246. gl.clearColor( r, g, b, a );
  16247. currentColorClear.copy( color );
  16248. }
  16249. },
  16250. reset: function () {
  16251. locked = false;
  16252. currentColorMask = null;
  16253. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  16254. }
  16255. };
  16256. }
  16257. function DepthBuffer() {
  16258. var locked = false;
  16259. var currentDepthMask = null;
  16260. var currentDepthFunc = null;
  16261. var currentDepthClear = null;
  16262. return {
  16263. setTest: function ( depthTest ) {
  16264. if ( depthTest ) {
  16265. enable( 2929 );
  16266. } else {
  16267. disable( 2929 );
  16268. }
  16269. },
  16270. setMask: function ( depthMask ) {
  16271. if ( currentDepthMask !== depthMask && ! locked ) {
  16272. gl.depthMask( depthMask );
  16273. currentDepthMask = depthMask;
  16274. }
  16275. },
  16276. setFunc: function ( depthFunc ) {
  16277. if ( currentDepthFunc !== depthFunc ) {
  16278. if ( depthFunc ) {
  16279. switch ( depthFunc ) {
  16280. case NeverDepth:
  16281. gl.depthFunc( 512 );
  16282. break;
  16283. case AlwaysDepth:
  16284. gl.depthFunc( 519 );
  16285. break;
  16286. case LessDepth:
  16287. gl.depthFunc( 513 );
  16288. break;
  16289. case LessEqualDepth:
  16290. gl.depthFunc( 515 );
  16291. break;
  16292. case EqualDepth:
  16293. gl.depthFunc( 514 );
  16294. break;
  16295. case GreaterEqualDepth:
  16296. gl.depthFunc( 518 );
  16297. break;
  16298. case GreaterDepth:
  16299. gl.depthFunc( 516 );
  16300. break;
  16301. case NotEqualDepth:
  16302. gl.depthFunc( 517 );
  16303. break;
  16304. default:
  16305. gl.depthFunc( 515 );
  16306. }
  16307. } else {
  16308. gl.depthFunc( 515 );
  16309. }
  16310. currentDepthFunc = depthFunc;
  16311. }
  16312. },
  16313. setLocked: function ( lock ) {
  16314. locked = lock;
  16315. },
  16316. setClear: function ( depth ) {
  16317. if ( currentDepthClear !== depth ) {
  16318. gl.clearDepth( depth );
  16319. currentDepthClear = depth;
  16320. }
  16321. },
  16322. reset: function () {
  16323. locked = false;
  16324. currentDepthMask = null;
  16325. currentDepthFunc = null;
  16326. currentDepthClear = null;
  16327. }
  16328. };
  16329. }
  16330. function StencilBuffer() {
  16331. var locked = false;
  16332. var currentStencilMask = null;
  16333. var currentStencilFunc = null;
  16334. var currentStencilRef = null;
  16335. var currentStencilFuncMask = null;
  16336. var currentStencilFail = null;
  16337. var currentStencilZFail = null;
  16338. var currentStencilZPass = null;
  16339. var currentStencilClear = null;
  16340. return {
  16341. setTest: function ( stencilTest ) {
  16342. if ( stencilTest ) {
  16343. enable( 2960 );
  16344. } else {
  16345. disable( 2960 );
  16346. }
  16347. },
  16348. setMask: function ( stencilMask ) {
  16349. if ( currentStencilMask !== stencilMask && ! locked ) {
  16350. gl.stencilMask( stencilMask );
  16351. currentStencilMask = stencilMask;
  16352. }
  16353. },
  16354. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  16355. if ( currentStencilFunc !== stencilFunc ||
  16356. currentStencilRef !== stencilRef ||
  16357. currentStencilFuncMask !== stencilMask ) {
  16358. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  16359. currentStencilFunc = stencilFunc;
  16360. currentStencilRef = stencilRef;
  16361. currentStencilFuncMask = stencilMask;
  16362. }
  16363. },
  16364. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  16365. if ( currentStencilFail !== stencilFail ||
  16366. currentStencilZFail !== stencilZFail ||
  16367. currentStencilZPass !== stencilZPass ) {
  16368. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  16369. currentStencilFail = stencilFail;
  16370. currentStencilZFail = stencilZFail;
  16371. currentStencilZPass = stencilZPass;
  16372. }
  16373. },
  16374. setLocked: function ( lock ) {
  16375. locked = lock;
  16376. },
  16377. setClear: function ( stencil ) {
  16378. if ( currentStencilClear !== stencil ) {
  16379. gl.clearStencil( stencil );
  16380. currentStencilClear = stencil;
  16381. }
  16382. },
  16383. reset: function () {
  16384. locked = false;
  16385. currentStencilMask = null;
  16386. currentStencilFunc = null;
  16387. currentStencilRef = null;
  16388. currentStencilFuncMask = null;
  16389. currentStencilFail = null;
  16390. currentStencilZFail = null;
  16391. currentStencilZPass = null;
  16392. currentStencilClear = null;
  16393. }
  16394. };
  16395. }
  16396. //
  16397. var colorBuffer = new ColorBuffer();
  16398. var depthBuffer = new DepthBuffer();
  16399. var stencilBuffer = new StencilBuffer();
  16400. var maxVertexAttributes = gl.getParameter( 34921 );
  16401. var newAttributes = new Uint8Array( maxVertexAttributes );
  16402. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  16403. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  16404. var enabledCapabilities = {};
  16405. var compressedTextureFormats = null;
  16406. var currentProgram = null;
  16407. var currentBlendingEnabled = null;
  16408. var currentBlending = null;
  16409. var currentBlendEquation = null;
  16410. var currentBlendSrc = null;
  16411. var currentBlendDst = null;
  16412. var currentBlendEquationAlpha = null;
  16413. var currentBlendSrcAlpha = null;
  16414. var currentBlendDstAlpha = null;
  16415. var currentPremultipledAlpha = false;
  16416. var currentFlipSided = null;
  16417. var currentCullFace = null;
  16418. var currentLineWidth = null;
  16419. var currentPolygonOffsetFactor = null;
  16420. var currentPolygonOffsetUnits = null;
  16421. var maxTextures = gl.getParameter( 35661 );
  16422. var lineWidthAvailable = false;
  16423. var version = 0;
  16424. var glVersion = gl.getParameter( 7938 );
  16425. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  16426. version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
  16427. lineWidthAvailable = ( version >= 1.0 );
  16428. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  16429. version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
  16430. lineWidthAvailable = ( version >= 2.0 );
  16431. }
  16432. var currentTextureSlot = null;
  16433. var currentBoundTextures = {};
  16434. var currentScissor = new Vector4();
  16435. var currentViewport = new Vector4();
  16436. function createTexture( type, target, count ) {
  16437. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  16438. var texture = gl.createTexture();
  16439. gl.bindTexture( type, texture );
  16440. gl.texParameteri( type, 10241, 9728 );
  16441. gl.texParameteri( type, 10240, 9728 );
  16442. for ( var i = 0; i < count; i ++ ) {
  16443. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  16444. }
  16445. return texture;
  16446. }
  16447. var emptyTextures = {};
  16448. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  16449. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  16450. // init
  16451. colorBuffer.setClear( 0, 0, 0, 1 );
  16452. depthBuffer.setClear( 1 );
  16453. stencilBuffer.setClear( 0 );
  16454. enable( 2929 );
  16455. depthBuffer.setFunc( LessEqualDepth );
  16456. setFlipSided( false );
  16457. setCullFace( CullFaceBack );
  16458. enable( 2884 );
  16459. setBlending( NoBlending );
  16460. //
  16461. function initAttributes() {
  16462. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  16463. newAttributes[ i ] = 0;
  16464. }
  16465. }
  16466. function enableAttribute( attribute ) {
  16467. enableAttributeAndDivisor( attribute, 0 );
  16468. }
  16469. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  16470. newAttributes[ attribute ] = 1;
  16471. if ( enabledAttributes[ attribute ] === 0 ) {
  16472. gl.enableVertexAttribArray( attribute );
  16473. enabledAttributes[ attribute ] = 1;
  16474. }
  16475. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  16476. var extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  16477. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  16478. attributeDivisors[ attribute ] = meshPerAttribute;
  16479. }
  16480. }
  16481. function disableUnusedAttributes() {
  16482. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  16483. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  16484. gl.disableVertexAttribArray( i );
  16485. enabledAttributes[ i ] = 0;
  16486. }
  16487. }
  16488. }
  16489. function enable( id ) {
  16490. if ( enabledCapabilities[ id ] !== true ) {
  16491. gl.enable( id );
  16492. enabledCapabilities[ id ] = true;
  16493. }
  16494. }
  16495. function disable( id ) {
  16496. if ( enabledCapabilities[ id ] !== false ) {
  16497. gl.disable( id );
  16498. enabledCapabilities[ id ] = false;
  16499. }
  16500. }
  16501. function getCompressedTextureFormats() {
  16502. if ( compressedTextureFormats === null ) {
  16503. compressedTextureFormats = [];
  16504. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  16505. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  16506. extensions.get( 'WEBGL_compressed_texture_etc1' ) ||
  16507. extensions.get( 'WEBGL_compressed_texture_astc' ) ) {
  16508. var formats = gl.getParameter( 34467 );
  16509. for ( var i = 0; i < formats.length; i ++ ) {
  16510. compressedTextureFormats.push( formats[ i ] );
  16511. }
  16512. }
  16513. }
  16514. return compressedTextureFormats;
  16515. }
  16516. function useProgram( program ) {
  16517. if ( currentProgram !== program ) {
  16518. gl.useProgram( program );
  16519. currentProgram = program;
  16520. return true;
  16521. }
  16522. return false;
  16523. }
  16524. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  16525. if ( blending === NoBlending ) {
  16526. if ( currentBlendingEnabled ) {
  16527. disable( 3042 );
  16528. currentBlendingEnabled = false;
  16529. }
  16530. return;
  16531. }
  16532. if ( ! currentBlendingEnabled ) {
  16533. enable( 3042 );
  16534. currentBlendingEnabled = true;
  16535. }
  16536. if ( blending !== CustomBlending ) {
  16537. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  16538. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  16539. gl.blendEquation( 32774 );
  16540. currentBlendEquation = AddEquation;
  16541. currentBlendEquationAlpha = AddEquation;
  16542. }
  16543. if ( premultipliedAlpha ) {
  16544. switch ( blending ) {
  16545. case NormalBlending:
  16546. gl.blendFuncSeparate( 1, 771, 1, 771 );
  16547. break;
  16548. case AdditiveBlending:
  16549. gl.blendFunc( 1, 1 );
  16550. break;
  16551. case SubtractiveBlending:
  16552. gl.blendFuncSeparate( 0, 0, 769, 771 );
  16553. break;
  16554. case MultiplyBlending:
  16555. gl.blendFuncSeparate( 0, 768, 0, 770 );
  16556. break;
  16557. default:
  16558. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  16559. break;
  16560. }
  16561. } else {
  16562. switch ( blending ) {
  16563. case NormalBlending:
  16564. gl.blendFuncSeparate( 770, 771, 1, 771 );
  16565. break;
  16566. case AdditiveBlending:
  16567. gl.blendFunc( 770, 1 );
  16568. break;
  16569. case SubtractiveBlending:
  16570. gl.blendFunc( 0, 769 );
  16571. break;
  16572. case MultiplyBlending:
  16573. gl.blendFunc( 0, 768 );
  16574. break;
  16575. default:
  16576. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  16577. break;
  16578. }
  16579. }
  16580. currentBlendSrc = null;
  16581. currentBlendDst = null;
  16582. currentBlendSrcAlpha = null;
  16583. currentBlendDstAlpha = null;
  16584. currentBlending = blending;
  16585. currentPremultipledAlpha = premultipliedAlpha;
  16586. }
  16587. return;
  16588. }
  16589. // custom blending
  16590. blendEquationAlpha = blendEquationAlpha || blendEquation;
  16591. blendSrcAlpha = blendSrcAlpha || blendSrc;
  16592. blendDstAlpha = blendDstAlpha || blendDst;
  16593. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  16594. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  16595. currentBlendEquation = blendEquation;
  16596. currentBlendEquationAlpha = blendEquationAlpha;
  16597. }
  16598. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  16599. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  16600. currentBlendSrc = blendSrc;
  16601. currentBlendDst = blendDst;
  16602. currentBlendSrcAlpha = blendSrcAlpha;
  16603. currentBlendDstAlpha = blendDstAlpha;
  16604. }
  16605. currentBlending = blending;
  16606. currentPremultipledAlpha = null;
  16607. }
  16608. function setMaterial( material, frontFaceCW ) {
  16609. material.side === DoubleSide
  16610. ? disable( 2884 )
  16611. : enable( 2884 );
  16612. var flipSided = ( material.side === BackSide );
  16613. if ( frontFaceCW ) flipSided = ! flipSided;
  16614. setFlipSided( flipSided );
  16615. ( material.blending === NormalBlending && material.transparent === false )
  16616. ? setBlending( NoBlending )
  16617. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  16618. depthBuffer.setFunc( material.depthFunc );
  16619. depthBuffer.setTest( material.depthTest );
  16620. depthBuffer.setMask( material.depthWrite );
  16621. colorBuffer.setMask( material.colorWrite );
  16622. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16623. }
  16624. //
  16625. function setFlipSided( flipSided ) {
  16626. if ( currentFlipSided !== flipSided ) {
  16627. if ( flipSided ) {
  16628. gl.frontFace( 2304 );
  16629. } else {
  16630. gl.frontFace( 2305 );
  16631. }
  16632. currentFlipSided = flipSided;
  16633. }
  16634. }
  16635. function setCullFace( cullFace ) {
  16636. if ( cullFace !== CullFaceNone ) {
  16637. enable( 2884 );
  16638. if ( cullFace !== currentCullFace ) {
  16639. if ( cullFace === CullFaceBack ) {
  16640. gl.cullFace( 1029 );
  16641. } else if ( cullFace === CullFaceFront ) {
  16642. gl.cullFace( 1028 );
  16643. } else {
  16644. gl.cullFace( 1032 );
  16645. }
  16646. }
  16647. } else {
  16648. disable( 2884 );
  16649. }
  16650. currentCullFace = cullFace;
  16651. }
  16652. function setLineWidth( width ) {
  16653. if ( width !== currentLineWidth ) {
  16654. if ( lineWidthAvailable ) gl.lineWidth( width );
  16655. currentLineWidth = width;
  16656. }
  16657. }
  16658. function setPolygonOffset( polygonOffset, factor, units ) {
  16659. if ( polygonOffset ) {
  16660. enable( 32823 );
  16661. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  16662. gl.polygonOffset( factor, units );
  16663. currentPolygonOffsetFactor = factor;
  16664. currentPolygonOffsetUnits = units;
  16665. }
  16666. } else {
  16667. disable( 32823 );
  16668. }
  16669. }
  16670. function setScissorTest( scissorTest ) {
  16671. if ( scissorTest ) {
  16672. enable( 3089 );
  16673. } else {
  16674. disable( 3089 );
  16675. }
  16676. }
  16677. // texture
  16678. function activeTexture( webglSlot ) {
  16679. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  16680. if ( currentTextureSlot !== webglSlot ) {
  16681. gl.activeTexture( webglSlot );
  16682. currentTextureSlot = webglSlot;
  16683. }
  16684. }
  16685. function bindTexture( webglType, webglTexture ) {
  16686. if ( currentTextureSlot === null ) {
  16687. activeTexture();
  16688. }
  16689. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16690. if ( boundTexture === undefined ) {
  16691. boundTexture = { type: undefined, texture: undefined };
  16692. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16693. }
  16694. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16695. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  16696. boundTexture.type = webglType;
  16697. boundTexture.texture = webglTexture;
  16698. }
  16699. }
  16700. function compressedTexImage2D() {
  16701. try {
  16702. gl.compressedTexImage2D.apply( gl, arguments );
  16703. } catch ( error ) {
  16704. console.error( 'THREE.WebGLState:', error );
  16705. }
  16706. }
  16707. function texImage2D() {
  16708. try {
  16709. gl.texImage2D.apply( gl, arguments );
  16710. } catch ( error ) {
  16711. console.error( 'THREE.WebGLState:', error );
  16712. }
  16713. }
  16714. function texImage3D() {
  16715. try {
  16716. gl.texImage3D.apply( gl, arguments );
  16717. } catch ( error ) {
  16718. console.error( 'THREE.WebGLState:', error );
  16719. }
  16720. }
  16721. //
  16722. function scissor( scissor ) {
  16723. if ( currentScissor.equals( scissor ) === false ) {
  16724. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  16725. currentScissor.copy( scissor );
  16726. }
  16727. }
  16728. function viewport( viewport ) {
  16729. if ( currentViewport.equals( viewport ) === false ) {
  16730. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  16731. currentViewport.copy( viewport );
  16732. }
  16733. }
  16734. //
  16735. function reset() {
  16736. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16737. if ( enabledAttributes[ i ] === 1 ) {
  16738. gl.disableVertexAttribArray( i );
  16739. enabledAttributes[ i ] = 0;
  16740. }
  16741. }
  16742. enabledCapabilities = {};
  16743. compressedTextureFormats = null;
  16744. currentTextureSlot = null;
  16745. currentBoundTextures = {};
  16746. currentProgram = null;
  16747. currentBlending = null;
  16748. currentFlipSided = null;
  16749. currentCullFace = null;
  16750. colorBuffer.reset();
  16751. depthBuffer.reset();
  16752. stencilBuffer.reset();
  16753. }
  16754. return {
  16755. buffers: {
  16756. color: colorBuffer,
  16757. depth: depthBuffer,
  16758. stencil: stencilBuffer
  16759. },
  16760. initAttributes: initAttributes,
  16761. enableAttribute: enableAttribute,
  16762. enableAttributeAndDivisor: enableAttributeAndDivisor,
  16763. disableUnusedAttributes: disableUnusedAttributes,
  16764. enable: enable,
  16765. disable: disable,
  16766. getCompressedTextureFormats: getCompressedTextureFormats,
  16767. useProgram: useProgram,
  16768. setBlending: setBlending,
  16769. setMaterial: setMaterial,
  16770. setFlipSided: setFlipSided,
  16771. setCullFace: setCullFace,
  16772. setLineWidth: setLineWidth,
  16773. setPolygonOffset: setPolygonOffset,
  16774. setScissorTest: setScissorTest,
  16775. activeTexture: activeTexture,
  16776. bindTexture: bindTexture,
  16777. compressedTexImage2D: compressedTexImage2D,
  16778. texImage2D: texImage2D,
  16779. texImage3D: texImage3D,
  16780. scissor: scissor,
  16781. viewport: viewport,
  16782. reset: reset
  16783. };
  16784. }
  16785. /**
  16786. * @author mrdoob / http://mrdoob.com/
  16787. */
  16788. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  16789. var _videoTextures = {};
  16790. var _canvas;
  16791. //
  16792. var useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined';
  16793. function createCanvas( width, height ) {
  16794. // Use OffscreenCanvas when available. Specially needed in web workers
  16795. return useOffscreenCanvas ?
  16796. new OffscreenCanvas( width, height ) :
  16797. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  16798. }
  16799. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  16800. var scale = 1;
  16801. // handle case if texture exceeds max size
  16802. if ( image.width > maxSize || image.height > maxSize ) {
  16803. scale = maxSize / Math.max( image.width, image.height );
  16804. }
  16805. // only perform resize if necessary
  16806. if ( scale < 1 || needsPowerOfTwo === true ) {
  16807. // only perform resize for certain image types
  16808. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  16809. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  16810. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  16811. var floor = needsPowerOfTwo ? _Math.floorPowerOfTwo : Math.floor;
  16812. var width = floor( scale * image.width );
  16813. var height = floor( scale * image.height );
  16814. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  16815. // cube textures can't reuse the same canvas
  16816. var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  16817. canvas.width = width;
  16818. canvas.height = height;
  16819. var context = canvas.getContext( '2d' );
  16820. context.drawImage( image, 0, 0, width, height );
  16821. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  16822. return canvas;
  16823. } else {
  16824. if ( 'data' in image ) {
  16825. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  16826. }
  16827. return image;
  16828. }
  16829. }
  16830. return image;
  16831. }
  16832. function isPowerOfTwo( image ) {
  16833. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  16834. }
  16835. function textureNeedsPowerOfTwo( texture ) {
  16836. if ( capabilities.isWebGL2 ) return false;
  16837. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  16838. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  16839. }
  16840. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  16841. return texture.generateMipmaps && supportsMips &&
  16842. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  16843. }
  16844. function generateMipmap( target, texture, width, height ) {
  16845. _gl.generateMipmap( target );
  16846. var textureProperties = properties.get( texture );
  16847. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  16848. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  16849. }
  16850. function getInternalFormat( glFormat, glType ) {
  16851. if ( ! capabilities.isWebGL2 ) return glFormat;
  16852. var internalFormat = glFormat;
  16853. if ( glFormat === 6403 ) {
  16854. if ( glType === 5126 ) internalFormat = 33326;
  16855. if ( glType === 5131 ) internalFormat = 33325;
  16856. if ( glType === 5121 ) internalFormat = 33321;
  16857. }
  16858. if ( glFormat === 6407 ) {
  16859. if ( glType === 5126 ) internalFormat = 34837;
  16860. if ( glType === 5131 ) internalFormat = 34843;
  16861. if ( glType === 5121 ) internalFormat = 32849;
  16862. }
  16863. if ( glFormat === 6408 ) {
  16864. if ( glType === 5126 ) internalFormat = 34836;
  16865. if ( glType === 5131 ) internalFormat = 34842;
  16866. if ( glType === 5121 ) internalFormat = 32856;
  16867. }
  16868. if ( internalFormat === 33325 || internalFormat === 33326 ||
  16869. internalFormat === 34842 || internalFormat === 34836 ) {
  16870. extensions.get( 'EXT_color_buffer_float' );
  16871. } else if ( internalFormat === 34843 || internalFormat === 34837 ) {
  16872. console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' );
  16873. }
  16874. return internalFormat;
  16875. }
  16876. // Fallback filters for non-power-of-2 textures
  16877. function filterFallback( f ) {
  16878. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  16879. return 9728;
  16880. }
  16881. return 9729;
  16882. }
  16883. //
  16884. function onTextureDispose( event ) {
  16885. var texture = event.target;
  16886. texture.removeEventListener( 'dispose', onTextureDispose );
  16887. deallocateTexture( texture );
  16888. if ( texture.isVideoTexture ) {
  16889. delete _videoTextures[ texture.id ];
  16890. }
  16891. info.memory.textures --;
  16892. }
  16893. function onRenderTargetDispose( event ) {
  16894. var renderTarget = event.target;
  16895. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  16896. deallocateRenderTarget( renderTarget );
  16897. info.memory.textures --;
  16898. }
  16899. //
  16900. function deallocateTexture( texture ) {
  16901. var textureProperties = properties.get( texture );
  16902. if ( textureProperties.__webglInit === undefined ) return;
  16903. _gl.deleteTexture( textureProperties.__webglTexture );
  16904. properties.remove( texture );
  16905. }
  16906. function deallocateRenderTarget( renderTarget ) {
  16907. var renderTargetProperties = properties.get( renderTarget );
  16908. var textureProperties = properties.get( renderTarget.texture );
  16909. if ( ! renderTarget ) return;
  16910. if ( textureProperties.__webglTexture !== undefined ) {
  16911. _gl.deleteTexture( textureProperties.__webglTexture );
  16912. }
  16913. if ( renderTarget.depthTexture ) {
  16914. renderTarget.depthTexture.dispose();
  16915. }
  16916. if ( renderTarget.isWebGLRenderTargetCube ) {
  16917. for ( var i = 0; i < 6; i ++ ) {
  16918. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  16919. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  16920. }
  16921. } else {
  16922. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  16923. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  16924. }
  16925. properties.remove( renderTarget.texture );
  16926. properties.remove( renderTarget );
  16927. }
  16928. //
  16929. function setTexture2D( texture, slot ) {
  16930. var textureProperties = properties.get( texture );
  16931. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  16932. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16933. var image = texture.image;
  16934. if ( image === undefined ) {
  16935. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  16936. } else if ( image.complete === false ) {
  16937. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  16938. } else {
  16939. uploadTexture( textureProperties, texture, slot );
  16940. return;
  16941. }
  16942. }
  16943. state.activeTexture( 33984 + slot );
  16944. state.bindTexture( 3553, textureProperties.__webglTexture );
  16945. }
  16946. function setTexture2DArray( texture, slot ) {
  16947. var textureProperties = properties.get( texture );
  16948. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16949. uploadTexture( textureProperties, texture, slot );
  16950. return;
  16951. }
  16952. state.activeTexture( 33984 + slot );
  16953. state.bindTexture( 35866, textureProperties.__webglTexture );
  16954. }
  16955. function setTexture3D( texture, slot ) {
  16956. var textureProperties = properties.get( texture );
  16957. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16958. uploadTexture( textureProperties, texture, slot );
  16959. return;
  16960. }
  16961. state.activeTexture( 33984 + slot );
  16962. state.bindTexture( 32879, textureProperties.__webglTexture );
  16963. }
  16964. function setTextureCube( texture, slot ) {
  16965. var textureProperties = properties.get( texture );
  16966. if ( texture.image.length === 6 ) {
  16967. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16968. initTexture( textureProperties, texture );
  16969. state.activeTexture( 33984 + slot );
  16970. state.bindTexture( 34067, textureProperties.__webglTexture );
  16971. _gl.pixelStorei( 37440, texture.flipY );
  16972. var isCompressed = ( texture && texture.isCompressedTexture );
  16973. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  16974. var cubeImage = [];
  16975. for ( var i = 0; i < 6; i ++ ) {
  16976. if ( ! isCompressed && ! isDataTexture ) {
  16977. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, capabilities.maxCubemapSize );
  16978. } else {
  16979. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16980. }
  16981. }
  16982. var image = cubeImage[ 0 ],
  16983. supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
  16984. glFormat = utils.convert( texture.format ),
  16985. glType = utils.convert( texture.type ),
  16986. glInternalFormat = getInternalFormat( glFormat, glType );
  16987. setTextureParameters( 34067, texture, supportsMips );
  16988. for ( var i = 0; i < 6; i ++ ) {
  16989. if ( ! isCompressed ) {
  16990. if ( isDataTexture ) {
  16991. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16992. } else {
  16993. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  16994. }
  16995. } else {
  16996. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16997. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16998. mipmap = mipmaps[ j ];
  16999. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  17000. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  17001. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  17002. } else {
  17003. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  17004. }
  17005. } else {
  17006. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  17007. }
  17008. }
  17009. }
  17010. }
  17011. if ( ! isCompressed ) {
  17012. textureProperties.__maxMipLevel = 0;
  17013. } else {
  17014. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17015. }
  17016. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  17017. // We assume images for cube map have the same size.
  17018. generateMipmap( 34067, texture, image.width, image.height );
  17019. }
  17020. textureProperties.__version = texture.version;
  17021. if ( texture.onUpdate ) texture.onUpdate( texture );
  17022. } else {
  17023. state.activeTexture( 33984 + slot );
  17024. state.bindTexture( 34067, textureProperties.__webglTexture );
  17025. }
  17026. }
  17027. }
  17028. function setTextureCubeDynamic( texture, slot ) {
  17029. state.activeTexture( 33984 + slot );
  17030. state.bindTexture( 34067, properties.get( texture ).__webglTexture );
  17031. }
  17032. function setTextureParameters( textureType, texture, supportsMips ) {
  17033. var extension;
  17034. if ( supportsMips ) {
  17035. _gl.texParameteri( textureType, 10242, utils.convert( texture.wrapS ) );
  17036. _gl.texParameteri( textureType, 10243, utils.convert( texture.wrapT ) );
  17037. if ( textureType === 32879 || textureType === 35866 ) {
  17038. _gl.texParameteri( textureType, 32882, utils.convert( texture.wrapR ) );
  17039. }
  17040. _gl.texParameteri( textureType, 10240, utils.convert( texture.magFilter ) );
  17041. _gl.texParameteri( textureType, 10241, utils.convert( texture.minFilter ) );
  17042. } else {
  17043. _gl.texParameteri( textureType, 10242, 33071 );
  17044. _gl.texParameteri( textureType, 10243, 33071 );
  17045. if ( textureType === 32879 || textureType === 35866 ) {
  17046. _gl.texParameteri( textureType, 32882, 33071 );
  17047. }
  17048. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  17049. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  17050. }
  17051. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  17052. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  17053. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  17054. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  17055. }
  17056. }
  17057. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  17058. if ( extension ) {
  17059. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  17060. if ( texture.type === HalfFloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  17061. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  17062. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  17063. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  17064. }
  17065. }
  17066. }
  17067. function initTexture( textureProperties, texture ) {
  17068. if ( textureProperties.__webglInit === undefined ) {
  17069. textureProperties.__webglInit = true;
  17070. texture.addEventListener( 'dispose', onTextureDispose );
  17071. textureProperties.__webglTexture = _gl.createTexture();
  17072. info.memory.textures ++;
  17073. }
  17074. }
  17075. function uploadTexture( textureProperties, texture, slot ) {
  17076. var textureType = 3553;
  17077. if ( texture.isDataTexture2DArray ) textureType = 35866;
  17078. if ( texture.isDataTexture3D ) textureType = 32879;
  17079. initTexture( textureProperties, texture );
  17080. state.activeTexture( 33984 + slot );
  17081. state.bindTexture( textureType, textureProperties.__webglTexture );
  17082. _gl.pixelStorei( 37440, texture.flipY );
  17083. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  17084. _gl.pixelStorei( 3317, texture.unpackAlignment );
  17085. var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  17086. var image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize );
  17087. var supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2,
  17088. glFormat = utils.convert( texture.format ),
  17089. glType = utils.convert( texture.type ),
  17090. glInternalFormat = getInternalFormat( glFormat, glType );
  17091. setTextureParameters( textureType, texture, supportsMips );
  17092. var mipmap, mipmaps = texture.mipmaps;
  17093. if ( texture.isDepthTexture ) {
  17094. // populate depth texture with dummy data
  17095. glInternalFormat = 6402;
  17096. if ( texture.type === FloatType ) {
  17097. if ( ! capabilities.isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
  17098. glInternalFormat = 36012;
  17099. } else if ( capabilities.isWebGL2 ) {
  17100. // WebGL 2.0 requires signed internalformat for glTexImage2D
  17101. glInternalFormat = 33189;
  17102. }
  17103. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  17104. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  17105. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  17106. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  17107. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  17108. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  17109. texture.type = UnsignedShortType;
  17110. glType = utils.convert( texture.type );
  17111. }
  17112. }
  17113. // Depth stencil textures need the DEPTH_STENCIL internal format
  17114. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  17115. if ( texture.format === DepthStencilFormat ) {
  17116. glInternalFormat = 34041;
  17117. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  17118. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  17119. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  17120. if ( texture.type !== UnsignedInt248Type ) {
  17121. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  17122. texture.type = UnsignedInt248Type;
  17123. glType = utils.convert( texture.type );
  17124. }
  17125. }
  17126. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  17127. } else if ( texture.isDataTexture ) {
  17128. // use manually created mipmaps if available
  17129. // if there are no manual mipmaps
  17130. // set 0 level mipmap and then use GL to generate other mipmap levels
  17131. if ( mipmaps.length > 0 && supportsMips ) {
  17132. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  17133. mipmap = mipmaps[ i ];
  17134. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  17135. }
  17136. texture.generateMipmaps = false;
  17137. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17138. } else {
  17139. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  17140. textureProperties.__maxMipLevel = 0;
  17141. }
  17142. } else if ( texture.isCompressedTexture ) {
  17143. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  17144. mipmap = mipmaps[ i ];
  17145. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  17146. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  17147. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  17148. } else {
  17149. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  17150. }
  17151. } else {
  17152. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  17153. }
  17154. }
  17155. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17156. } else if ( texture.isDataTexture2DArray ) {
  17157. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  17158. textureProperties.__maxMipLevel = 0;
  17159. } else if ( texture.isDataTexture3D ) {
  17160. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  17161. textureProperties.__maxMipLevel = 0;
  17162. } else {
  17163. // regular Texture (image, video, canvas)
  17164. // use manually created mipmaps if available
  17165. // if there are no manual mipmaps
  17166. // set 0 level mipmap and then use GL to generate other mipmap levels
  17167. if ( mipmaps.length > 0 && supportsMips ) {
  17168. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  17169. mipmap = mipmaps[ i ];
  17170. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  17171. }
  17172. texture.generateMipmaps = false;
  17173. textureProperties.__maxMipLevel = mipmaps.length - 1;
  17174. } else {
  17175. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  17176. textureProperties.__maxMipLevel = 0;
  17177. }
  17178. }
  17179. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  17180. generateMipmap( 3553, texture, image.width, image.height );
  17181. }
  17182. textureProperties.__version = texture.version;
  17183. if ( texture.onUpdate ) texture.onUpdate( texture );
  17184. }
  17185. // Render targets
  17186. // Setup storage for target texture and bind it to correct framebuffer
  17187. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  17188. var glFormat = utils.convert( renderTarget.texture.format );
  17189. var glType = utils.convert( renderTarget.texture.type );
  17190. var glInternalFormat = getInternalFormat( glFormat, glType );
  17191. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  17192. _gl.bindFramebuffer( 36160, framebuffer );
  17193. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  17194. _gl.bindFramebuffer( 36160, null );
  17195. }
  17196. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  17197. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  17198. _gl.bindRenderbuffer( 36161, renderbuffer );
  17199. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  17200. if ( isMultisample ) {
  17201. var samples = getRenderTargetSamples( renderTarget );
  17202. _gl.renderbufferStorageMultisample( 36161, samples, 33189, renderTarget.width, renderTarget.height );
  17203. } else {
  17204. _gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height );
  17205. }
  17206. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  17207. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  17208. if ( isMultisample ) {
  17209. var samples = getRenderTargetSamples( renderTarget );
  17210. _gl.renderbufferStorageMultisample( 36161, samples, 34041, renderTarget.width, renderTarget.height );
  17211. } else {
  17212. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  17213. }
  17214. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  17215. } else {
  17216. var glFormat = utils.convert( renderTarget.texture.format );
  17217. var glType = utils.convert( renderTarget.texture.type );
  17218. var glInternalFormat = getInternalFormat( glFormat, glType );
  17219. if ( isMultisample ) {
  17220. var samples = getRenderTargetSamples( renderTarget );
  17221. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  17222. } else {
  17223. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  17224. }
  17225. }
  17226. _gl.bindRenderbuffer( 36161, null );
  17227. }
  17228. // Setup resources for a Depth Texture for a FBO (needs an extension)
  17229. function setupDepthTexture( framebuffer, renderTarget ) {
  17230. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  17231. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  17232. _gl.bindFramebuffer( 36160, framebuffer );
  17233. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  17234. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  17235. }
  17236. // upload an empty depth texture with framebuffer size
  17237. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  17238. renderTarget.depthTexture.image.width !== renderTarget.width ||
  17239. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  17240. renderTarget.depthTexture.image.width = renderTarget.width;
  17241. renderTarget.depthTexture.image.height = renderTarget.height;
  17242. renderTarget.depthTexture.needsUpdate = true;
  17243. }
  17244. setTexture2D( renderTarget.depthTexture, 0 );
  17245. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  17246. if ( renderTarget.depthTexture.format === DepthFormat ) {
  17247. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  17248. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  17249. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  17250. } else {
  17251. throw new Error( 'Unknown depthTexture format' );
  17252. }
  17253. }
  17254. // Setup GL resources for a non-texture depth buffer
  17255. function setupDepthRenderbuffer( renderTarget ) {
  17256. var renderTargetProperties = properties.get( renderTarget );
  17257. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  17258. if ( renderTarget.depthTexture ) {
  17259. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  17260. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  17261. } else {
  17262. if ( isCube ) {
  17263. renderTargetProperties.__webglDepthbuffer = [];
  17264. for ( var i = 0; i < 6; i ++ ) {
  17265. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  17266. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  17267. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  17268. }
  17269. } else {
  17270. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  17271. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  17272. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  17273. }
  17274. }
  17275. _gl.bindFramebuffer( 36160, null );
  17276. }
  17277. // Set up GL resources for the render target
  17278. function setupRenderTarget( renderTarget ) {
  17279. var renderTargetProperties = properties.get( renderTarget );
  17280. var textureProperties = properties.get( renderTarget.texture );
  17281. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  17282. textureProperties.__webglTexture = _gl.createTexture();
  17283. info.memory.textures ++;
  17284. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  17285. var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  17286. var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;
  17287. // Setup framebuffer
  17288. if ( isCube ) {
  17289. renderTargetProperties.__webglFramebuffer = [];
  17290. for ( var i = 0; i < 6; i ++ ) {
  17291. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  17292. }
  17293. } else {
  17294. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  17295. if ( isMultisample ) {
  17296. if ( capabilities.isWebGL2 ) {
  17297. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  17298. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  17299. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  17300. var glFormat = utils.convert( renderTarget.texture.format );
  17301. var glType = utils.convert( renderTarget.texture.type );
  17302. var glInternalFormat = getInternalFormat( glFormat, glType );
  17303. var samples = getRenderTargetSamples( renderTarget );
  17304. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  17305. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  17306. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  17307. _gl.bindRenderbuffer( 36161, null );
  17308. if ( renderTarget.depthBuffer ) {
  17309. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  17310. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  17311. }
  17312. _gl.bindFramebuffer( 36160, null );
  17313. } else {
  17314. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  17315. }
  17316. }
  17317. }
  17318. // Setup color buffer
  17319. if ( isCube ) {
  17320. state.bindTexture( 34067, textureProperties.__webglTexture );
  17321. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  17322. for ( var i = 0; i < 6; i ++ ) {
  17323. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  17324. }
  17325. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  17326. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  17327. }
  17328. state.bindTexture( 34067, null );
  17329. } else {
  17330. state.bindTexture( 3553, textureProperties.__webglTexture );
  17331. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  17332. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  17333. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  17334. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  17335. }
  17336. state.bindTexture( 3553, null );
  17337. }
  17338. // Setup depth and stencil buffers
  17339. if ( renderTarget.depthBuffer ) {
  17340. setupDepthRenderbuffer( renderTarget );
  17341. }
  17342. }
  17343. function updateRenderTargetMipmap( renderTarget ) {
  17344. var texture = renderTarget.texture;
  17345. var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2;
  17346. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  17347. var target = renderTarget.isWebGLRenderTargetCube ? 34067 : 3553;
  17348. var webglTexture = properties.get( texture ).__webglTexture;
  17349. state.bindTexture( target, webglTexture );
  17350. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  17351. state.bindTexture( target, null );
  17352. }
  17353. }
  17354. function updateMultisampleRenderTarget( renderTarget ) {
  17355. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  17356. if ( capabilities.isWebGL2 ) {
  17357. var renderTargetProperties = properties.get( renderTarget );
  17358. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  17359. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  17360. var width = renderTarget.width;
  17361. var height = renderTarget.height;
  17362. var mask = 16384;
  17363. if ( renderTarget.depthBuffer ) mask |= 256;
  17364. if ( renderTarget.stencilBuffer ) mask |= 1024;
  17365. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  17366. } else {
  17367. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  17368. }
  17369. }
  17370. }
  17371. function getRenderTargetSamples( renderTarget ) {
  17372. return ( capabilities.isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  17373. Math.min( capabilities.maxSamples, renderTarget.samples ) : 0;
  17374. }
  17375. function updateVideoTexture( texture ) {
  17376. var id = texture.id;
  17377. var frame = info.render.frame;
  17378. // Check the last frame we updated the VideoTexture
  17379. if ( _videoTextures[ id ] !== frame ) {
  17380. _videoTextures[ id ] = frame;
  17381. texture.update();
  17382. }
  17383. }
  17384. this.setTexture2D = setTexture2D;
  17385. this.setTexture2DArray = setTexture2DArray;
  17386. this.setTexture3D = setTexture3D;
  17387. this.setTextureCube = setTextureCube;
  17388. this.setTextureCubeDynamic = setTextureCubeDynamic;
  17389. this.setupRenderTarget = setupRenderTarget;
  17390. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  17391. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  17392. }
  17393. /**
  17394. * @author thespite / http://www.twitter.com/thespite
  17395. */
  17396. function WebGLUtils( gl, extensions, capabilities ) {
  17397. function convert( p ) {
  17398. var extension;
  17399. if ( p === RepeatWrapping ) return 10497;
  17400. if ( p === ClampToEdgeWrapping ) return 33071;
  17401. if ( p === MirroredRepeatWrapping ) return 33648;
  17402. if ( p === NearestFilter ) return 9728;
  17403. if ( p === NearestMipMapNearestFilter ) return 9984;
  17404. if ( p === NearestMipMapLinearFilter ) return 9986;
  17405. if ( p === LinearFilter ) return 9729;
  17406. if ( p === LinearMipMapNearestFilter ) return 9985;
  17407. if ( p === LinearMipMapLinearFilter ) return 9987;
  17408. if ( p === UnsignedByteType ) return 5121;
  17409. if ( p === UnsignedShort4444Type ) return 32819;
  17410. if ( p === UnsignedShort5551Type ) return 32820;
  17411. if ( p === UnsignedShort565Type ) return 33635;
  17412. if ( p === ByteType ) return 5120;
  17413. if ( p === ShortType ) return 5122;
  17414. if ( p === UnsignedShortType ) return 5123;
  17415. if ( p === IntType ) return 5124;
  17416. if ( p === UnsignedIntType ) return 5125;
  17417. if ( p === FloatType ) return 5126;
  17418. if ( p === HalfFloatType ) {
  17419. if ( capabilities.isWebGL2 ) return 5131;
  17420. extension = extensions.get( 'OES_texture_half_float' );
  17421. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  17422. }
  17423. if ( p === AlphaFormat ) return 6406;
  17424. if ( p === RGBFormat ) return 6407;
  17425. if ( p === RGBAFormat ) return 6408;
  17426. if ( p === LuminanceFormat ) return 6409;
  17427. if ( p === LuminanceAlphaFormat ) return 6410;
  17428. if ( p === DepthFormat ) return 6402;
  17429. if ( p === DepthStencilFormat ) return 34041;
  17430. if ( p === RedFormat ) return 6403;
  17431. if ( p === AddEquation ) return 32774;
  17432. if ( p === SubtractEquation ) return 32778;
  17433. if ( p === ReverseSubtractEquation ) return 32779;
  17434. if ( p === ZeroFactor ) return 0;
  17435. if ( p === OneFactor ) return 1;
  17436. if ( p === SrcColorFactor ) return 768;
  17437. if ( p === OneMinusSrcColorFactor ) return 769;
  17438. if ( p === SrcAlphaFactor ) return 770;
  17439. if ( p === OneMinusSrcAlphaFactor ) return 771;
  17440. if ( p === DstAlphaFactor ) return 772;
  17441. if ( p === OneMinusDstAlphaFactor ) return 773;
  17442. if ( p === DstColorFactor ) return 774;
  17443. if ( p === OneMinusDstColorFactor ) return 775;
  17444. if ( p === SrcAlphaSaturateFactor ) return 776;
  17445. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  17446. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  17447. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  17448. if ( extension !== null ) {
  17449. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  17450. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17451. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17452. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17453. }
  17454. }
  17455. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  17456. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  17457. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  17458. if ( extension !== null ) {
  17459. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  17460. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  17461. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  17462. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  17463. }
  17464. }
  17465. if ( p === RGB_ETC1_Format ) {
  17466. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  17467. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  17468. }
  17469. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  17470. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  17471. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  17472. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  17473. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  17474. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  17475. if ( extension !== null ) {
  17476. return p;
  17477. }
  17478. }
  17479. if ( p === MinEquation || p === MaxEquation ) {
  17480. if ( capabilities.isWebGL2 ) {
  17481. if ( p === MinEquation ) return 32775;
  17482. if ( p === MaxEquation ) return 32776;
  17483. }
  17484. extension = extensions.get( 'EXT_blend_minmax' );
  17485. if ( extension !== null ) {
  17486. if ( p === MinEquation ) return extension.MIN_EXT;
  17487. if ( p === MaxEquation ) return extension.MAX_EXT;
  17488. }
  17489. }
  17490. if ( p === UnsignedInt248Type ) {
  17491. if ( capabilities.isWebGL2 ) return 34042;
  17492. extension = extensions.get( 'WEBGL_depth_texture' );
  17493. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  17494. }
  17495. return 0;
  17496. }
  17497. return { convert: convert };
  17498. }
  17499. /**
  17500. * @author mrdoob / http://mrdoob.com/
  17501. */
  17502. function Group() {
  17503. Object3D.call( this );
  17504. this.type = 'Group';
  17505. }
  17506. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17507. constructor: Group,
  17508. isGroup: true
  17509. } );
  17510. /**
  17511. * @author mrdoob / http://mrdoob.com/
  17512. * @author mikael emtinger / http://gomo.se/
  17513. * @author WestLangley / http://github.com/WestLangley
  17514. */
  17515. function Camera() {
  17516. Object3D.call( this );
  17517. this.type = 'Camera';
  17518. this.matrixWorldInverse = new Matrix4();
  17519. this.projectionMatrix = new Matrix4();
  17520. this.projectionMatrixInverse = new Matrix4();
  17521. }
  17522. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17523. constructor: Camera,
  17524. isCamera: true,
  17525. copy: function ( source, recursive ) {
  17526. Object3D.prototype.copy.call( this, source, recursive );
  17527. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  17528. this.projectionMatrix.copy( source.projectionMatrix );
  17529. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  17530. return this;
  17531. },
  17532. getWorldDirection: function ( target ) {
  17533. if ( target === undefined ) {
  17534. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  17535. target = new Vector3();
  17536. }
  17537. this.updateMatrixWorld( true );
  17538. var e = this.matrixWorld.elements;
  17539. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  17540. },
  17541. updateMatrixWorld: function ( force ) {
  17542. Object3D.prototype.updateMatrixWorld.call( this, force );
  17543. this.matrixWorldInverse.getInverse( this.matrixWorld );
  17544. },
  17545. clone: function () {
  17546. return new this.constructor().copy( this );
  17547. }
  17548. } );
  17549. /**
  17550. * @author mrdoob / http://mrdoob.com/
  17551. * @author greggman / http://games.greggman.com/
  17552. * @author zz85 / http://www.lab4games.net/zz85/blog
  17553. * @author tschw
  17554. */
  17555. function PerspectiveCamera( fov, aspect, near, far ) {
  17556. Camera.call( this );
  17557. this.type = 'PerspectiveCamera';
  17558. this.fov = fov !== undefined ? fov : 50;
  17559. this.zoom = 1;
  17560. this.near = near !== undefined ? near : 0.1;
  17561. this.far = far !== undefined ? far : 2000;
  17562. this.focus = 10;
  17563. this.aspect = aspect !== undefined ? aspect : 1;
  17564. this.view = null;
  17565. this.filmGauge = 35; // width of the film (default in millimeters)
  17566. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  17567. this.updateProjectionMatrix();
  17568. }
  17569. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  17570. constructor: PerspectiveCamera,
  17571. isPerspectiveCamera: true,
  17572. copy: function ( source, recursive ) {
  17573. Camera.prototype.copy.call( this, source, recursive );
  17574. this.fov = source.fov;
  17575. this.zoom = source.zoom;
  17576. this.near = source.near;
  17577. this.far = source.far;
  17578. this.focus = source.focus;
  17579. this.aspect = source.aspect;
  17580. this.view = source.view === null ? null : Object.assign( {}, source.view );
  17581. this.filmGauge = source.filmGauge;
  17582. this.filmOffset = source.filmOffset;
  17583. return this;
  17584. },
  17585. /**
  17586. * Sets the FOV by focal length in respect to the current .filmGauge.
  17587. *
  17588. * The default film gauge is 35, so that the focal length can be specified for
  17589. * a 35mm (full frame) camera.
  17590. *
  17591. * Values for focal length and film gauge must have the same unit.
  17592. */
  17593. setFocalLength: function ( focalLength ) {
  17594. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  17595. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  17596. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  17597. this.updateProjectionMatrix();
  17598. },
  17599. /**
  17600. * Calculates the focal length from the current .fov and .filmGauge.
  17601. */
  17602. getFocalLength: function () {
  17603. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  17604. return 0.5 * this.getFilmHeight() / vExtentSlope;
  17605. },
  17606. getEffectiveFOV: function () {
  17607. return _Math.RAD2DEG * 2 * Math.atan(
  17608. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  17609. },
  17610. getFilmWidth: function () {
  17611. // film not completely covered in portrait format (aspect < 1)
  17612. return this.filmGauge * Math.min( this.aspect, 1 );
  17613. },
  17614. getFilmHeight: function () {
  17615. // film not completely covered in landscape format (aspect > 1)
  17616. return this.filmGauge / Math.max( this.aspect, 1 );
  17617. },
  17618. /**
  17619. * Sets an offset in a larger frustum. This is useful for multi-window or
  17620. * multi-monitor/multi-machine setups.
  17621. *
  17622. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  17623. * the monitors are in grid like this
  17624. *
  17625. * +---+---+---+
  17626. * | A | B | C |
  17627. * +---+---+---+
  17628. * | D | E | F |
  17629. * +---+---+---+
  17630. *
  17631. * then for each monitor you would call it like this
  17632. *
  17633. * var w = 1920;
  17634. * var h = 1080;
  17635. * var fullWidth = w * 3;
  17636. * var fullHeight = h * 2;
  17637. *
  17638. * --A--
  17639. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  17640. * --B--
  17641. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  17642. * --C--
  17643. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  17644. * --D--
  17645. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  17646. * --E--
  17647. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  17648. * --F--
  17649. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  17650. *
  17651. * Note there is no reason monitors have to be the same size or in a grid.
  17652. */
  17653. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  17654. this.aspect = fullWidth / fullHeight;
  17655. if ( this.view === null ) {
  17656. this.view = {
  17657. enabled: true,
  17658. fullWidth: 1,
  17659. fullHeight: 1,
  17660. offsetX: 0,
  17661. offsetY: 0,
  17662. width: 1,
  17663. height: 1
  17664. };
  17665. }
  17666. this.view.enabled = true;
  17667. this.view.fullWidth = fullWidth;
  17668. this.view.fullHeight = fullHeight;
  17669. this.view.offsetX = x;
  17670. this.view.offsetY = y;
  17671. this.view.width = width;
  17672. this.view.height = height;
  17673. this.updateProjectionMatrix();
  17674. },
  17675. clearViewOffset: function () {
  17676. if ( this.view !== null ) {
  17677. this.view.enabled = false;
  17678. }
  17679. this.updateProjectionMatrix();
  17680. },
  17681. updateProjectionMatrix: function () {
  17682. var near = this.near,
  17683. top = near * Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  17684. height = 2 * top,
  17685. width = this.aspect * height,
  17686. left = - 0.5 * width,
  17687. view = this.view;
  17688. if ( this.view !== null && this.view.enabled ) {
  17689. var fullWidth = view.fullWidth,
  17690. fullHeight = view.fullHeight;
  17691. left += view.offsetX * width / fullWidth;
  17692. top -= view.offsetY * height / fullHeight;
  17693. width *= view.width / fullWidth;
  17694. height *= view.height / fullHeight;
  17695. }
  17696. var skew = this.filmOffset;
  17697. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  17698. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  17699. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  17700. },
  17701. toJSON: function ( meta ) {
  17702. var data = Object3D.prototype.toJSON.call( this, meta );
  17703. data.object.fov = this.fov;
  17704. data.object.zoom = this.zoom;
  17705. data.object.near = this.near;
  17706. data.object.far = this.far;
  17707. data.object.focus = this.focus;
  17708. data.object.aspect = this.aspect;
  17709. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  17710. data.object.filmGauge = this.filmGauge;
  17711. data.object.filmOffset = this.filmOffset;
  17712. return data;
  17713. }
  17714. } );
  17715. /**
  17716. * @author mrdoob / http://mrdoob.com/
  17717. */
  17718. function ArrayCamera( array ) {
  17719. PerspectiveCamera.call( this );
  17720. this.cameras = array || [];
  17721. }
  17722. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  17723. constructor: ArrayCamera,
  17724. isArrayCamera: true
  17725. } );
  17726. /**
  17727. * @author jsantell / https://www.jsantell.com/
  17728. * @author mrdoob / http://mrdoob.com/
  17729. */
  17730. var cameraLPos = new Vector3();
  17731. var cameraRPos = new Vector3();
  17732. /**
  17733. * Assumes 2 cameras that are parallel and share an X-axis, and that
  17734. * the cameras' projection and world matrices have already been set.
  17735. * And that near and far planes are identical for both cameras.
  17736. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  17737. */
  17738. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  17739. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  17740. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  17741. var ipd = cameraLPos.distanceTo( cameraRPos );
  17742. var projL = cameraL.projectionMatrix.elements;
  17743. var projR = cameraR.projectionMatrix.elements;
  17744. // VR systems will have identical far and near planes, and
  17745. // most likely identical top and bottom frustum extents.
  17746. // Use the left camera for these values.
  17747. var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  17748. var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  17749. var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  17750. var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  17751. var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  17752. var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  17753. var left = near * leftFov;
  17754. var right = near * rightFov;
  17755. // Calculate the new camera's position offset from the
  17756. // left camera. xOffset should be roughly half `ipd`.
  17757. var zOffset = ipd / ( - leftFov + rightFov );
  17758. var xOffset = zOffset * - leftFov;
  17759. // TODO: Better way to apply this offset?
  17760. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  17761. camera.translateX( xOffset );
  17762. camera.translateZ( zOffset );
  17763. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  17764. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  17765. // Find the union of the frustum values of the cameras and scale
  17766. // the values so that the near plane's position does not change in world space,
  17767. // although must now be relative to the new union camera.
  17768. var near2 = near + zOffset;
  17769. var far2 = far + zOffset;
  17770. var left2 = left - xOffset;
  17771. var right2 = right + ( ipd - xOffset );
  17772. var top2 = topFov * far / far2 * near2;
  17773. var bottom2 = bottomFov * far / far2 * near2;
  17774. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  17775. }
  17776. /**
  17777. * @author mrdoob / http://mrdoob.com/
  17778. */
  17779. function WebVRManager( renderer ) {
  17780. var scope = this;
  17781. var device = null;
  17782. var frameData = null;
  17783. var poseTarget = null;
  17784. var controllers = [];
  17785. var standingMatrix = new Matrix4();
  17786. var standingMatrixInverse = new Matrix4();
  17787. var framebufferScaleFactor = 1.0;
  17788. var frameOfReferenceType = 'stage';
  17789. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  17790. frameData = new window.VRFrameData();
  17791. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  17792. }
  17793. var matrixWorldInverse = new Matrix4();
  17794. var tempQuaternion = new Quaternion();
  17795. var tempPosition = new Vector3();
  17796. var cameraL = new PerspectiveCamera();
  17797. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  17798. cameraL.layers.enable( 1 );
  17799. var cameraR = new PerspectiveCamera();
  17800. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  17801. cameraR.layers.enable( 2 );
  17802. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  17803. cameraVR.layers.enable( 1 );
  17804. cameraVR.layers.enable( 2 );
  17805. //
  17806. function isPresenting() {
  17807. return device !== null && device.isPresenting === true;
  17808. }
  17809. var currentSize = new Vector2(), currentPixelRatio;
  17810. function onVRDisplayPresentChange() {
  17811. updateDrawingBufferSize();
  17812. if ( isPresenting() ) {
  17813. animation.start();
  17814. } else {
  17815. animation.stop();
  17816. }
  17817. }
  17818. //
  17819. var triggers = [];
  17820. function findGamepad( id ) {
  17821. var gamepads = navigator.getGamepads && navigator.getGamepads();
  17822. for ( var i = 0, j = 0, l = gamepads.length; i < l; i ++ ) {
  17823. var gamepad = gamepads[ i ];
  17824. if ( gamepad && ( gamepad.id === 'Daydream Controller' ||
  17825. gamepad.id === 'Gear VR Controller' || gamepad.id === 'Oculus Go Controller' ||
  17826. gamepad.id === 'OpenVR Gamepad' || gamepad.id.startsWith( 'Oculus Touch' ) ||
  17827. gamepad.id.startsWith( 'Spatial Controller' ) ) ) {
  17828. if ( j === id ) return gamepad;
  17829. j ++;
  17830. }
  17831. }
  17832. }
  17833. function updateDrawingBufferSize() {
  17834. if ( isPresenting() ) {
  17835. var eyeParameters = device.getEyeParameters( 'left' );
  17836. var renderWidth = eyeParameters.renderWidth * framebufferScaleFactor;
  17837. var renderHeight = eyeParameters.renderHeight * framebufferScaleFactor;
  17838. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  17839. } else {
  17840. if ( scope.enabled ) {
  17841. currentPixelRatio = renderer.getPixelRatio();
  17842. renderer.getSize( currentSize );
  17843. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  17844. }
  17845. }
  17846. }
  17847. function updateControllers() {
  17848. for ( var i = 0; i < controllers.length; i ++ ) {
  17849. var controller = controllers[ i ];
  17850. var gamepad = findGamepad( i );
  17851. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  17852. if ( gamepad.pose === null ) return;
  17853. // Pose
  17854. var pose = gamepad.pose;
  17855. if ( pose.hasPosition === false ) controller.position.set( 0.2, - 0.6, - 0.05 );
  17856. if ( pose.position !== null ) controller.position.fromArray( pose.position );
  17857. if ( pose.orientation !== null ) controller.quaternion.fromArray( pose.orientation );
  17858. controller.matrix.compose( controller.position, controller.quaternion, controller.scale );
  17859. controller.matrix.premultiply( standingMatrix );
  17860. controller.matrix.decompose( controller.position, controller.quaternion, controller.scale );
  17861. controller.matrixWorldNeedsUpdate = true;
  17862. controller.visible = true;
  17863. // Trigger
  17864. var buttonId = gamepad.id === 'Daydream Controller' ? 0 : 1;
  17865. if ( triggers[ i ] !== gamepad.buttons[ buttonId ].pressed ) {
  17866. triggers[ i ] = gamepad.buttons[ buttonId ].pressed;
  17867. if ( triggers[ i ] === true ) {
  17868. controller.dispatchEvent( { type: 'selectstart' } );
  17869. } else {
  17870. controller.dispatchEvent( { type: 'selectend' } );
  17871. controller.dispatchEvent( { type: 'select' } );
  17872. }
  17873. }
  17874. } else {
  17875. controller.visible = false;
  17876. }
  17877. }
  17878. }
  17879. //
  17880. this.enabled = false;
  17881. this.getController = function ( id ) {
  17882. var controller = controllers[ id ];
  17883. if ( controller === undefined ) {
  17884. controller = new Group();
  17885. controller.matrixAutoUpdate = false;
  17886. controller.visible = false;
  17887. controllers[ id ] = controller;
  17888. }
  17889. return controller;
  17890. };
  17891. this.getDevice = function () {
  17892. return device;
  17893. };
  17894. this.setDevice = function ( value ) {
  17895. if ( value !== undefined ) device = value;
  17896. animation.setContext( value );
  17897. updateDrawingBufferSize();
  17898. if ( isPresenting() ) animation.start();
  17899. };
  17900. this.setFramebufferScaleFactor = function ( value ) {
  17901. framebufferScaleFactor = value;
  17902. };
  17903. this.setFrameOfReferenceType = function ( value ) {
  17904. frameOfReferenceType = value;
  17905. };
  17906. this.setPoseTarget = function ( object ) {
  17907. if ( object !== undefined ) poseTarget = object;
  17908. };
  17909. this.getCamera = function ( camera ) {
  17910. var userHeight = frameOfReferenceType === 'stage' ? 1.6 : 0;
  17911. if ( isPresenting() === false ) {
  17912. camera.position.set( 0, userHeight, 0 );
  17913. camera.rotation.set( 0, 0, 0 );
  17914. return camera;
  17915. }
  17916. device.depthNear = camera.near;
  17917. device.depthFar = camera.far;
  17918. device.getFrameData( frameData );
  17919. //
  17920. if ( frameOfReferenceType === 'stage' ) {
  17921. var stageParameters = device.stageParameters;
  17922. if ( stageParameters ) {
  17923. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  17924. } else {
  17925. standingMatrix.makeTranslation( 0, userHeight, 0 );
  17926. }
  17927. }
  17928. var pose = frameData.pose;
  17929. var poseObject = poseTarget !== null ? poseTarget : camera;
  17930. // We want to manipulate poseObject by its position and quaternion components since users may rely on them.
  17931. poseObject.matrix.copy( standingMatrix );
  17932. poseObject.matrix.decompose( poseObject.position, poseObject.quaternion, poseObject.scale );
  17933. if ( pose.orientation !== null ) {
  17934. tempQuaternion.fromArray( pose.orientation );
  17935. poseObject.quaternion.multiply( tempQuaternion );
  17936. }
  17937. if ( pose.position !== null ) {
  17938. tempQuaternion.setFromRotationMatrix( standingMatrix );
  17939. tempPosition.fromArray( pose.position );
  17940. tempPosition.applyQuaternion( tempQuaternion );
  17941. poseObject.position.add( tempPosition );
  17942. }
  17943. poseObject.updateMatrixWorld();
  17944. //
  17945. cameraL.near = camera.near;
  17946. cameraR.near = camera.near;
  17947. cameraL.far = camera.far;
  17948. cameraR.far = camera.far;
  17949. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  17950. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  17951. // TODO (mrdoob) Double check this code
  17952. standingMatrixInverse.getInverse( standingMatrix );
  17953. if ( frameOfReferenceType === 'stage' ) {
  17954. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  17955. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  17956. }
  17957. var parent = poseObject.parent;
  17958. if ( parent !== null ) {
  17959. matrixWorldInverse.getInverse( parent.matrixWorld );
  17960. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  17961. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  17962. }
  17963. // envMap and Mirror needs camera.matrixWorld
  17964. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  17965. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  17966. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  17967. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  17968. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  17969. //
  17970. var layers = device.getLayers();
  17971. if ( layers.length ) {
  17972. var layer = layers[ 0 ];
  17973. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  17974. cameraL.bounds.fromArray( layer.leftBounds );
  17975. }
  17976. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  17977. cameraR.bounds.fromArray( layer.rightBounds );
  17978. }
  17979. }
  17980. updateControllers();
  17981. return cameraVR;
  17982. };
  17983. this.getStandingMatrix = function () {
  17984. return standingMatrix;
  17985. };
  17986. this.isPresenting = isPresenting;
  17987. // Animation Loop
  17988. var animation = new WebGLAnimation();
  17989. this.setAnimationLoop = function ( callback ) {
  17990. animation.setAnimationLoop( callback );
  17991. if ( isPresenting() ) animation.start();
  17992. };
  17993. this.submitFrame = function () {
  17994. if ( isPresenting() ) device.submitFrame();
  17995. };
  17996. this.dispose = function () {
  17997. if ( typeof window !== 'undefined' ) {
  17998. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  17999. }
  18000. };
  18001. }
  18002. /**
  18003. * @author mrdoob / http://mrdoob.com/
  18004. */
  18005. function WebXRManager( renderer ) {
  18006. var gl = renderer.context;
  18007. var device = null;
  18008. var session = null;
  18009. var framebufferScaleFactor = 1.0;
  18010. var frameOfReference = null;
  18011. var frameOfReferenceType = 'stage';
  18012. var pose = null;
  18013. var poseTarget = null;
  18014. var controllers = [];
  18015. var inputSources = [];
  18016. function isPresenting() {
  18017. return session !== null && frameOfReference !== null;
  18018. }
  18019. //
  18020. var cameraL = new PerspectiveCamera();
  18021. cameraL.layers.enable( 1 );
  18022. cameraL.viewport = new Vector4();
  18023. var cameraR = new PerspectiveCamera();
  18024. cameraR.layers.enable( 2 );
  18025. cameraR.viewport = new Vector4();
  18026. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  18027. cameraVR.layers.enable( 1 );
  18028. cameraVR.layers.enable( 2 );
  18029. //
  18030. this.enabled = false;
  18031. this.getController = function ( id ) {
  18032. var controller = controllers[ id ];
  18033. if ( controller === undefined ) {
  18034. controller = new Group();
  18035. controller.matrixAutoUpdate = false;
  18036. controller.visible = false;
  18037. controllers[ id ] = controller;
  18038. }
  18039. return controller;
  18040. };
  18041. this.getDevice = function () {
  18042. return device;
  18043. };
  18044. this.setDevice = function ( value ) {
  18045. if ( value !== undefined ) device = value;
  18046. if ( value instanceof XRDevice ) gl.setCompatibleXRDevice( value );
  18047. };
  18048. //
  18049. function onSessionEvent( event ) {
  18050. var controller = controllers[ inputSources.indexOf( event.inputSource ) ];
  18051. if ( controller ) controller.dispatchEvent( { type: event.type } );
  18052. }
  18053. function onSessionEnd() {
  18054. renderer.setFramebuffer( null );
  18055. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  18056. animation.stop();
  18057. }
  18058. this.setFramebufferScaleFactor = function ( value ) {
  18059. framebufferScaleFactor = value;
  18060. };
  18061. this.setFrameOfReferenceType = function ( value ) {
  18062. frameOfReferenceType = value;
  18063. };
  18064. this.setSession = function ( value ) {
  18065. session = value;
  18066. if ( session !== null ) {
  18067. session.addEventListener( 'select', onSessionEvent );
  18068. session.addEventListener( 'selectstart', onSessionEvent );
  18069. session.addEventListener( 'selectend', onSessionEvent );
  18070. session.addEventListener( 'end', onSessionEnd );
  18071. session.baseLayer = new XRWebGLLayer( session, gl, { framebufferScaleFactor: framebufferScaleFactor } );
  18072. session.requestFrameOfReference( frameOfReferenceType ).then( function ( value ) {
  18073. frameOfReference = value;
  18074. renderer.setFramebuffer( session.baseLayer.framebuffer );
  18075. animation.setContext( session );
  18076. animation.start();
  18077. } );
  18078. //
  18079. inputSources = session.getInputSources();
  18080. session.addEventListener( 'inputsourceschange', function () {
  18081. inputSources = session.getInputSources();
  18082. console.log( inputSources );
  18083. for ( var i = 0; i < controllers.length; i ++ ) {
  18084. var controller = controllers[ i ];
  18085. controller.userData.inputSource = inputSources[ i ];
  18086. }
  18087. } );
  18088. }
  18089. };
  18090. function updateCamera( camera, parent ) {
  18091. if ( parent === null ) {
  18092. camera.matrixWorld.copy( camera.matrix );
  18093. } else {
  18094. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  18095. }
  18096. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  18097. }
  18098. this.setPoseTarget = function ( object ) {
  18099. if ( object !== undefined ) poseTarget = object;
  18100. };
  18101. this.getCamera = function ( camera ) {
  18102. if ( isPresenting() ) {
  18103. var parent = camera.parent;
  18104. var cameras = cameraVR.cameras;
  18105. var object = poseTarget || camera;
  18106. updateCamera( cameraVR, parent );
  18107. for ( var i = 0; i < cameras.length; i ++ ) {
  18108. updateCamera( cameras[ i ], parent );
  18109. }
  18110. // update camera and its children
  18111. object.matrixWorld.copy( cameraVR.matrixWorld );
  18112. var children = object.children;
  18113. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18114. children[ i ].updateMatrixWorld( true );
  18115. }
  18116. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  18117. return cameraVR;
  18118. }
  18119. return camera;
  18120. };
  18121. this.getCameraPose = function ( ) {
  18122. return pose;
  18123. };
  18124. this.isPresenting = isPresenting;
  18125. // Animation Loop
  18126. var onAnimationFrameCallback = null;
  18127. function onAnimationFrame( time, frame ) {
  18128. pose = frame.getDevicePose( frameOfReference );
  18129. if ( pose !== null ) {
  18130. var layer = session.baseLayer;
  18131. var views = frame.views;
  18132. for ( var i = 0; i < views.length; i ++ ) {
  18133. var view = views[ i ];
  18134. var viewport = layer.getViewport( view );
  18135. var viewMatrix = pose.getViewMatrix( view );
  18136. var camera = cameraVR.cameras[ i ];
  18137. camera.matrix.fromArray( viewMatrix ).getInverse( camera.matrix );
  18138. camera.projectionMatrix.fromArray( view.projectionMatrix );
  18139. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  18140. if ( i === 0 ) {
  18141. cameraVR.matrix.copy( camera.matrix );
  18142. }
  18143. }
  18144. }
  18145. //
  18146. for ( var i = 0; i < controllers.length; i ++ ) {
  18147. var controller = controllers[ i ];
  18148. var inputSource = inputSources[ i ];
  18149. if ( inputSource ) {
  18150. var inputPose = frame.getInputPose( inputSource, frameOfReference );
  18151. if ( inputPose !== null ) {
  18152. if ( 'targetRay' in inputPose ) {
  18153. controller.matrix.elements = inputPose.targetRay.transformMatrix;
  18154. } else if ( 'pointerMatrix' in inputPose ) {
  18155. // DEPRECATED
  18156. controller.matrix.elements = inputPose.pointerMatrix;
  18157. }
  18158. controller.matrix.decompose( controller.position, controller.rotation, controller.scale );
  18159. controller.visible = true;
  18160. continue;
  18161. }
  18162. }
  18163. controller.visible = false;
  18164. }
  18165. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  18166. }
  18167. var animation = new WebGLAnimation();
  18168. animation.setAnimationLoop( onAnimationFrame );
  18169. this.setAnimationLoop = function ( callback ) {
  18170. onAnimationFrameCallback = callback;
  18171. };
  18172. this.dispose = function () {};
  18173. // DEPRECATED
  18174. this.getStandingMatrix = function () {
  18175. console.warn( 'THREE.WebXRManager: getStandingMatrix() is no longer needed.' );
  18176. return new Matrix4();
  18177. };
  18178. this.submitFrame = function () {};
  18179. }
  18180. /**
  18181. * @author supereggbert / http://www.paulbrunt.co.uk/
  18182. * @author mrdoob / http://mrdoob.com/
  18183. * @author alteredq / http://alteredqualia.com/
  18184. * @author szimek / https://github.com/szimek/
  18185. * @author tschw
  18186. */
  18187. function WebGLRenderer( parameters ) {
  18188. console.log( 'THREE.WebGLRenderer', REVISION );
  18189. parameters = parameters || {};
  18190. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  18191. _context = parameters.context !== undefined ? parameters.context : null,
  18192. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  18193. _depth = parameters.depth !== undefined ? parameters.depth : true,
  18194. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  18195. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  18196. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  18197. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  18198. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  18199. var currentRenderList = null;
  18200. var currentRenderState = null;
  18201. // public properties
  18202. this.domElement = _canvas;
  18203. this.context = null;
  18204. // clearing
  18205. this.autoClear = true;
  18206. this.autoClearColor = true;
  18207. this.autoClearDepth = true;
  18208. this.autoClearStencil = true;
  18209. // scene graph
  18210. this.sortObjects = true;
  18211. // user-defined clipping
  18212. this.clippingPlanes = [];
  18213. this.localClippingEnabled = false;
  18214. // physically based shading
  18215. this.gammaFactor = 2.0; // for backwards compatibility
  18216. this.gammaInput = false;
  18217. this.gammaOutput = false;
  18218. // physical lights
  18219. this.physicallyCorrectLights = false;
  18220. // tone mapping
  18221. this.toneMapping = LinearToneMapping;
  18222. this.toneMappingExposure = 1.0;
  18223. this.toneMappingWhitePoint = 1.0;
  18224. // morphs
  18225. this.maxMorphTargets = 8;
  18226. this.maxMorphNormals = 4;
  18227. // internal properties
  18228. var _this = this,
  18229. _isContextLost = false,
  18230. // internal state cache
  18231. _framebuffer = null,
  18232. _currentRenderTarget = null,
  18233. _currentFramebuffer = null,
  18234. _currentMaterialId = - 1,
  18235. // geometry and program caching
  18236. _currentGeometryProgram = {
  18237. geometry: null,
  18238. program: null,
  18239. wireframe: false
  18240. },
  18241. _currentCamera = null,
  18242. _currentArrayCamera = null,
  18243. _currentViewport = new Vector4(),
  18244. _currentScissor = new Vector4(),
  18245. _currentScissorTest = null,
  18246. //
  18247. _usedTextureUnits = 0,
  18248. //
  18249. _width = _canvas.width,
  18250. _height = _canvas.height,
  18251. _pixelRatio = 1,
  18252. _viewport = new Vector4( 0, 0, _width, _height ),
  18253. _scissor = new Vector4( 0, 0, _width, _height ),
  18254. _scissorTest = false,
  18255. // frustum
  18256. _frustum = new Frustum(),
  18257. // clipping
  18258. _clipping = new WebGLClipping(),
  18259. _clippingEnabled = false,
  18260. _localClippingEnabled = false,
  18261. // camera matrices cache
  18262. _projScreenMatrix = new Matrix4(),
  18263. _vector3 = new Vector3();
  18264. function getTargetPixelRatio() {
  18265. return _currentRenderTarget === null ? _pixelRatio : 1;
  18266. }
  18267. // initialize
  18268. var _gl;
  18269. try {
  18270. var contextAttributes = {
  18271. alpha: _alpha,
  18272. depth: _depth,
  18273. stencil: _stencil,
  18274. antialias: _antialias,
  18275. premultipliedAlpha: _premultipliedAlpha,
  18276. preserveDrawingBuffer: _preserveDrawingBuffer,
  18277. powerPreference: _powerPreference
  18278. };
  18279. // event listeners must be registered before WebGL context is created, see #12753
  18280. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  18281. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  18282. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  18283. if ( _gl === null ) {
  18284. if ( _canvas.getContext( 'webgl' ) !== null ) {
  18285. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  18286. } else {
  18287. throw new Error( 'Error creating WebGL context.' );
  18288. }
  18289. }
  18290. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  18291. if ( _gl.getShaderPrecisionFormat === undefined ) {
  18292. _gl.getShaderPrecisionFormat = function () {
  18293. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  18294. };
  18295. }
  18296. } catch ( error ) {
  18297. console.error( 'THREE.WebGLRenderer: ' + error.message );
  18298. throw error;
  18299. }
  18300. var extensions, capabilities, state, info;
  18301. var properties, textures, attributes, geometries, objects;
  18302. var programCache, renderLists, renderStates;
  18303. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  18304. var utils;
  18305. function initGLContext() {
  18306. extensions = new WebGLExtensions( _gl );
  18307. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  18308. if ( ! capabilities.isWebGL2 ) {
  18309. extensions.get( 'WEBGL_depth_texture' );
  18310. extensions.get( 'OES_texture_float' );
  18311. extensions.get( 'OES_texture_half_float' );
  18312. extensions.get( 'OES_texture_half_float_linear' );
  18313. extensions.get( 'OES_standard_derivatives' );
  18314. extensions.get( 'OES_element_index_uint' );
  18315. extensions.get( 'ANGLE_instanced_arrays' );
  18316. }
  18317. extensions.get( 'OES_texture_float_linear' );
  18318. utils = new WebGLUtils( _gl, extensions, capabilities );
  18319. state = new WebGLState( _gl, extensions, utils, capabilities );
  18320. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  18321. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  18322. info = new WebGLInfo( _gl );
  18323. properties = new WebGLProperties();
  18324. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  18325. attributes = new WebGLAttributes( _gl );
  18326. geometries = new WebGLGeometries( _gl, attributes, info );
  18327. objects = new WebGLObjects( geometries, info );
  18328. morphtargets = new WebGLMorphtargets( _gl );
  18329. programCache = new WebGLPrograms( _this, extensions, capabilities );
  18330. renderLists = new WebGLRenderLists();
  18331. renderStates = new WebGLRenderStates();
  18332. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  18333. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  18334. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  18335. info.programs = programCache.programs;
  18336. _this.context = _gl;
  18337. _this.capabilities = capabilities;
  18338. _this.extensions = extensions;
  18339. _this.properties = properties;
  18340. _this.renderLists = renderLists;
  18341. _this.state = state;
  18342. _this.info = info;
  18343. }
  18344. initGLContext();
  18345. // vr
  18346. var vr = null;
  18347. if ( typeof navigator !== 'undefined' ) {
  18348. vr = ( 'xr' in navigator ) ? new WebXRManager( _this ) : new WebVRManager( _this );
  18349. }
  18350. this.vr = vr;
  18351. // shadow map
  18352. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  18353. this.shadowMap = shadowMap;
  18354. // API
  18355. this.getContext = function () {
  18356. return _gl;
  18357. };
  18358. this.getContextAttributes = function () {
  18359. return _gl.getContextAttributes();
  18360. };
  18361. this.forceContextLoss = function () {
  18362. var extension = extensions.get( 'WEBGL_lose_context' );
  18363. if ( extension ) extension.loseContext();
  18364. };
  18365. this.forceContextRestore = function () {
  18366. var extension = extensions.get( 'WEBGL_lose_context' );
  18367. if ( extension ) extension.restoreContext();
  18368. };
  18369. this.getPixelRatio = function () {
  18370. return _pixelRatio;
  18371. };
  18372. this.setPixelRatio = function ( value ) {
  18373. if ( value === undefined ) return;
  18374. _pixelRatio = value;
  18375. this.setSize( _width, _height, false );
  18376. };
  18377. this.getSize = function ( target ) {
  18378. if ( target === undefined ) {
  18379. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  18380. target = new Vector2();
  18381. }
  18382. return target.set( _width, _height );
  18383. };
  18384. this.setSize = function ( width, height, updateStyle ) {
  18385. if ( vr.isPresenting() ) {
  18386. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  18387. return;
  18388. }
  18389. _width = width;
  18390. _height = height;
  18391. _canvas.width = width * _pixelRatio;
  18392. _canvas.height = height * _pixelRatio;
  18393. if ( updateStyle !== false ) {
  18394. _canvas.style.width = width + 'px';
  18395. _canvas.style.height = height + 'px';
  18396. }
  18397. this.setViewport( 0, 0, width, height );
  18398. };
  18399. this.getDrawingBufferSize = function ( target ) {
  18400. if ( target === undefined ) {
  18401. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  18402. target = new Vector2();
  18403. }
  18404. return target.set( _width * _pixelRatio, _height * _pixelRatio );
  18405. };
  18406. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  18407. _width = width;
  18408. _height = height;
  18409. _pixelRatio = pixelRatio;
  18410. _canvas.width = width * pixelRatio;
  18411. _canvas.height = height * pixelRatio;
  18412. this.setViewport( 0, 0, width, height );
  18413. };
  18414. this.getCurrentViewport = function ( target ) {
  18415. if ( target === undefined ) {
  18416. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  18417. target = new Vector4();
  18418. }
  18419. return target.copy( _currentViewport );
  18420. };
  18421. this.getViewport = function ( target ) {
  18422. return target.copy( _viewport );
  18423. };
  18424. this.setViewport = function ( x, y, width, height ) {
  18425. if ( x.isVector4 ) {
  18426. _viewport.set( x.x, x.y, x.z, x.w );
  18427. } else {
  18428. _viewport.set( x, y, width, height );
  18429. }
  18430. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  18431. };
  18432. this.getScissor = function ( target ) {
  18433. return target.copy( _scissor );
  18434. };
  18435. this.setScissor = function ( x, y, width, height ) {
  18436. if ( x.isVector4 ) {
  18437. _scissor.set( x.x, x.y, x.z, x.w );
  18438. } else {
  18439. _scissor.set( x, y, width, height );
  18440. }
  18441. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  18442. };
  18443. this.getScissorTest = function () {
  18444. return _scissorTest;
  18445. };
  18446. this.setScissorTest = function ( boolean ) {
  18447. state.setScissorTest( _scissorTest = boolean );
  18448. };
  18449. // Clearing
  18450. this.getClearColor = function () {
  18451. return background.getClearColor();
  18452. };
  18453. this.setClearColor = function () {
  18454. background.setClearColor.apply( background, arguments );
  18455. };
  18456. this.getClearAlpha = function () {
  18457. return background.getClearAlpha();
  18458. };
  18459. this.setClearAlpha = function () {
  18460. background.setClearAlpha.apply( background, arguments );
  18461. };
  18462. this.clear = function ( color, depth, stencil ) {
  18463. var bits = 0;
  18464. if ( color === undefined || color ) bits |= 16384;
  18465. if ( depth === undefined || depth ) bits |= 256;
  18466. if ( stencil === undefined || stencil ) bits |= 1024;
  18467. _gl.clear( bits );
  18468. };
  18469. this.clearColor = function () {
  18470. this.clear( true, false, false );
  18471. };
  18472. this.clearDepth = function () {
  18473. this.clear( false, true, false );
  18474. };
  18475. this.clearStencil = function () {
  18476. this.clear( false, false, true );
  18477. };
  18478. //
  18479. this.dispose = function () {
  18480. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  18481. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  18482. renderLists.dispose();
  18483. renderStates.dispose();
  18484. properties.dispose();
  18485. objects.dispose();
  18486. vr.dispose();
  18487. animation.stop();
  18488. };
  18489. // Events
  18490. function onContextLost( event ) {
  18491. event.preventDefault();
  18492. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  18493. _isContextLost = true;
  18494. }
  18495. function onContextRestore( /* event */ ) {
  18496. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  18497. _isContextLost = false;
  18498. initGLContext();
  18499. }
  18500. function onMaterialDispose( event ) {
  18501. var material = event.target;
  18502. material.removeEventListener( 'dispose', onMaterialDispose );
  18503. deallocateMaterial( material );
  18504. }
  18505. // Buffer deallocation
  18506. function deallocateMaterial( material ) {
  18507. releaseMaterialProgramReference( material );
  18508. properties.remove( material );
  18509. }
  18510. function releaseMaterialProgramReference( material ) {
  18511. var programInfo = properties.get( material ).program;
  18512. material.program = undefined;
  18513. if ( programInfo !== undefined ) {
  18514. programCache.releaseProgram( programInfo );
  18515. }
  18516. }
  18517. // Buffer rendering
  18518. function renderObjectImmediate( object, program ) {
  18519. object.render( function ( object ) {
  18520. _this.renderBufferImmediate( object, program );
  18521. } );
  18522. }
  18523. this.renderBufferImmediate = function ( object, program ) {
  18524. state.initAttributes();
  18525. var buffers = properties.get( object );
  18526. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  18527. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  18528. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  18529. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  18530. var programAttributes = program.getAttributes();
  18531. if ( object.hasPositions ) {
  18532. _gl.bindBuffer( 34962, buffers.position );
  18533. _gl.bufferData( 34962, object.positionArray, 35048 );
  18534. state.enableAttribute( programAttributes.position );
  18535. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  18536. }
  18537. if ( object.hasNormals ) {
  18538. _gl.bindBuffer( 34962, buffers.normal );
  18539. _gl.bufferData( 34962, object.normalArray, 35048 );
  18540. state.enableAttribute( programAttributes.normal );
  18541. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  18542. }
  18543. if ( object.hasUvs ) {
  18544. _gl.bindBuffer( 34962, buffers.uv );
  18545. _gl.bufferData( 34962, object.uvArray, 35048 );
  18546. state.enableAttribute( programAttributes.uv );
  18547. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  18548. }
  18549. if ( object.hasColors ) {
  18550. _gl.bindBuffer( 34962, buffers.color );
  18551. _gl.bufferData( 34962, object.colorArray, 35048 );
  18552. state.enableAttribute( programAttributes.color );
  18553. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  18554. }
  18555. state.disableUnusedAttributes();
  18556. _gl.drawArrays( 4, 0, object.count );
  18557. object.count = 0;
  18558. };
  18559. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  18560. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  18561. state.setMaterial( material, frontFaceCW );
  18562. var program = setProgram( camera, fog, material, object );
  18563. var updateBuffers = false;
  18564. if ( _currentGeometryProgram.geometry !== geometry.id ||
  18565. _currentGeometryProgram.program !== program.id ||
  18566. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  18567. _currentGeometryProgram.geometry = geometry.id;
  18568. _currentGeometryProgram.program = program.id;
  18569. _currentGeometryProgram.wireframe = material.wireframe === true;
  18570. updateBuffers = true;
  18571. }
  18572. if ( object.morphTargetInfluences ) {
  18573. morphtargets.update( object, geometry, material, program );
  18574. updateBuffers = true;
  18575. }
  18576. //
  18577. var index = geometry.index;
  18578. var position = geometry.attributes.position;
  18579. var rangeFactor = 1;
  18580. if ( material.wireframe === true ) {
  18581. index = geometries.getWireframeAttribute( geometry );
  18582. rangeFactor = 2;
  18583. }
  18584. var attribute;
  18585. var renderer = bufferRenderer;
  18586. if ( index !== null ) {
  18587. attribute = attributes.get( index );
  18588. renderer = indexedBufferRenderer;
  18589. renderer.setIndex( attribute );
  18590. }
  18591. if ( updateBuffers ) {
  18592. setupVertexAttributes( material, program, geometry );
  18593. if ( index !== null ) {
  18594. _gl.bindBuffer( 34963, attribute.buffer );
  18595. }
  18596. }
  18597. //
  18598. var dataCount = Infinity;
  18599. if ( index !== null ) {
  18600. dataCount = index.count;
  18601. } else if ( position !== undefined ) {
  18602. dataCount = position.count;
  18603. }
  18604. var rangeStart = geometry.drawRange.start * rangeFactor;
  18605. var rangeCount = geometry.drawRange.count * rangeFactor;
  18606. var groupStart = group !== null ? group.start * rangeFactor : 0;
  18607. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  18608. var drawStart = Math.max( rangeStart, groupStart );
  18609. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  18610. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  18611. if ( drawCount === 0 ) return;
  18612. //
  18613. if ( object.isMesh ) {
  18614. if ( material.wireframe === true ) {
  18615. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  18616. renderer.setMode( 1 );
  18617. } else {
  18618. switch ( object.drawMode ) {
  18619. case TrianglesDrawMode:
  18620. renderer.setMode( 4 );
  18621. break;
  18622. case TriangleStripDrawMode:
  18623. renderer.setMode( 5 );
  18624. break;
  18625. case TriangleFanDrawMode:
  18626. renderer.setMode( 6 );
  18627. break;
  18628. }
  18629. }
  18630. } else if ( object.isLine ) {
  18631. var lineWidth = material.linewidth;
  18632. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  18633. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  18634. if ( object.isLineSegments ) {
  18635. renderer.setMode( 1 );
  18636. } else if ( object.isLineLoop ) {
  18637. renderer.setMode( 2 );
  18638. } else {
  18639. renderer.setMode( 3 );
  18640. }
  18641. } else if ( object.isPoints ) {
  18642. renderer.setMode( 0 );
  18643. } else if ( object.isSprite ) {
  18644. renderer.setMode( 4 );
  18645. }
  18646. if ( geometry && geometry.isInstancedBufferGeometry ) {
  18647. if ( geometry.maxInstancedCount > 0 ) {
  18648. renderer.renderInstances( geometry, drawStart, drawCount );
  18649. }
  18650. } else {
  18651. renderer.render( drawStart, drawCount );
  18652. }
  18653. };
  18654. function setupVertexAttributes( material, program, geometry ) {
  18655. if ( geometry && geometry.isInstancedBufferGeometry && ! capabilities.isWebGL2 ) {
  18656. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  18657. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  18658. return;
  18659. }
  18660. }
  18661. state.initAttributes();
  18662. var geometryAttributes = geometry.attributes;
  18663. var programAttributes = program.getAttributes();
  18664. var materialDefaultAttributeValues = material.defaultAttributeValues;
  18665. for ( var name in programAttributes ) {
  18666. var programAttribute = programAttributes[ name ];
  18667. if ( programAttribute >= 0 ) {
  18668. var geometryAttribute = geometryAttributes[ name ];
  18669. if ( geometryAttribute !== undefined ) {
  18670. var normalized = geometryAttribute.normalized;
  18671. var size = geometryAttribute.itemSize;
  18672. var attribute = attributes.get( geometryAttribute );
  18673. // TODO Attribute may not be available on context restore
  18674. if ( attribute === undefined ) continue;
  18675. var buffer = attribute.buffer;
  18676. var type = attribute.type;
  18677. var bytesPerElement = attribute.bytesPerElement;
  18678. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  18679. var data = geometryAttribute.data;
  18680. var stride = data.stride;
  18681. var offset = geometryAttribute.offset;
  18682. if ( data && data.isInstancedInterleavedBuffer ) {
  18683. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  18684. if ( geometry.maxInstancedCount === undefined ) {
  18685. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  18686. }
  18687. } else {
  18688. state.enableAttribute( programAttribute );
  18689. }
  18690. _gl.bindBuffer( 34962, buffer );
  18691. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  18692. } else {
  18693. if ( geometryAttribute.isInstancedBufferAttribute ) {
  18694. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  18695. if ( geometry.maxInstancedCount === undefined ) {
  18696. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  18697. }
  18698. } else {
  18699. state.enableAttribute( programAttribute );
  18700. }
  18701. _gl.bindBuffer( 34962, buffer );
  18702. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  18703. }
  18704. } else if ( materialDefaultAttributeValues !== undefined ) {
  18705. var value = materialDefaultAttributeValues[ name ];
  18706. if ( value !== undefined ) {
  18707. switch ( value.length ) {
  18708. case 2:
  18709. _gl.vertexAttrib2fv( programAttribute, value );
  18710. break;
  18711. case 3:
  18712. _gl.vertexAttrib3fv( programAttribute, value );
  18713. break;
  18714. case 4:
  18715. _gl.vertexAttrib4fv( programAttribute, value );
  18716. break;
  18717. default:
  18718. _gl.vertexAttrib1fv( programAttribute, value );
  18719. }
  18720. }
  18721. }
  18722. }
  18723. }
  18724. state.disableUnusedAttributes();
  18725. }
  18726. // Compile
  18727. this.compile = function ( scene, camera ) {
  18728. currentRenderState = renderStates.get( scene, camera );
  18729. currentRenderState.init();
  18730. scene.traverse( function ( object ) {
  18731. if ( object.isLight ) {
  18732. currentRenderState.pushLight( object );
  18733. if ( object.castShadow ) {
  18734. currentRenderState.pushShadow( object );
  18735. }
  18736. }
  18737. } );
  18738. currentRenderState.setupLights( camera );
  18739. scene.traverse( function ( object ) {
  18740. if ( object.material ) {
  18741. if ( Array.isArray( object.material ) ) {
  18742. for ( var i = 0; i < object.material.length; i ++ ) {
  18743. initMaterial( object.material[ i ], scene.fog, object );
  18744. }
  18745. } else {
  18746. initMaterial( object.material, scene.fog, object );
  18747. }
  18748. }
  18749. } );
  18750. };
  18751. // Animation Loop
  18752. var onAnimationFrameCallback = null;
  18753. function onAnimationFrame( time ) {
  18754. if ( vr.isPresenting() ) return;
  18755. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  18756. }
  18757. var animation = new WebGLAnimation();
  18758. animation.setAnimationLoop( onAnimationFrame );
  18759. if ( typeof window !== 'undefined' ) animation.setContext( window );
  18760. this.setAnimationLoop = function ( callback ) {
  18761. onAnimationFrameCallback = callback;
  18762. vr.setAnimationLoop( callback );
  18763. animation.start();
  18764. };
  18765. // Rendering
  18766. this.render = function ( scene, camera ) {
  18767. var renderTarget, forceClear;
  18768. if ( arguments[ 2 ] !== undefined ) {
  18769. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  18770. renderTarget = arguments[ 2 ];
  18771. }
  18772. if ( arguments[ 3 ] !== undefined ) {
  18773. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  18774. forceClear = arguments[ 3 ];
  18775. }
  18776. if ( ! ( camera && camera.isCamera ) ) {
  18777. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  18778. return;
  18779. }
  18780. if ( _isContextLost ) return;
  18781. // reset caching for this frame
  18782. _currentGeometryProgram.geometry = null;
  18783. _currentGeometryProgram.program = null;
  18784. _currentGeometryProgram.wireframe = false;
  18785. _currentMaterialId = - 1;
  18786. _currentCamera = null;
  18787. // update scene graph
  18788. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  18789. // update camera matrices and frustum
  18790. if ( camera.parent === null ) camera.updateMatrixWorld();
  18791. if ( vr.enabled ) {
  18792. camera = vr.getCamera( camera );
  18793. }
  18794. //
  18795. currentRenderState = renderStates.get( scene, camera );
  18796. currentRenderState.init();
  18797. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  18798. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  18799. _frustum.setFromMatrix( _projScreenMatrix );
  18800. _localClippingEnabled = this.localClippingEnabled;
  18801. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  18802. currentRenderList = renderLists.get( scene, camera );
  18803. currentRenderList.init();
  18804. projectObject( scene, camera, 0, _this.sortObjects );
  18805. if ( _this.sortObjects === true ) {
  18806. currentRenderList.sort();
  18807. }
  18808. //
  18809. if ( _clippingEnabled ) _clipping.beginShadows();
  18810. var shadowsArray = currentRenderState.state.shadowsArray;
  18811. shadowMap.render( shadowsArray, scene, camera );
  18812. currentRenderState.setupLights( camera );
  18813. if ( _clippingEnabled ) _clipping.endShadows();
  18814. //
  18815. if ( this.info.autoReset ) this.info.reset();
  18816. if ( renderTarget !== undefined ) {
  18817. this.setRenderTarget( renderTarget );
  18818. }
  18819. //
  18820. background.render( currentRenderList, scene, camera, forceClear );
  18821. // render scene
  18822. var opaqueObjects = currentRenderList.opaque;
  18823. var transparentObjects = currentRenderList.transparent;
  18824. if ( scene.overrideMaterial ) {
  18825. var overrideMaterial = scene.overrideMaterial;
  18826. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  18827. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  18828. } else {
  18829. // opaque pass (front-to-back order)
  18830. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  18831. // transparent pass (back-to-front order)
  18832. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  18833. }
  18834. //
  18835. scene.onAfterRender( _this, scene, camera );
  18836. //
  18837. if ( _currentRenderTarget !== null ) {
  18838. // Generate mipmap if we're using any kind of mipmap filtering
  18839. textures.updateRenderTargetMipmap( _currentRenderTarget );
  18840. // resolve multisample renderbuffers to a single-sample texture if necessary
  18841. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  18842. }
  18843. // Ensure depth buffer writing is enabled so it can be cleared on next render
  18844. state.buffers.depth.setTest( true );
  18845. state.buffers.depth.setMask( true );
  18846. state.buffers.color.setMask( true );
  18847. state.setPolygonOffset( false );
  18848. if ( vr.enabled ) {
  18849. vr.submitFrame();
  18850. }
  18851. // _gl.finish();
  18852. currentRenderList = null;
  18853. currentRenderState = null;
  18854. };
  18855. function projectObject( object, camera, groupOrder, sortObjects ) {
  18856. if ( object.visible === false ) return;
  18857. var visible = object.layers.test( camera.layers );
  18858. if ( visible ) {
  18859. if ( object.isGroup ) {
  18860. groupOrder = object.renderOrder;
  18861. } else if ( object.isLight ) {
  18862. currentRenderState.pushLight( object );
  18863. if ( object.castShadow ) {
  18864. currentRenderState.pushShadow( object );
  18865. }
  18866. } else if ( object.isSprite ) {
  18867. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  18868. if ( sortObjects ) {
  18869. _vector3.setFromMatrixPosition( object.matrixWorld )
  18870. .applyMatrix4( _projScreenMatrix );
  18871. }
  18872. var geometry = objects.update( object );
  18873. var material = object.material;
  18874. if ( material.visible ) {
  18875. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  18876. }
  18877. }
  18878. } else if ( object.isImmediateRenderObject ) {
  18879. if ( sortObjects ) {
  18880. _vector3.setFromMatrixPosition( object.matrixWorld )
  18881. .applyMatrix4( _projScreenMatrix );
  18882. }
  18883. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  18884. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  18885. if ( object.isSkinnedMesh ) {
  18886. object.skeleton.update();
  18887. }
  18888. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  18889. if ( sortObjects ) {
  18890. _vector3.setFromMatrixPosition( object.matrixWorld )
  18891. .applyMatrix4( _projScreenMatrix );
  18892. }
  18893. var geometry = objects.update( object );
  18894. var material = object.material;
  18895. if ( Array.isArray( material ) ) {
  18896. var groups = geometry.groups;
  18897. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  18898. var group = groups[ i ];
  18899. var groupMaterial = material[ group.materialIndex ];
  18900. if ( groupMaterial && groupMaterial.visible ) {
  18901. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  18902. }
  18903. }
  18904. } else if ( material.visible ) {
  18905. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  18906. }
  18907. }
  18908. }
  18909. }
  18910. var children = object.children;
  18911. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18912. projectObject( children[ i ], camera, groupOrder, sortObjects );
  18913. }
  18914. }
  18915. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  18916. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  18917. var renderItem = renderList[ i ];
  18918. var object = renderItem.object;
  18919. var geometry = renderItem.geometry;
  18920. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  18921. var group = renderItem.group;
  18922. if ( camera.isArrayCamera ) {
  18923. _currentArrayCamera = camera;
  18924. var cameras = camera.cameras;
  18925. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  18926. var camera2 = cameras[ j ];
  18927. if ( object.layers.test( camera2.layers ) ) {
  18928. if ( 'viewport' in camera2 ) { // XR
  18929. state.viewport( _currentViewport.copy( camera2.viewport ) );
  18930. } else {
  18931. var bounds = camera2.bounds;
  18932. var x = bounds.x * _width;
  18933. var y = bounds.y * _height;
  18934. var width = bounds.z * _width;
  18935. var height = bounds.w * _height;
  18936. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  18937. }
  18938. currentRenderState.setupLights( camera2 );
  18939. renderObject( object, scene, camera2, geometry, material, group );
  18940. }
  18941. }
  18942. } else {
  18943. _currentArrayCamera = null;
  18944. renderObject( object, scene, camera, geometry, material, group );
  18945. }
  18946. }
  18947. }
  18948. function renderObject( object, scene, camera, geometry, material, group ) {
  18949. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  18950. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  18951. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  18952. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  18953. if ( object.isImmediateRenderObject ) {
  18954. state.setMaterial( material );
  18955. var program = setProgram( camera, scene.fog, material, object );
  18956. _currentGeometryProgram.geometry = null;
  18957. _currentGeometryProgram.program = null;
  18958. _currentGeometryProgram.wireframe = false;
  18959. renderObjectImmediate( object, program );
  18960. } else {
  18961. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  18962. }
  18963. object.onAfterRender( _this, scene, camera, geometry, material, group );
  18964. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  18965. }
  18966. function initMaterial( material, fog, object ) {
  18967. var materialProperties = properties.get( material );
  18968. var lights = currentRenderState.state.lights;
  18969. var shadowsArray = currentRenderState.state.shadowsArray;
  18970. var lightsHash = materialProperties.lightsHash;
  18971. var lightsStateHash = lights.state.hash;
  18972. var parameters = programCache.getParameters(
  18973. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  18974. var code = programCache.getProgramCode( material, parameters );
  18975. var program = materialProperties.program;
  18976. var programChange = true;
  18977. if ( program === undefined ) {
  18978. // new material
  18979. material.addEventListener( 'dispose', onMaterialDispose );
  18980. } else if ( program.code !== code ) {
  18981. // changed glsl or parameters
  18982. releaseMaterialProgramReference( material );
  18983. } else if ( lightsHash.stateID !== lightsStateHash.stateID ||
  18984. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  18985. lightsHash.pointLength !== lightsStateHash.pointLength ||
  18986. lightsHash.spotLength !== lightsStateHash.spotLength ||
  18987. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  18988. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  18989. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) {
  18990. lightsHash.stateID = lightsStateHash.stateID;
  18991. lightsHash.directionalLength = lightsStateHash.directionalLength;
  18992. lightsHash.pointLength = lightsStateHash.pointLength;
  18993. lightsHash.spotLength = lightsStateHash.spotLength;
  18994. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  18995. lightsHash.hemiLength = lightsStateHash.hemiLength;
  18996. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  18997. programChange = false;
  18998. } else if ( parameters.shaderID !== undefined ) {
  18999. // same glsl and uniform list
  19000. return;
  19001. } else {
  19002. // only rebuild uniform list
  19003. programChange = false;
  19004. }
  19005. if ( programChange ) {
  19006. if ( parameters.shaderID ) {
  19007. var shader = ShaderLib[ parameters.shaderID ];
  19008. materialProperties.shader = {
  19009. name: material.type,
  19010. uniforms: cloneUniforms( shader.uniforms ),
  19011. vertexShader: shader.vertexShader,
  19012. fragmentShader: shader.fragmentShader
  19013. };
  19014. } else {
  19015. materialProperties.shader = {
  19016. name: material.type,
  19017. uniforms: material.uniforms,
  19018. vertexShader: material.vertexShader,
  19019. fragmentShader: material.fragmentShader
  19020. };
  19021. }
  19022. material.onBeforeCompile( materialProperties.shader, _this );
  19023. // Computing code again as onBeforeCompile may have changed the shaders
  19024. code = programCache.getProgramCode( material, parameters );
  19025. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  19026. materialProperties.program = program;
  19027. material.program = program;
  19028. }
  19029. var programAttributes = program.getAttributes();
  19030. if ( material.morphTargets ) {
  19031. material.numSupportedMorphTargets = 0;
  19032. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  19033. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  19034. material.numSupportedMorphTargets ++;
  19035. }
  19036. }
  19037. }
  19038. if ( material.morphNormals ) {
  19039. material.numSupportedMorphNormals = 0;
  19040. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  19041. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  19042. material.numSupportedMorphNormals ++;
  19043. }
  19044. }
  19045. }
  19046. var uniforms = materialProperties.shader.uniforms;
  19047. if ( ! material.isShaderMaterial &&
  19048. ! material.isRawShaderMaterial ||
  19049. material.clipping === true ) {
  19050. materialProperties.numClippingPlanes = _clipping.numPlanes;
  19051. materialProperties.numIntersection = _clipping.numIntersection;
  19052. uniforms.clippingPlanes = _clipping.uniform;
  19053. }
  19054. materialProperties.fog = fog;
  19055. // store the light setup it was created for
  19056. if ( lightsHash === undefined ) {
  19057. materialProperties.lightsHash = lightsHash = {};
  19058. }
  19059. lightsHash.stateID = lightsStateHash.stateID;
  19060. lightsHash.directionalLength = lightsStateHash.directionalLength;
  19061. lightsHash.pointLength = lightsStateHash.pointLength;
  19062. lightsHash.spotLength = lightsStateHash.spotLength;
  19063. lightsHash.rectAreaLength = lightsStateHash.rectAreaLength;
  19064. lightsHash.hemiLength = lightsStateHash.hemiLength;
  19065. lightsHash.shadowsLength = lightsStateHash.shadowsLength;
  19066. if ( material.lights ) {
  19067. // wire up the material to this renderer's lighting state
  19068. uniforms.ambientLightColor.value = lights.state.ambient;
  19069. uniforms.directionalLights.value = lights.state.directional;
  19070. uniforms.spotLights.value = lights.state.spot;
  19071. uniforms.rectAreaLights.value = lights.state.rectArea;
  19072. uniforms.pointLights.value = lights.state.point;
  19073. uniforms.hemisphereLights.value = lights.state.hemi;
  19074. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  19075. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  19076. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  19077. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  19078. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  19079. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  19080. // TODO (abelnation): add area lights shadow info to uniforms
  19081. }
  19082. var progUniforms = materialProperties.program.getUniforms(),
  19083. uniformsList =
  19084. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  19085. materialProperties.uniformsList = uniformsList;
  19086. }
  19087. function setProgram( camera, fog, material, object ) {
  19088. _usedTextureUnits = 0;
  19089. var materialProperties = properties.get( material );
  19090. var lights = currentRenderState.state.lights;
  19091. var lightsHash = materialProperties.lightsHash;
  19092. var lightsStateHash = lights.state.hash;
  19093. if ( _clippingEnabled ) {
  19094. if ( _localClippingEnabled || camera !== _currentCamera ) {
  19095. var useCache =
  19096. camera === _currentCamera &&
  19097. material.id === _currentMaterialId;
  19098. // we might want to call this function with some ClippingGroup
  19099. // object instead of the material, once it becomes feasible
  19100. // (#8465, #8379)
  19101. _clipping.setState(
  19102. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  19103. camera, materialProperties, useCache );
  19104. }
  19105. }
  19106. if ( material.needsUpdate === false ) {
  19107. if ( materialProperties.program === undefined ) {
  19108. material.needsUpdate = true;
  19109. } else if ( material.fog && materialProperties.fog !== fog ) {
  19110. material.needsUpdate = true;
  19111. } else if ( material.lights && ( lightsHash.stateID !== lightsStateHash.stateID ||
  19112. lightsHash.directionalLength !== lightsStateHash.directionalLength ||
  19113. lightsHash.pointLength !== lightsStateHash.pointLength ||
  19114. lightsHash.spotLength !== lightsStateHash.spotLength ||
  19115. lightsHash.rectAreaLength !== lightsStateHash.rectAreaLength ||
  19116. lightsHash.hemiLength !== lightsStateHash.hemiLength ||
  19117. lightsHash.shadowsLength !== lightsStateHash.shadowsLength ) ) {
  19118. material.needsUpdate = true;
  19119. } else if ( materialProperties.numClippingPlanes !== undefined &&
  19120. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  19121. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  19122. material.needsUpdate = true;
  19123. }
  19124. }
  19125. if ( material.needsUpdate ) {
  19126. initMaterial( material, fog, object );
  19127. material.needsUpdate = false;
  19128. }
  19129. var refreshProgram = false;
  19130. var refreshMaterial = false;
  19131. var refreshLights = false;
  19132. var program = materialProperties.program,
  19133. p_uniforms = program.getUniforms(),
  19134. m_uniforms = materialProperties.shader.uniforms;
  19135. if ( state.useProgram( program.program ) ) {
  19136. refreshProgram = true;
  19137. refreshMaterial = true;
  19138. refreshLights = true;
  19139. }
  19140. if ( material.id !== _currentMaterialId ) {
  19141. _currentMaterialId = material.id;
  19142. refreshMaterial = true;
  19143. }
  19144. if ( refreshProgram || _currentCamera !== camera ) {
  19145. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  19146. if ( capabilities.logarithmicDepthBuffer ) {
  19147. p_uniforms.setValue( _gl, 'logDepthBufFC',
  19148. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  19149. }
  19150. if ( _currentCamera !== camera ) {
  19151. _currentCamera = camera;
  19152. // lighting uniforms depend on the camera so enforce an update
  19153. // now, in case this material supports lights - or later, when
  19154. // the next material that does gets activated:
  19155. refreshMaterial = true; // set to true on material change
  19156. refreshLights = true; // remains set until update done
  19157. }
  19158. // load material specific uniforms
  19159. // (shader material also gets them for the sake of genericity)
  19160. if ( material.isShaderMaterial ||
  19161. material.isMeshPhongMaterial ||
  19162. material.isMeshStandardMaterial ||
  19163. material.envMap ) {
  19164. var uCamPos = p_uniforms.map.cameraPosition;
  19165. if ( uCamPos !== undefined ) {
  19166. uCamPos.setValue( _gl,
  19167. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  19168. }
  19169. }
  19170. if ( material.isMeshPhongMaterial ||
  19171. material.isMeshLambertMaterial ||
  19172. material.isMeshBasicMaterial ||
  19173. material.isMeshStandardMaterial ||
  19174. material.isShaderMaterial ||
  19175. material.skinning ) {
  19176. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  19177. }
  19178. }
  19179. // skinning uniforms must be set even if material didn't change
  19180. // auto-setting of texture unit for bone texture must go before other textures
  19181. // not sure why, but otherwise weird things happen
  19182. if ( material.skinning ) {
  19183. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  19184. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  19185. var skeleton = object.skeleton;
  19186. if ( skeleton ) {
  19187. var bones = skeleton.bones;
  19188. if ( capabilities.floatVertexTextures ) {
  19189. if ( skeleton.boneTexture === undefined ) {
  19190. // layout (1 matrix = 4 pixels)
  19191. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19192. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19193. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19194. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19195. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19196. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  19197. size = _Math.ceilPowerOfTwo( size );
  19198. size = Math.max( size, 4 );
  19199. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19200. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  19201. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19202. boneTexture.needsUpdate = true;
  19203. skeleton.boneMatrices = boneMatrices;
  19204. skeleton.boneTexture = boneTexture;
  19205. skeleton.boneTextureSize = size;
  19206. }
  19207. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  19208. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  19209. } else {
  19210. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  19211. }
  19212. }
  19213. }
  19214. if ( refreshMaterial ) {
  19215. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  19216. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  19217. if ( material.lights ) {
  19218. // the current material requires lighting info
  19219. // note: all lighting uniforms are always set correctly
  19220. // they simply reference the renderer's state for their
  19221. // values
  19222. //
  19223. // use the current material's .needsUpdate flags to set
  19224. // the GL state when required
  19225. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  19226. }
  19227. // refresh uniforms common to several materials
  19228. if ( fog && material.fog ) {
  19229. refreshUniformsFog( m_uniforms, fog );
  19230. }
  19231. if ( material.isMeshBasicMaterial ) {
  19232. refreshUniformsCommon( m_uniforms, material );
  19233. } else if ( material.isMeshLambertMaterial ) {
  19234. refreshUniformsCommon( m_uniforms, material );
  19235. refreshUniformsLambert( m_uniforms, material );
  19236. } else if ( material.isMeshPhongMaterial ) {
  19237. refreshUniformsCommon( m_uniforms, material );
  19238. if ( material.isMeshToonMaterial ) {
  19239. refreshUniformsToon( m_uniforms, material );
  19240. } else {
  19241. refreshUniformsPhong( m_uniforms, material );
  19242. }
  19243. } else if ( material.isMeshStandardMaterial ) {
  19244. refreshUniformsCommon( m_uniforms, material );
  19245. if ( material.isMeshPhysicalMaterial ) {
  19246. refreshUniformsPhysical( m_uniforms, material );
  19247. } else {
  19248. refreshUniformsStandard( m_uniforms, material );
  19249. }
  19250. } else if ( material.isMeshMatcapMaterial ) {
  19251. refreshUniformsCommon( m_uniforms, material );
  19252. refreshUniformsMatcap( m_uniforms, material );
  19253. } else if ( material.isMeshDepthMaterial ) {
  19254. refreshUniformsCommon( m_uniforms, material );
  19255. refreshUniformsDepth( m_uniforms, material );
  19256. } else if ( material.isMeshDistanceMaterial ) {
  19257. refreshUniformsCommon( m_uniforms, material );
  19258. refreshUniformsDistance( m_uniforms, material );
  19259. } else if ( material.isMeshNormalMaterial ) {
  19260. refreshUniformsCommon( m_uniforms, material );
  19261. refreshUniformsNormal( m_uniforms, material );
  19262. } else if ( material.isLineBasicMaterial ) {
  19263. refreshUniformsLine( m_uniforms, material );
  19264. if ( material.isLineDashedMaterial ) {
  19265. refreshUniformsDash( m_uniforms, material );
  19266. }
  19267. } else if ( material.isPointsMaterial ) {
  19268. refreshUniformsPoints( m_uniforms, material );
  19269. } else if ( material.isSpriteMaterial ) {
  19270. refreshUniformsSprites( m_uniforms, material );
  19271. } else if ( material.isShadowMaterial ) {
  19272. m_uniforms.color.value = material.color;
  19273. m_uniforms.opacity.value = material.opacity;
  19274. }
  19275. // RectAreaLight Texture
  19276. // TODO (mrdoob): Find a nicer implementation
  19277. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  19278. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  19279. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  19280. }
  19281. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  19282. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, _this );
  19283. material.uniformsNeedUpdate = false;
  19284. }
  19285. if ( material.isSpriteMaterial ) {
  19286. p_uniforms.setValue( _gl, 'center', object.center );
  19287. }
  19288. // common matrices
  19289. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  19290. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  19291. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  19292. return program;
  19293. }
  19294. // Uniforms (refresh uniforms objects)
  19295. function refreshUniformsCommon( uniforms, material ) {
  19296. uniforms.opacity.value = material.opacity;
  19297. if ( material.color ) {
  19298. uniforms.diffuse.value = material.color;
  19299. }
  19300. if ( material.emissive ) {
  19301. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  19302. }
  19303. if ( material.map ) {
  19304. uniforms.map.value = material.map;
  19305. }
  19306. if ( material.alphaMap ) {
  19307. uniforms.alphaMap.value = material.alphaMap;
  19308. }
  19309. if ( material.specularMap ) {
  19310. uniforms.specularMap.value = material.specularMap;
  19311. }
  19312. if ( material.envMap ) {
  19313. uniforms.envMap.value = material.envMap;
  19314. // don't flip CubeTexture envMaps, flip everything else:
  19315. // WebGLRenderTargetCube will be flipped for backwards compatibility
  19316. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  19317. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  19318. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  19319. uniforms.reflectivity.value = material.reflectivity;
  19320. uniforms.refractionRatio.value = material.refractionRatio;
  19321. uniforms.maxMipLevel.value = properties.get( material.envMap ).__maxMipLevel;
  19322. }
  19323. if ( material.lightMap ) {
  19324. uniforms.lightMap.value = material.lightMap;
  19325. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  19326. }
  19327. if ( material.aoMap ) {
  19328. uniforms.aoMap.value = material.aoMap;
  19329. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  19330. }
  19331. // uv repeat and offset setting priorities
  19332. // 1. color map
  19333. // 2. specular map
  19334. // 3. normal map
  19335. // 4. bump map
  19336. // 5. alpha map
  19337. // 6. emissive map
  19338. var uvScaleMap;
  19339. if ( material.map ) {
  19340. uvScaleMap = material.map;
  19341. } else if ( material.specularMap ) {
  19342. uvScaleMap = material.specularMap;
  19343. } else if ( material.displacementMap ) {
  19344. uvScaleMap = material.displacementMap;
  19345. } else if ( material.normalMap ) {
  19346. uvScaleMap = material.normalMap;
  19347. } else if ( material.bumpMap ) {
  19348. uvScaleMap = material.bumpMap;
  19349. } else if ( material.roughnessMap ) {
  19350. uvScaleMap = material.roughnessMap;
  19351. } else if ( material.metalnessMap ) {
  19352. uvScaleMap = material.metalnessMap;
  19353. } else if ( material.alphaMap ) {
  19354. uvScaleMap = material.alphaMap;
  19355. } else if ( material.emissiveMap ) {
  19356. uvScaleMap = material.emissiveMap;
  19357. }
  19358. if ( uvScaleMap !== undefined ) {
  19359. // backwards compatibility
  19360. if ( uvScaleMap.isWebGLRenderTarget ) {
  19361. uvScaleMap = uvScaleMap.texture;
  19362. }
  19363. if ( uvScaleMap.matrixAutoUpdate === true ) {
  19364. uvScaleMap.updateMatrix();
  19365. }
  19366. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  19367. }
  19368. }
  19369. function refreshUniformsLine( uniforms, material ) {
  19370. uniforms.diffuse.value = material.color;
  19371. uniforms.opacity.value = material.opacity;
  19372. }
  19373. function refreshUniformsDash( uniforms, material ) {
  19374. uniforms.dashSize.value = material.dashSize;
  19375. uniforms.totalSize.value = material.dashSize + material.gapSize;
  19376. uniforms.scale.value = material.scale;
  19377. }
  19378. function refreshUniformsPoints( uniforms, material ) {
  19379. uniforms.diffuse.value = material.color;
  19380. uniforms.opacity.value = material.opacity;
  19381. uniforms.size.value = material.size * _pixelRatio;
  19382. uniforms.scale.value = _height * 0.5;
  19383. uniforms.map.value = material.map;
  19384. if ( material.map !== null ) {
  19385. if ( material.map.matrixAutoUpdate === true ) {
  19386. material.map.updateMatrix();
  19387. }
  19388. uniforms.uvTransform.value.copy( material.map.matrix );
  19389. }
  19390. }
  19391. function refreshUniformsSprites( uniforms, material ) {
  19392. uniforms.diffuse.value = material.color;
  19393. uniforms.opacity.value = material.opacity;
  19394. uniforms.rotation.value = material.rotation;
  19395. uniforms.map.value = material.map;
  19396. if ( material.map !== null ) {
  19397. if ( material.map.matrixAutoUpdate === true ) {
  19398. material.map.updateMatrix();
  19399. }
  19400. uniforms.uvTransform.value.copy( material.map.matrix );
  19401. }
  19402. }
  19403. function refreshUniformsFog( uniforms, fog ) {
  19404. uniforms.fogColor.value = fog.color;
  19405. if ( fog.isFog ) {
  19406. uniforms.fogNear.value = fog.near;
  19407. uniforms.fogFar.value = fog.far;
  19408. } else if ( fog.isFogExp2 ) {
  19409. uniforms.fogDensity.value = fog.density;
  19410. }
  19411. }
  19412. function refreshUniformsLambert( uniforms, material ) {
  19413. if ( material.emissiveMap ) {
  19414. uniforms.emissiveMap.value = material.emissiveMap;
  19415. }
  19416. }
  19417. function refreshUniformsPhong( uniforms, material ) {
  19418. uniforms.specular.value = material.specular;
  19419. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  19420. if ( material.emissiveMap ) {
  19421. uniforms.emissiveMap.value = material.emissiveMap;
  19422. }
  19423. if ( material.bumpMap ) {
  19424. uniforms.bumpMap.value = material.bumpMap;
  19425. uniforms.bumpScale.value = material.bumpScale;
  19426. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19427. }
  19428. if ( material.normalMap ) {
  19429. uniforms.normalMap.value = material.normalMap;
  19430. uniforms.normalScale.value.copy( material.normalScale );
  19431. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19432. }
  19433. if ( material.displacementMap ) {
  19434. uniforms.displacementMap.value = material.displacementMap;
  19435. uniforms.displacementScale.value = material.displacementScale;
  19436. uniforms.displacementBias.value = material.displacementBias;
  19437. }
  19438. }
  19439. function refreshUniformsToon( uniforms, material ) {
  19440. refreshUniformsPhong( uniforms, material );
  19441. if ( material.gradientMap ) {
  19442. uniforms.gradientMap.value = material.gradientMap;
  19443. }
  19444. }
  19445. function refreshUniformsStandard( uniforms, material ) {
  19446. uniforms.roughness.value = material.roughness;
  19447. uniforms.metalness.value = material.metalness;
  19448. if ( material.roughnessMap ) {
  19449. uniforms.roughnessMap.value = material.roughnessMap;
  19450. }
  19451. if ( material.metalnessMap ) {
  19452. uniforms.metalnessMap.value = material.metalnessMap;
  19453. }
  19454. if ( material.emissiveMap ) {
  19455. uniforms.emissiveMap.value = material.emissiveMap;
  19456. }
  19457. if ( material.bumpMap ) {
  19458. uniforms.bumpMap.value = material.bumpMap;
  19459. uniforms.bumpScale.value = material.bumpScale;
  19460. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19461. }
  19462. if ( material.normalMap ) {
  19463. uniforms.normalMap.value = material.normalMap;
  19464. uniforms.normalScale.value.copy( material.normalScale );
  19465. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19466. }
  19467. if ( material.displacementMap ) {
  19468. uniforms.displacementMap.value = material.displacementMap;
  19469. uniforms.displacementScale.value = material.displacementScale;
  19470. uniforms.displacementBias.value = material.displacementBias;
  19471. }
  19472. if ( material.envMap ) {
  19473. //uniforms.envMap.value = material.envMap; // part of uniforms common
  19474. uniforms.envMapIntensity.value = material.envMapIntensity;
  19475. }
  19476. }
  19477. function refreshUniformsPhysical( uniforms, material ) {
  19478. refreshUniformsStandard( uniforms, material );
  19479. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  19480. uniforms.clearCoat.value = material.clearCoat;
  19481. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  19482. }
  19483. function refreshUniformsMatcap( uniforms, material ) {
  19484. if ( material.matcap ) {
  19485. uniforms.matcap.value = material.matcap;
  19486. }
  19487. if ( material.bumpMap ) {
  19488. uniforms.bumpMap.value = material.bumpMap;
  19489. uniforms.bumpScale.value = material.bumpScale;
  19490. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19491. }
  19492. if ( material.normalMap ) {
  19493. uniforms.normalMap.value = material.normalMap;
  19494. uniforms.normalScale.value.copy( material.normalScale );
  19495. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19496. }
  19497. if ( material.displacementMap ) {
  19498. uniforms.displacementMap.value = material.displacementMap;
  19499. uniforms.displacementScale.value = material.displacementScale;
  19500. uniforms.displacementBias.value = material.displacementBias;
  19501. }
  19502. }
  19503. function refreshUniformsDepth( uniforms, material ) {
  19504. if ( material.displacementMap ) {
  19505. uniforms.displacementMap.value = material.displacementMap;
  19506. uniforms.displacementScale.value = material.displacementScale;
  19507. uniforms.displacementBias.value = material.displacementBias;
  19508. }
  19509. }
  19510. function refreshUniformsDistance( uniforms, material ) {
  19511. if ( material.displacementMap ) {
  19512. uniforms.displacementMap.value = material.displacementMap;
  19513. uniforms.displacementScale.value = material.displacementScale;
  19514. uniforms.displacementBias.value = material.displacementBias;
  19515. }
  19516. uniforms.referencePosition.value.copy( material.referencePosition );
  19517. uniforms.nearDistance.value = material.nearDistance;
  19518. uniforms.farDistance.value = material.farDistance;
  19519. }
  19520. function refreshUniformsNormal( uniforms, material ) {
  19521. if ( material.bumpMap ) {
  19522. uniforms.bumpMap.value = material.bumpMap;
  19523. uniforms.bumpScale.value = material.bumpScale;
  19524. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  19525. }
  19526. if ( material.normalMap ) {
  19527. uniforms.normalMap.value = material.normalMap;
  19528. uniforms.normalScale.value.copy( material.normalScale );
  19529. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  19530. }
  19531. if ( material.displacementMap ) {
  19532. uniforms.displacementMap.value = material.displacementMap;
  19533. uniforms.displacementScale.value = material.displacementScale;
  19534. uniforms.displacementBias.value = material.displacementBias;
  19535. }
  19536. }
  19537. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  19538. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  19539. uniforms.ambientLightColor.needsUpdate = value;
  19540. uniforms.directionalLights.needsUpdate = value;
  19541. uniforms.pointLights.needsUpdate = value;
  19542. uniforms.spotLights.needsUpdate = value;
  19543. uniforms.rectAreaLights.needsUpdate = value;
  19544. uniforms.hemisphereLights.needsUpdate = value;
  19545. }
  19546. // Textures
  19547. function allocTextureUnit() {
  19548. var textureUnit = _usedTextureUnits;
  19549. if ( textureUnit >= capabilities.maxTextures ) {
  19550. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  19551. }
  19552. _usedTextureUnits += 1;
  19553. return textureUnit;
  19554. }
  19555. this.allocTextureUnit = allocTextureUnit;
  19556. // this.setTexture2D = setTexture2D;
  19557. this.setTexture2D = ( function () {
  19558. var warned = false;
  19559. // backwards compatibility: peel texture.texture
  19560. return function setTexture2D( texture, slot ) {
  19561. if ( texture && texture.isWebGLRenderTarget ) {
  19562. if ( ! warned ) {
  19563. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  19564. warned = true;
  19565. }
  19566. texture = texture.texture;
  19567. }
  19568. textures.setTexture2D( texture, slot );
  19569. };
  19570. }() );
  19571. this.setTexture2DArray = function ( texture, slot ) {
  19572. textures.setTexture2DArray( texture, slot );
  19573. };
  19574. this.setTexture3D = function ( texture, slot ) {
  19575. textures.setTexture3D( texture, slot );
  19576. };
  19577. this.setTexture = ( function () {
  19578. var warned = false;
  19579. return function setTexture( texture, slot ) {
  19580. if ( ! warned ) {
  19581. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  19582. warned = true;
  19583. }
  19584. textures.setTexture2D( texture, slot );
  19585. };
  19586. }() );
  19587. this.setTextureCube = ( function () {
  19588. var warned = false;
  19589. return function setTextureCube( texture, slot ) {
  19590. // backwards compatibility: peel texture.texture
  19591. if ( texture && texture.isWebGLRenderTargetCube ) {
  19592. if ( ! warned ) {
  19593. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  19594. warned = true;
  19595. }
  19596. texture = texture.texture;
  19597. }
  19598. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  19599. // TODO: unify these code paths
  19600. if ( ( texture && texture.isCubeTexture ) ||
  19601. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  19602. // CompressedTexture can have Array in image :/
  19603. // this function alone should take care of cube textures
  19604. textures.setTextureCube( texture, slot );
  19605. } else {
  19606. // assumed: texture property of THREE.WebGLRenderTargetCube
  19607. textures.setTextureCubeDynamic( texture, slot );
  19608. }
  19609. };
  19610. }() );
  19611. //
  19612. this.setFramebuffer = function ( value ) {
  19613. _framebuffer = value;
  19614. };
  19615. this.getRenderTarget = function () {
  19616. return _currentRenderTarget;
  19617. };
  19618. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipMapLevel ) {
  19619. _currentRenderTarget = renderTarget;
  19620. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  19621. textures.setupRenderTarget( renderTarget );
  19622. }
  19623. var framebuffer = _framebuffer;
  19624. var isCube = false;
  19625. if ( renderTarget ) {
  19626. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  19627. if ( renderTarget.isWebGLRenderTargetCube ) {
  19628. framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
  19629. isCube = true;
  19630. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  19631. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  19632. } else {
  19633. framebuffer = __webglFramebuffer;
  19634. }
  19635. _currentViewport.copy( renderTarget.viewport );
  19636. _currentScissor.copy( renderTarget.scissor );
  19637. _currentScissorTest = renderTarget.scissorTest;
  19638. } else {
  19639. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  19640. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  19641. _currentScissorTest = _scissorTest;
  19642. }
  19643. if ( _currentFramebuffer !== framebuffer ) {
  19644. _gl.bindFramebuffer( 36160, framebuffer );
  19645. _currentFramebuffer = framebuffer;
  19646. }
  19647. state.viewport( _currentViewport );
  19648. state.scissor( _currentScissor );
  19649. state.setScissorTest( _currentScissorTest );
  19650. if ( isCube ) {
  19651. var textureProperties = properties.get( renderTarget.texture );
  19652. _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipMapLevel || 0 );
  19653. }
  19654. };
  19655. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  19656. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  19657. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  19658. return;
  19659. }
  19660. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  19661. if ( framebuffer ) {
  19662. var restore = false;
  19663. if ( framebuffer !== _currentFramebuffer ) {
  19664. _gl.bindFramebuffer( 36160, framebuffer );
  19665. restore = true;
  19666. }
  19667. try {
  19668. var texture = renderTarget.texture;
  19669. var textureFormat = texture.format;
  19670. var textureType = texture.type;
  19671. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  19672. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  19673. return;
  19674. }
  19675. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  19676. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  19677. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  19678. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  19679. return;
  19680. }
  19681. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  19682. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  19683. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  19684. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  19685. }
  19686. } else {
  19687. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  19688. }
  19689. } finally {
  19690. if ( restore ) {
  19691. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  19692. }
  19693. }
  19694. }
  19695. };
  19696. this.copyFramebufferToTexture = function ( position, texture, level ) {
  19697. var width = texture.image.width;
  19698. var height = texture.image.height;
  19699. var glFormat = utils.convert( texture.format );
  19700. this.setTexture2D( texture, 0 );
  19701. _gl.copyTexImage2D( 3553, level || 0, glFormat, position.x, position.y, width, height, 0 );
  19702. };
  19703. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  19704. var width = srcTexture.image.width;
  19705. var height = srcTexture.image.height;
  19706. var glFormat = utils.convert( dstTexture.format );
  19707. var glType = utils.convert( dstTexture.type );
  19708. this.setTexture2D( dstTexture, 0 );
  19709. if ( srcTexture.isDataTexture ) {
  19710. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  19711. } else {
  19712. _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  19713. }
  19714. };
  19715. }
  19716. /**
  19717. * @author mrdoob / http://mrdoob.com/
  19718. * @author alteredq / http://alteredqualia.com/
  19719. */
  19720. function FogExp2( color, density ) {
  19721. this.name = '';
  19722. this.color = new Color( color );
  19723. this.density = ( density !== undefined ) ? density : 0.00025;
  19724. }
  19725. Object.assign( FogExp2.prototype, {
  19726. isFogExp2: true,
  19727. clone: function () {
  19728. return new FogExp2( this.color, this.density );
  19729. },
  19730. toJSON: function ( /* meta */ ) {
  19731. return {
  19732. type: 'FogExp2',
  19733. color: this.color.getHex(),
  19734. density: this.density
  19735. };
  19736. }
  19737. } );
  19738. /**
  19739. * @author mrdoob / http://mrdoob.com/
  19740. * @author alteredq / http://alteredqualia.com/
  19741. */
  19742. function Fog( color, near, far ) {
  19743. this.name = '';
  19744. this.color = new Color( color );
  19745. this.near = ( near !== undefined ) ? near : 1;
  19746. this.far = ( far !== undefined ) ? far : 1000;
  19747. }
  19748. Object.assign( Fog.prototype, {
  19749. isFog: true,
  19750. clone: function () {
  19751. return new Fog( this.color, this.near, this.far );
  19752. },
  19753. toJSON: function ( /* meta */ ) {
  19754. return {
  19755. type: 'Fog',
  19756. color: this.color.getHex(),
  19757. near: this.near,
  19758. far: this.far
  19759. };
  19760. }
  19761. } );
  19762. /**
  19763. * @author mrdoob / http://mrdoob.com/
  19764. */
  19765. function Scene() {
  19766. Object3D.call( this );
  19767. this.type = 'Scene';
  19768. this.background = null;
  19769. this.fog = null;
  19770. this.overrideMaterial = null;
  19771. this.autoUpdate = true; // checked by the renderer
  19772. }
  19773. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19774. constructor: Scene,
  19775. isScene: true,
  19776. copy: function ( source, recursive ) {
  19777. Object3D.prototype.copy.call( this, source, recursive );
  19778. if ( source.background !== null ) this.background = source.background.clone();
  19779. if ( source.fog !== null ) this.fog = source.fog.clone();
  19780. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  19781. this.autoUpdate = source.autoUpdate;
  19782. this.matrixAutoUpdate = source.matrixAutoUpdate;
  19783. return this;
  19784. },
  19785. toJSON: function ( meta ) {
  19786. var data = Object3D.prototype.toJSON.call( this, meta );
  19787. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  19788. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  19789. return data;
  19790. },
  19791. dispose: function () {
  19792. this.dispatchEvent( { type: 'dispose' } );
  19793. }
  19794. } );
  19795. /**
  19796. * @author benaadams / https://twitter.com/ben_a_adams
  19797. */
  19798. function InterleavedBuffer( array, stride ) {
  19799. this.array = array;
  19800. this.stride = stride;
  19801. this.count = array !== undefined ? array.length / stride : 0;
  19802. this.dynamic = false;
  19803. this.updateRange = { offset: 0, count: - 1 };
  19804. this.version = 0;
  19805. }
  19806. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  19807. set: function ( value ) {
  19808. if ( value === true ) this.version ++;
  19809. }
  19810. } );
  19811. Object.assign( InterleavedBuffer.prototype, {
  19812. isInterleavedBuffer: true,
  19813. onUploadCallback: function () {},
  19814. setArray: function ( array ) {
  19815. if ( Array.isArray( array ) ) {
  19816. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  19817. }
  19818. this.count = array !== undefined ? array.length / this.stride : 0;
  19819. this.array = array;
  19820. return this;
  19821. },
  19822. setDynamic: function ( value ) {
  19823. this.dynamic = value;
  19824. return this;
  19825. },
  19826. copy: function ( source ) {
  19827. this.array = new source.array.constructor( source.array );
  19828. this.count = source.count;
  19829. this.stride = source.stride;
  19830. this.dynamic = source.dynamic;
  19831. return this;
  19832. },
  19833. copyAt: function ( index1, attribute, index2 ) {
  19834. index1 *= this.stride;
  19835. index2 *= attribute.stride;
  19836. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  19837. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  19838. }
  19839. return this;
  19840. },
  19841. set: function ( value, offset ) {
  19842. if ( offset === undefined ) offset = 0;
  19843. this.array.set( value, offset );
  19844. return this;
  19845. },
  19846. clone: function () {
  19847. return new this.constructor().copy( this );
  19848. },
  19849. onUpload: function ( callback ) {
  19850. this.onUploadCallback = callback;
  19851. return this;
  19852. }
  19853. } );
  19854. /**
  19855. * @author benaadams / https://twitter.com/ben_a_adams
  19856. */
  19857. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  19858. this.data = interleavedBuffer;
  19859. this.itemSize = itemSize;
  19860. this.offset = offset;
  19861. this.normalized = normalized === true;
  19862. }
  19863. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  19864. count: {
  19865. get: function () {
  19866. return this.data.count;
  19867. }
  19868. },
  19869. array: {
  19870. get: function () {
  19871. return this.data.array;
  19872. }
  19873. }
  19874. } );
  19875. Object.assign( InterleavedBufferAttribute.prototype, {
  19876. isInterleavedBufferAttribute: true,
  19877. setX: function ( index, x ) {
  19878. this.data.array[ index * this.data.stride + this.offset ] = x;
  19879. return this;
  19880. },
  19881. setY: function ( index, y ) {
  19882. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  19883. return this;
  19884. },
  19885. setZ: function ( index, z ) {
  19886. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  19887. return this;
  19888. },
  19889. setW: function ( index, w ) {
  19890. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  19891. return this;
  19892. },
  19893. getX: function ( index ) {
  19894. return this.data.array[ index * this.data.stride + this.offset ];
  19895. },
  19896. getY: function ( index ) {
  19897. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  19898. },
  19899. getZ: function ( index ) {
  19900. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  19901. },
  19902. getW: function ( index ) {
  19903. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  19904. },
  19905. setXY: function ( index, x, y ) {
  19906. index = index * this.data.stride + this.offset;
  19907. this.data.array[ index + 0 ] = x;
  19908. this.data.array[ index + 1 ] = y;
  19909. return this;
  19910. },
  19911. setXYZ: function ( index, x, y, z ) {
  19912. index = index * this.data.stride + this.offset;
  19913. this.data.array[ index + 0 ] = x;
  19914. this.data.array[ index + 1 ] = y;
  19915. this.data.array[ index + 2 ] = z;
  19916. return this;
  19917. },
  19918. setXYZW: function ( index, x, y, z, w ) {
  19919. index = index * this.data.stride + this.offset;
  19920. this.data.array[ index + 0 ] = x;
  19921. this.data.array[ index + 1 ] = y;
  19922. this.data.array[ index + 2 ] = z;
  19923. this.data.array[ index + 3 ] = w;
  19924. return this;
  19925. }
  19926. } );
  19927. /**
  19928. * @author alteredq / http://alteredqualia.com/
  19929. *
  19930. * parameters = {
  19931. * color: <hex>,
  19932. * map: new THREE.Texture( <Image> ),
  19933. * rotation: <float>,
  19934. * sizeAttenuation: <bool>
  19935. * }
  19936. */
  19937. function SpriteMaterial( parameters ) {
  19938. Material.call( this );
  19939. this.type = 'SpriteMaterial';
  19940. this.color = new Color( 0xffffff );
  19941. this.map = null;
  19942. this.rotation = 0;
  19943. this.sizeAttenuation = true;
  19944. this.lights = false;
  19945. this.transparent = true;
  19946. this.setValues( parameters );
  19947. }
  19948. SpriteMaterial.prototype = Object.create( Material.prototype );
  19949. SpriteMaterial.prototype.constructor = SpriteMaterial;
  19950. SpriteMaterial.prototype.isSpriteMaterial = true;
  19951. SpriteMaterial.prototype.copy = function ( source ) {
  19952. Material.prototype.copy.call( this, source );
  19953. this.color.copy( source.color );
  19954. this.map = source.map;
  19955. this.rotation = source.rotation;
  19956. this.sizeAttenuation = source.sizeAttenuation;
  19957. return this;
  19958. };
  19959. /**
  19960. * @author mikael emtinger / http://gomo.se/
  19961. * @author alteredq / http://alteredqualia.com/
  19962. */
  19963. var geometry;
  19964. function Sprite( material ) {
  19965. Object3D.call( this );
  19966. this.type = 'Sprite';
  19967. if ( geometry === undefined ) {
  19968. geometry = new BufferGeometry();
  19969. var float32Array = new Float32Array( [
  19970. - 0.5, - 0.5, 0, 0, 0,
  19971. 0.5, - 0.5, 0, 1, 0,
  19972. 0.5, 0.5, 0, 1, 1,
  19973. - 0.5, 0.5, 0, 0, 1
  19974. ] );
  19975. var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  19976. geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  19977. geometry.addAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  19978. geometry.addAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  19979. }
  19980. this.geometry = geometry;
  19981. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  19982. this.center = new Vector2( 0.5, 0.5 );
  19983. }
  19984. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19985. constructor: Sprite,
  19986. isSprite: true,
  19987. raycast: ( function () {
  19988. var intersectPoint = new Vector3();
  19989. var worldScale = new Vector3();
  19990. var mvPosition = new Vector3();
  19991. var alignedPosition = new Vector2();
  19992. var rotatedPosition = new Vector2();
  19993. var viewWorldMatrix = new Matrix4();
  19994. var vA = new Vector3();
  19995. var vB = new Vector3();
  19996. var vC = new Vector3();
  19997. var uvA = new Vector2();
  19998. var uvB = new Vector2();
  19999. var uvC = new Vector2();
  20000. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  20001. // compute position in camera space
  20002. alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  20003. // to check if rotation is not zero
  20004. if ( sin !== undefined ) {
  20005. rotatedPosition.x = ( cos * alignedPosition.x ) - ( sin * alignedPosition.y );
  20006. rotatedPosition.y = ( sin * alignedPosition.x ) + ( cos * alignedPosition.y );
  20007. } else {
  20008. rotatedPosition.copy( alignedPosition );
  20009. }
  20010. vertexPosition.copy( mvPosition );
  20011. vertexPosition.x += rotatedPosition.x;
  20012. vertexPosition.y += rotatedPosition.y;
  20013. // transform to world space
  20014. vertexPosition.applyMatrix4( viewWorldMatrix );
  20015. }
  20016. return function raycast( raycaster, intersects ) {
  20017. worldScale.setFromMatrixScale( this.matrixWorld );
  20018. viewWorldMatrix.getInverse( this.modelViewMatrix ).premultiply( this.matrixWorld );
  20019. mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  20020. var rotation = this.material.rotation;
  20021. var sin, cos;
  20022. if ( rotation !== 0 ) {
  20023. cos = Math.cos( rotation );
  20024. sin = Math.sin( rotation );
  20025. }
  20026. var center = this.center;
  20027. transformVertex( vA.set( - 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20028. transformVertex( vB.set( 0.5, - 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20029. transformVertex( vC.set( 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20030. uvA.set( 0, 0 );
  20031. uvB.set( 1, 0 );
  20032. uvC.set( 1, 1 );
  20033. // check first triangle
  20034. var intersect = raycaster.ray.intersectTriangle( vA, vB, vC, false, intersectPoint );
  20035. if ( intersect === null ) {
  20036. // check second triangle
  20037. transformVertex( vB.set( - 0.5, 0.5, 0 ), mvPosition, center, worldScale, sin, cos );
  20038. uvB.set( 0, 1 );
  20039. intersect = raycaster.ray.intersectTriangle( vA, vC, vB, false, intersectPoint );
  20040. if ( intersect === null ) {
  20041. return;
  20042. }
  20043. }
  20044. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20045. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20046. intersects.push( {
  20047. distance: distance,
  20048. point: intersectPoint.clone(),
  20049. uv: Triangle.getUV( intersectPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() ),
  20050. face: null,
  20051. object: this
  20052. } );
  20053. };
  20054. }() ),
  20055. clone: function () {
  20056. return new this.constructor( this.material ).copy( this );
  20057. },
  20058. copy: function ( source ) {
  20059. Object3D.prototype.copy.call( this, source );
  20060. if ( source.center !== undefined ) this.center.copy( source.center );
  20061. return this;
  20062. }
  20063. } );
  20064. /**
  20065. * @author mikael emtinger / http://gomo.se/
  20066. * @author alteredq / http://alteredqualia.com/
  20067. * @author mrdoob / http://mrdoob.com/
  20068. */
  20069. function LOD() {
  20070. Object3D.call( this );
  20071. this.type = 'LOD';
  20072. Object.defineProperties( this, {
  20073. levels: {
  20074. enumerable: true,
  20075. value: []
  20076. }
  20077. } );
  20078. }
  20079. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20080. constructor: LOD,
  20081. copy: function ( source ) {
  20082. Object3D.prototype.copy.call( this, source, false );
  20083. var levels = source.levels;
  20084. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  20085. var level = levels[ i ];
  20086. this.addLevel( level.object.clone(), level.distance );
  20087. }
  20088. return this;
  20089. },
  20090. addLevel: function ( object, distance ) {
  20091. if ( distance === undefined ) distance = 0;
  20092. distance = Math.abs( distance );
  20093. var levels = this.levels;
  20094. for ( var l = 0; l < levels.length; l ++ ) {
  20095. if ( distance < levels[ l ].distance ) {
  20096. break;
  20097. }
  20098. }
  20099. levels.splice( l, 0, { distance: distance, object: object } );
  20100. this.add( object );
  20101. },
  20102. getObjectForDistance: function ( distance ) {
  20103. var levels = this.levels;
  20104. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  20105. if ( distance < levels[ i ].distance ) {
  20106. break;
  20107. }
  20108. }
  20109. return levels[ i - 1 ].object;
  20110. },
  20111. raycast: ( function () {
  20112. var matrixPosition = new Vector3();
  20113. return function raycast( raycaster, intersects ) {
  20114. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  20115. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  20116. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  20117. };
  20118. }() ),
  20119. update: function () {
  20120. var v1 = new Vector3();
  20121. var v2 = new Vector3();
  20122. return function update( camera ) {
  20123. var levels = this.levels;
  20124. if ( levels.length > 1 ) {
  20125. v1.setFromMatrixPosition( camera.matrixWorld );
  20126. v2.setFromMatrixPosition( this.matrixWorld );
  20127. var distance = v1.distanceTo( v2 );
  20128. levels[ 0 ].object.visible = true;
  20129. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  20130. if ( distance >= levels[ i ].distance ) {
  20131. levels[ i - 1 ].object.visible = false;
  20132. levels[ i ].object.visible = true;
  20133. } else {
  20134. break;
  20135. }
  20136. }
  20137. for ( ; i < l; i ++ ) {
  20138. levels[ i ].object.visible = false;
  20139. }
  20140. }
  20141. };
  20142. }(),
  20143. toJSON: function ( meta ) {
  20144. var data = Object3D.prototype.toJSON.call( this, meta );
  20145. data.object.levels = [];
  20146. var levels = this.levels;
  20147. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  20148. var level = levels[ i ];
  20149. data.object.levels.push( {
  20150. object: level.object.uuid,
  20151. distance: level.distance
  20152. } );
  20153. }
  20154. return data;
  20155. }
  20156. } );
  20157. /**
  20158. * @author mikael emtinger / http://gomo.se/
  20159. * @author alteredq / http://alteredqualia.com/
  20160. * @author ikerr / http://verold.com
  20161. */
  20162. function SkinnedMesh( geometry, material ) {
  20163. if ( geometry && geometry.isGeometry ) {
  20164. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  20165. }
  20166. Mesh.call( this, geometry, material );
  20167. this.type = 'SkinnedMesh';
  20168. this.bindMode = 'attached';
  20169. this.bindMatrix = new Matrix4();
  20170. this.bindMatrixInverse = new Matrix4();
  20171. }
  20172. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  20173. constructor: SkinnedMesh,
  20174. isSkinnedMesh: true,
  20175. bind: function ( skeleton, bindMatrix ) {
  20176. this.skeleton = skeleton;
  20177. if ( bindMatrix === undefined ) {
  20178. this.updateMatrixWorld( true );
  20179. this.skeleton.calculateInverses();
  20180. bindMatrix = this.matrixWorld;
  20181. }
  20182. this.bindMatrix.copy( bindMatrix );
  20183. this.bindMatrixInverse.getInverse( bindMatrix );
  20184. },
  20185. pose: function () {
  20186. this.skeleton.pose();
  20187. },
  20188. normalizeSkinWeights: function () {
  20189. var vector = new Vector4();
  20190. var skinWeight = this.geometry.attributes.skinWeight;
  20191. for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {
  20192. vector.x = skinWeight.getX( i );
  20193. vector.y = skinWeight.getY( i );
  20194. vector.z = skinWeight.getZ( i );
  20195. vector.w = skinWeight.getW( i );
  20196. var scale = 1.0 / vector.manhattanLength();
  20197. if ( scale !== Infinity ) {
  20198. vector.multiplyScalar( scale );
  20199. } else {
  20200. vector.set( 1, 0, 0, 0 ); // do something reasonable
  20201. }
  20202. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  20203. }
  20204. },
  20205. updateMatrixWorld: function ( force ) {
  20206. Mesh.prototype.updateMatrixWorld.call( this, force );
  20207. if ( this.bindMode === 'attached' ) {
  20208. this.bindMatrixInverse.getInverse( this.matrixWorld );
  20209. } else if ( this.bindMode === 'detached' ) {
  20210. this.bindMatrixInverse.getInverse( this.bindMatrix );
  20211. } else {
  20212. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  20213. }
  20214. },
  20215. clone: function () {
  20216. return new this.constructor( this.geometry, this.material ).copy( this );
  20217. }
  20218. } );
  20219. /**
  20220. * @author mikael emtinger / http://gomo.se/
  20221. * @author alteredq / http://alteredqualia.com/
  20222. * @author michael guerrero / http://realitymeltdown.com
  20223. * @author ikerr / http://verold.com
  20224. */
  20225. function Skeleton( bones, boneInverses ) {
  20226. // copy the bone array
  20227. bones = bones || [];
  20228. this.bones = bones.slice( 0 );
  20229. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  20230. // use the supplied bone inverses or calculate the inverses
  20231. if ( boneInverses === undefined ) {
  20232. this.calculateInverses();
  20233. } else {
  20234. if ( this.bones.length === boneInverses.length ) {
  20235. this.boneInverses = boneInverses.slice( 0 );
  20236. } else {
  20237. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  20238. this.boneInverses = [];
  20239. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  20240. this.boneInverses.push( new Matrix4() );
  20241. }
  20242. }
  20243. }
  20244. }
  20245. Object.assign( Skeleton.prototype, {
  20246. calculateInverses: function () {
  20247. this.boneInverses = [];
  20248. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  20249. var inverse = new Matrix4();
  20250. if ( this.bones[ i ] ) {
  20251. inverse.getInverse( this.bones[ i ].matrixWorld );
  20252. }
  20253. this.boneInverses.push( inverse );
  20254. }
  20255. },
  20256. pose: function () {
  20257. var bone, i, il;
  20258. // recover the bind-time world matrices
  20259. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  20260. bone = this.bones[ i ];
  20261. if ( bone ) {
  20262. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  20263. }
  20264. }
  20265. // compute the local matrices, positions, rotations and scales
  20266. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  20267. bone = this.bones[ i ];
  20268. if ( bone ) {
  20269. if ( bone.parent && bone.parent.isBone ) {
  20270. bone.matrix.getInverse( bone.parent.matrixWorld );
  20271. bone.matrix.multiply( bone.matrixWorld );
  20272. } else {
  20273. bone.matrix.copy( bone.matrixWorld );
  20274. }
  20275. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  20276. }
  20277. }
  20278. },
  20279. update: ( function () {
  20280. var offsetMatrix = new Matrix4();
  20281. var identityMatrix = new Matrix4();
  20282. return function update() {
  20283. var bones = this.bones;
  20284. var boneInverses = this.boneInverses;
  20285. var boneMatrices = this.boneMatrices;
  20286. var boneTexture = this.boneTexture;
  20287. // flatten bone matrices to array
  20288. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  20289. // compute the offset between the current and the original transform
  20290. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  20291. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  20292. offsetMatrix.toArray( boneMatrices, i * 16 );
  20293. }
  20294. if ( boneTexture !== undefined ) {
  20295. boneTexture.needsUpdate = true;
  20296. }
  20297. };
  20298. } )(),
  20299. clone: function () {
  20300. return new Skeleton( this.bones, this.boneInverses );
  20301. },
  20302. getBoneByName: function ( name ) {
  20303. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  20304. var bone = this.bones[ i ];
  20305. if ( bone.name === name ) {
  20306. return bone;
  20307. }
  20308. }
  20309. return undefined;
  20310. }
  20311. } );
  20312. /**
  20313. * @author mikael emtinger / http://gomo.se/
  20314. * @author alteredq / http://alteredqualia.com/
  20315. * @author ikerr / http://verold.com
  20316. */
  20317. function Bone() {
  20318. Object3D.call( this );
  20319. this.type = 'Bone';
  20320. }
  20321. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20322. constructor: Bone,
  20323. isBone: true
  20324. } );
  20325. /**
  20326. * @author mrdoob / http://mrdoob.com/
  20327. * @author alteredq / http://alteredqualia.com/
  20328. *
  20329. * parameters = {
  20330. * color: <hex>,
  20331. * opacity: <float>,
  20332. *
  20333. * linewidth: <float>,
  20334. * linecap: "round",
  20335. * linejoin: "round"
  20336. * }
  20337. */
  20338. function LineBasicMaterial( parameters ) {
  20339. Material.call( this );
  20340. this.type = 'LineBasicMaterial';
  20341. this.color = new Color( 0xffffff );
  20342. this.linewidth = 1;
  20343. this.linecap = 'round';
  20344. this.linejoin = 'round';
  20345. this.lights = false;
  20346. this.setValues( parameters );
  20347. }
  20348. LineBasicMaterial.prototype = Object.create( Material.prototype );
  20349. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  20350. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  20351. LineBasicMaterial.prototype.copy = function ( source ) {
  20352. Material.prototype.copy.call( this, source );
  20353. this.color.copy( source.color );
  20354. this.linewidth = source.linewidth;
  20355. this.linecap = source.linecap;
  20356. this.linejoin = source.linejoin;
  20357. return this;
  20358. };
  20359. /**
  20360. * @author mrdoob / http://mrdoob.com/
  20361. */
  20362. function Line( geometry, material, mode ) {
  20363. if ( mode === 1 ) {
  20364. console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );
  20365. }
  20366. Object3D.call( this );
  20367. this.type = 'Line';
  20368. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  20369. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  20370. }
  20371. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20372. constructor: Line,
  20373. isLine: true,
  20374. computeLineDistances: ( function () {
  20375. var start = new Vector3();
  20376. var end = new Vector3();
  20377. return function computeLineDistances() {
  20378. var geometry = this.geometry;
  20379. if ( geometry.isBufferGeometry ) {
  20380. // we assume non-indexed geometry
  20381. if ( geometry.index === null ) {
  20382. var positionAttribute = geometry.attributes.position;
  20383. var lineDistances = [ 0 ];
  20384. for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20385. start.fromBufferAttribute( positionAttribute, i - 1 );
  20386. end.fromBufferAttribute( positionAttribute, i );
  20387. lineDistances[ i ] = lineDistances[ i - 1 ];
  20388. lineDistances[ i ] += start.distanceTo( end );
  20389. }
  20390. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20391. } else {
  20392. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20393. }
  20394. } else if ( geometry.isGeometry ) {
  20395. var vertices = geometry.vertices;
  20396. var lineDistances = geometry.lineDistances;
  20397. lineDistances[ 0 ] = 0;
  20398. for ( var i = 1, l = vertices.length; i < l; i ++ ) {
  20399. lineDistances[ i ] = lineDistances[ i - 1 ];
  20400. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  20401. }
  20402. }
  20403. return this;
  20404. };
  20405. }() ),
  20406. raycast: ( function () {
  20407. var inverseMatrix = new Matrix4();
  20408. var ray = new Ray();
  20409. var sphere = new Sphere();
  20410. return function raycast( raycaster, intersects ) {
  20411. var precision = raycaster.linePrecision;
  20412. var geometry = this.geometry;
  20413. var matrixWorld = this.matrixWorld;
  20414. // Checking boundingSphere distance to ray
  20415. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20416. sphere.copy( geometry.boundingSphere );
  20417. sphere.applyMatrix4( matrixWorld );
  20418. sphere.radius += precision;
  20419. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  20420. //
  20421. inverseMatrix.getInverse( matrixWorld );
  20422. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  20423. var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20424. var localPrecisionSq = localPrecision * localPrecision;
  20425. var vStart = new Vector3();
  20426. var vEnd = new Vector3();
  20427. var interSegment = new Vector3();
  20428. var interRay = new Vector3();
  20429. var step = ( this && this.isLineSegments ) ? 2 : 1;
  20430. if ( geometry.isBufferGeometry ) {
  20431. var index = geometry.index;
  20432. var attributes = geometry.attributes;
  20433. var positions = attributes.position.array;
  20434. if ( index !== null ) {
  20435. var indices = index.array;
  20436. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  20437. var a = indices[ i ];
  20438. var b = indices[ i + 1 ];
  20439. vStart.fromArray( positions, a * 3 );
  20440. vEnd.fromArray( positions, b * 3 );
  20441. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20442. if ( distSq > localPrecisionSq ) continue;
  20443. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20444. var distance = raycaster.ray.origin.distanceTo( interRay );
  20445. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20446. intersects.push( {
  20447. distance: distance,
  20448. // What do we want? intersection point on the ray or on the segment??
  20449. // point: raycaster.ray.at( distance ),
  20450. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20451. index: i,
  20452. face: null,
  20453. faceIndex: null,
  20454. object: this
  20455. } );
  20456. }
  20457. } else {
  20458. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  20459. vStart.fromArray( positions, 3 * i );
  20460. vEnd.fromArray( positions, 3 * i + 3 );
  20461. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20462. if ( distSq > localPrecisionSq ) continue;
  20463. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20464. var distance = raycaster.ray.origin.distanceTo( interRay );
  20465. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20466. intersects.push( {
  20467. distance: distance,
  20468. // What do we want? intersection point on the ray or on the segment??
  20469. // point: raycaster.ray.at( distance ),
  20470. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20471. index: i,
  20472. face: null,
  20473. faceIndex: null,
  20474. object: this
  20475. } );
  20476. }
  20477. }
  20478. } else if ( geometry.isGeometry ) {
  20479. var vertices = geometry.vertices;
  20480. var nbVertices = vertices.length;
  20481. for ( var i = 0; i < nbVertices - 1; i += step ) {
  20482. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  20483. if ( distSq > localPrecisionSq ) continue;
  20484. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20485. var distance = raycaster.ray.origin.distanceTo( interRay );
  20486. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20487. intersects.push( {
  20488. distance: distance,
  20489. // What do we want? intersection point on the ray or on the segment??
  20490. // point: raycaster.ray.at( distance ),
  20491. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20492. index: i,
  20493. face: null,
  20494. faceIndex: null,
  20495. object: this
  20496. } );
  20497. }
  20498. }
  20499. };
  20500. }() ),
  20501. clone: function () {
  20502. return new this.constructor( this.geometry, this.material ).copy( this );
  20503. }
  20504. } );
  20505. /**
  20506. * @author mrdoob / http://mrdoob.com/
  20507. */
  20508. function LineSegments( geometry, material ) {
  20509. Line.call( this, geometry, material );
  20510. this.type = 'LineSegments';
  20511. }
  20512. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  20513. constructor: LineSegments,
  20514. isLineSegments: true,
  20515. computeLineDistances: ( function () {
  20516. var start = new Vector3();
  20517. var end = new Vector3();
  20518. return function computeLineDistances() {
  20519. var geometry = this.geometry;
  20520. if ( geometry.isBufferGeometry ) {
  20521. // we assume non-indexed geometry
  20522. if ( geometry.index === null ) {
  20523. var positionAttribute = geometry.attributes.position;
  20524. var lineDistances = [];
  20525. for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20526. start.fromBufferAttribute( positionAttribute, i );
  20527. end.fromBufferAttribute( positionAttribute, i + 1 );
  20528. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20529. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  20530. }
  20531. geometry.addAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20532. } else {
  20533. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20534. }
  20535. } else if ( geometry.isGeometry ) {
  20536. var vertices = geometry.vertices;
  20537. var lineDistances = geometry.lineDistances;
  20538. for ( var i = 0, l = vertices.length; i < l; i += 2 ) {
  20539. start.copy( vertices[ i ] );
  20540. end.copy( vertices[ i + 1 ] );
  20541. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20542. lineDistances[ i + 1 ] = lineDistances[ i ] + start.distanceTo( end );
  20543. }
  20544. }
  20545. return this;
  20546. };
  20547. }() )
  20548. } );
  20549. /**
  20550. * @author mgreter / http://github.com/mgreter
  20551. */
  20552. function LineLoop( geometry, material ) {
  20553. Line.call( this, geometry, material );
  20554. this.type = 'LineLoop';
  20555. }
  20556. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  20557. constructor: LineLoop,
  20558. isLineLoop: true,
  20559. } );
  20560. /**
  20561. * @author mrdoob / http://mrdoob.com/
  20562. * @author alteredq / http://alteredqualia.com/
  20563. *
  20564. * parameters = {
  20565. * color: <hex>,
  20566. * opacity: <float>,
  20567. * map: new THREE.Texture( <Image> ),
  20568. *
  20569. * size: <float>,
  20570. * sizeAttenuation: <bool>
  20571. *
  20572. * morphTargets: <bool>
  20573. * }
  20574. */
  20575. function PointsMaterial( parameters ) {
  20576. Material.call( this );
  20577. this.type = 'PointsMaterial';
  20578. this.color = new Color( 0xffffff );
  20579. this.map = null;
  20580. this.size = 1;
  20581. this.sizeAttenuation = true;
  20582. this.morphTargets = false;
  20583. this.lights = false;
  20584. this.setValues( parameters );
  20585. }
  20586. PointsMaterial.prototype = Object.create( Material.prototype );
  20587. PointsMaterial.prototype.constructor = PointsMaterial;
  20588. PointsMaterial.prototype.isPointsMaterial = true;
  20589. PointsMaterial.prototype.copy = function ( source ) {
  20590. Material.prototype.copy.call( this, source );
  20591. this.color.copy( source.color );
  20592. this.map = source.map;
  20593. this.size = source.size;
  20594. this.sizeAttenuation = source.sizeAttenuation;
  20595. this.morphTargets = source.morphTargets;
  20596. return this;
  20597. };
  20598. /**
  20599. * @author alteredq / http://alteredqualia.com/
  20600. */
  20601. function Points( geometry, material ) {
  20602. Object3D.call( this );
  20603. this.type = 'Points';
  20604. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  20605. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  20606. }
  20607. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  20608. constructor: Points,
  20609. isPoints: true,
  20610. raycast: ( function () {
  20611. var inverseMatrix = new Matrix4();
  20612. var ray = new Ray();
  20613. var sphere = new Sphere();
  20614. return function raycast( raycaster, intersects ) {
  20615. var object = this;
  20616. var geometry = this.geometry;
  20617. var matrixWorld = this.matrixWorld;
  20618. var threshold = raycaster.params.Points.threshold;
  20619. // Checking boundingSphere distance to ray
  20620. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20621. sphere.copy( geometry.boundingSphere );
  20622. sphere.applyMatrix4( matrixWorld );
  20623. sphere.radius += threshold;
  20624. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  20625. //
  20626. inverseMatrix.getInverse( matrixWorld );
  20627. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  20628. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20629. var localThresholdSq = localThreshold * localThreshold;
  20630. var position = new Vector3();
  20631. var intersectPoint = new Vector3();
  20632. function testPoint( point, index ) {
  20633. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  20634. if ( rayPointDistanceSq < localThresholdSq ) {
  20635. ray.closestPointToPoint( point, intersectPoint );
  20636. intersectPoint.applyMatrix4( matrixWorld );
  20637. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20638. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20639. intersects.push( {
  20640. distance: distance,
  20641. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20642. point: intersectPoint.clone(),
  20643. index: index,
  20644. face: null,
  20645. object: object
  20646. } );
  20647. }
  20648. }
  20649. if ( geometry.isBufferGeometry ) {
  20650. var index = geometry.index;
  20651. var attributes = geometry.attributes;
  20652. var positions = attributes.position.array;
  20653. if ( index !== null ) {
  20654. var indices = index.array;
  20655. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  20656. var a = indices[ i ];
  20657. position.fromArray( positions, a * 3 );
  20658. testPoint( position, a );
  20659. }
  20660. } else {
  20661. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  20662. position.fromArray( positions, i * 3 );
  20663. testPoint( position, i );
  20664. }
  20665. }
  20666. } else {
  20667. var vertices = geometry.vertices;
  20668. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20669. testPoint( vertices[ i ], i );
  20670. }
  20671. }
  20672. };
  20673. }() ),
  20674. clone: function () {
  20675. return new this.constructor( this.geometry, this.material ).copy( this );
  20676. }
  20677. } );
  20678. /**
  20679. * @author mrdoob / http://mrdoob.com/
  20680. */
  20681. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20682. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20683. this.format = format !== undefined ? format : RGBFormat;
  20684. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20685. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20686. this.generateMipmaps = false;
  20687. }
  20688. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  20689. constructor: VideoTexture,
  20690. isVideoTexture: true,
  20691. update: function () {
  20692. var video = this.image;
  20693. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  20694. this.needsUpdate = true;
  20695. }
  20696. }
  20697. } );
  20698. /**
  20699. * @author alteredq / http://alteredqualia.com/
  20700. */
  20701. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  20702. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  20703. this.image = { width: width, height: height };
  20704. this.mipmaps = mipmaps;
  20705. // no flipping for cube textures
  20706. // (also flipping doesn't work for compressed textures )
  20707. this.flipY = false;
  20708. // can't generate mipmaps for compressed textures
  20709. // mips must be embedded in DDS files
  20710. this.generateMipmaps = false;
  20711. }
  20712. CompressedTexture.prototype = Object.create( Texture.prototype );
  20713. CompressedTexture.prototype.constructor = CompressedTexture;
  20714. CompressedTexture.prototype.isCompressedTexture = true;
  20715. /**
  20716. * @author mrdoob / http://mrdoob.com/
  20717. */
  20718. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20719. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20720. this.needsUpdate = true;
  20721. }
  20722. CanvasTexture.prototype = Object.create( Texture.prototype );
  20723. CanvasTexture.prototype.constructor = CanvasTexture;
  20724. CanvasTexture.prototype.isCanvasTexture = true;
  20725. /**
  20726. * @author Matt DesLauriers / @mattdesl
  20727. * @author atix / arthursilber.de
  20728. */
  20729. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  20730. format = format !== undefined ? format : DepthFormat;
  20731. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  20732. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  20733. }
  20734. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  20735. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  20736. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20737. this.image = { width: width, height: height };
  20738. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  20739. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  20740. this.flipY = false;
  20741. this.generateMipmaps = false;
  20742. }
  20743. DepthTexture.prototype = Object.create( Texture.prototype );
  20744. DepthTexture.prototype.constructor = DepthTexture;
  20745. DepthTexture.prototype.isDepthTexture = true;
  20746. /**
  20747. * @author mrdoob / http://mrdoob.com/
  20748. * @author Mugen87 / https://github.com/Mugen87
  20749. */
  20750. function WireframeGeometry( geometry ) {
  20751. BufferGeometry.call( this );
  20752. this.type = 'WireframeGeometry';
  20753. // buffer
  20754. var vertices = [];
  20755. // helper variables
  20756. var i, j, l, o, ol;
  20757. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  20758. var key, keys = [ 'a', 'b', 'c' ];
  20759. var vertex;
  20760. // different logic for Geometry and BufferGeometry
  20761. if ( geometry && geometry.isGeometry ) {
  20762. // create a data structure that contains all edges without duplicates
  20763. var faces = geometry.faces;
  20764. for ( i = 0, l = faces.length; i < l; i ++ ) {
  20765. var face = faces[ i ];
  20766. for ( j = 0; j < 3; j ++ ) {
  20767. edge1 = face[ keys[ j ] ];
  20768. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  20769. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20770. edge[ 1 ] = Math.max( edge1, edge2 );
  20771. key = edge[ 0 ] + ',' + edge[ 1 ];
  20772. if ( edges[ key ] === undefined ) {
  20773. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20774. }
  20775. }
  20776. }
  20777. // generate vertices
  20778. for ( key in edges ) {
  20779. e = edges[ key ];
  20780. vertex = geometry.vertices[ e.index1 ];
  20781. vertices.push( vertex.x, vertex.y, vertex.z );
  20782. vertex = geometry.vertices[ e.index2 ];
  20783. vertices.push( vertex.x, vertex.y, vertex.z );
  20784. }
  20785. } else if ( geometry && geometry.isBufferGeometry ) {
  20786. var position, indices, groups;
  20787. var group, start, count;
  20788. var index1, index2;
  20789. vertex = new Vector3();
  20790. if ( geometry.index !== null ) {
  20791. // indexed BufferGeometry
  20792. position = geometry.attributes.position;
  20793. indices = geometry.index;
  20794. groups = geometry.groups;
  20795. if ( groups.length === 0 ) {
  20796. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20797. }
  20798. // create a data structure that contains all eges without duplicates
  20799. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  20800. group = groups[ o ];
  20801. start = group.start;
  20802. count = group.count;
  20803. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  20804. for ( j = 0; j < 3; j ++ ) {
  20805. edge1 = indices.getX( i + j );
  20806. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  20807. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20808. edge[ 1 ] = Math.max( edge1, edge2 );
  20809. key = edge[ 0 ] + ',' + edge[ 1 ];
  20810. if ( edges[ key ] === undefined ) {
  20811. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20812. }
  20813. }
  20814. }
  20815. }
  20816. // generate vertices
  20817. for ( key in edges ) {
  20818. e = edges[ key ];
  20819. vertex.fromBufferAttribute( position, e.index1 );
  20820. vertices.push( vertex.x, vertex.y, vertex.z );
  20821. vertex.fromBufferAttribute( position, e.index2 );
  20822. vertices.push( vertex.x, vertex.y, vertex.z );
  20823. }
  20824. } else {
  20825. // non-indexed BufferGeometry
  20826. position = geometry.attributes.position;
  20827. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20828. for ( j = 0; j < 3; j ++ ) {
  20829. // three edges per triangle, an edge is represented as (index1, index2)
  20830. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20831. index1 = 3 * i + j;
  20832. vertex.fromBufferAttribute( position, index1 );
  20833. vertices.push( vertex.x, vertex.y, vertex.z );
  20834. index2 = 3 * i + ( ( j + 1 ) % 3 );
  20835. vertex.fromBufferAttribute( position, index2 );
  20836. vertices.push( vertex.x, vertex.y, vertex.z );
  20837. }
  20838. }
  20839. }
  20840. }
  20841. // build geometry
  20842. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20843. }
  20844. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  20845. WireframeGeometry.prototype.constructor = WireframeGeometry;
  20846. /**
  20847. * @author zz85 / https://github.com/zz85
  20848. * @author Mugen87 / https://github.com/Mugen87
  20849. *
  20850. * Parametric Surfaces Geometry
  20851. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20852. */
  20853. // ParametricGeometry
  20854. function ParametricGeometry( func, slices, stacks ) {
  20855. Geometry.call( this );
  20856. this.type = 'ParametricGeometry';
  20857. this.parameters = {
  20858. func: func,
  20859. slices: slices,
  20860. stacks: stacks
  20861. };
  20862. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  20863. this.mergeVertices();
  20864. }
  20865. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  20866. ParametricGeometry.prototype.constructor = ParametricGeometry;
  20867. // ParametricBufferGeometry
  20868. function ParametricBufferGeometry( func, slices, stacks ) {
  20869. BufferGeometry.call( this );
  20870. this.type = 'ParametricBufferGeometry';
  20871. this.parameters = {
  20872. func: func,
  20873. slices: slices,
  20874. stacks: stacks
  20875. };
  20876. // buffers
  20877. var indices = [];
  20878. var vertices = [];
  20879. var normals = [];
  20880. var uvs = [];
  20881. var EPS = 0.00001;
  20882. var normal = new Vector3();
  20883. var p0 = new Vector3(), p1 = new Vector3();
  20884. var pu = new Vector3(), pv = new Vector3();
  20885. var i, j;
  20886. if ( func.length < 3 ) {
  20887. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  20888. }
  20889. // generate vertices, normals and uvs
  20890. var sliceCount = slices + 1;
  20891. for ( i = 0; i <= stacks; i ++ ) {
  20892. var v = i / stacks;
  20893. for ( j = 0; j <= slices; j ++ ) {
  20894. var u = j / slices;
  20895. // vertex
  20896. func( u, v, p0 );
  20897. vertices.push( p0.x, p0.y, p0.z );
  20898. // normal
  20899. // approximate tangent vectors via finite differences
  20900. if ( u - EPS >= 0 ) {
  20901. func( u - EPS, v, p1 );
  20902. pu.subVectors( p0, p1 );
  20903. } else {
  20904. func( u + EPS, v, p1 );
  20905. pu.subVectors( p1, p0 );
  20906. }
  20907. if ( v - EPS >= 0 ) {
  20908. func( u, v - EPS, p1 );
  20909. pv.subVectors( p0, p1 );
  20910. } else {
  20911. func( u, v + EPS, p1 );
  20912. pv.subVectors( p1, p0 );
  20913. }
  20914. // cross product of tangent vectors returns surface normal
  20915. normal.crossVectors( pu, pv ).normalize();
  20916. normals.push( normal.x, normal.y, normal.z );
  20917. // uv
  20918. uvs.push( u, v );
  20919. }
  20920. }
  20921. // generate indices
  20922. for ( i = 0; i < stacks; i ++ ) {
  20923. for ( j = 0; j < slices; j ++ ) {
  20924. var a = i * sliceCount + j;
  20925. var b = i * sliceCount + j + 1;
  20926. var c = ( i + 1 ) * sliceCount + j + 1;
  20927. var d = ( i + 1 ) * sliceCount + j;
  20928. // faces one and two
  20929. indices.push( a, b, d );
  20930. indices.push( b, c, d );
  20931. }
  20932. }
  20933. // build geometry
  20934. this.setIndex( indices );
  20935. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20936. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20937. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20938. }
  20939. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20940. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  20941. /**
  20942. * @author clockworkgeek / https://github.com/clockworkgeek
  20943. * @author timothypratley / https://github.com/timothypratley
  20944. * @author WestLangley / http://github.com/WestLangley
  20945. * @author Mugen87 / https://github.com/Mugen87
  20946. */
  20947. // PolyhedronGeometry
  20948. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  20949. Geometry.call( this );
  20950. this.type = 'PolyhedronGeometry';
  20951. this.parameters = {
  20952. vertices: vertices,
  20953. indices: indices,
  20954. radius: radius,
  20955. detail: detail
  20956. };
  20957. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  20958. this.mergeVertices();
  20959. }
  20960. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  20961. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  20962. // PolyhedronBufferGeometry
  20963. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  20964. BufferGeometry.call( this );
  20965. this.type = 'PolyhedronBufferGeometry';
  20966. this.parameters = {
  20967. vertices: vertices,
  20968. indices: indices,
  20969. radius: radius,
  20970. detail: detail
  20971. };
  20972. radius = radius || 1;
  20973. detail = detail || 0;
  20974. // default buffer data
  20975. var vertexBuffer = [];
  20976. var uvBuffer = [];
  20977. // the subdivision creates the vertex buffer data
  20978. subdivide( detail );
  20979. // all vertices should lie on a conceptual sphere with a given radius
  20980. appplyRadius( radius );
  20981. // finally, create the uv data
  20982. generateUVs();
  20983. // build non-indexed geometry
  20984. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20985. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20986. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20987. if ( detail === 0 ) {
  20988. this.computeVertexNormals(); // flat normals
  20989. } else {
  20990. this.normalizeNormals(); // smooth normals
  20991. }
  20992. // helper functions
  20993. function subdivide( detail ) {
  20994. var a = new Vector3();
  20995. var b = new Vector3();
  20996. var c = new Vector3();
  20997. // iterate over all faces and apply a subdivison with the given detail value
  20998. for ( var i = 0; i < indices.length; i += 3 ) {
  20999. // get the vertices of the face
  21000. getVertexByIndex( indices[ i + 0 ], a );
  21001. getVertexByIndex( indices[ i + 1 ], b );
  21002. getVertexByIndex( indices[ i + 2 ], c );
  21003. // perform subdivision
  21004. subdivideFace( a, b, c, detail );
  21005. }
  21006. }
  21007. function subdivideFace( a, b, c, detail ) {
  21008. var cols = Math.pow( 2, detail );
  21009. // we use this multidimensional array as a data structure for creating the subdivision
  21010. var v = [];
  21011. var i, j;
  21012. // construct all of the vertices for this subdivision
  21013. for ( i = 0; i <= cols; i ++ ) {
  21014. v[ i ] = [];
  21015. var aj = a.clone().lerp( c, i / cols );
  21016. var bj = b.clone().lerp( c, i / cols );
  21017. var rows = cols - i;
  21018. for ( j = 0; j <= rows; j ++ ) {
  21019. if ( j === 0 && i === cols ) {
  21020. v[ i ][ j ] = aj;
  21021. } else {
  21022. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21023. }
  21024. }
  21025. }
  21026. // construct all of the faces
  21027. for ( i = 0; i < cols; i ++ ) {
  21028. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  21029. var k = Math.floor( j / 2 );
  21030. if ( j % 2 === 0 ) {
  21031. pushVertex( v[ i ][ k + 1 ] );
  21032. pushVertex( v[ i + 1 ][ k ] );
  21033. pushVertex( v[ i ][ k ] );
  21034. } else {
  21035. pushVertex( v[ i ][ k + 1 ] );
  21036. pushVertex( v[ i + 1 ][ k + 1 ] );
  21037. pushVertex( v[ i + 1 ][ k ] );
  21038. }
  21039. }
  21040. }
  21041. }
  21042. function appplyRadius( radius ) {
  21043. var vertex = new Vector3();
  21044. // iterate over the entire buffer and apply the radius to each vertex
  21045. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  21046. vertex.x = vertexBuffer[ i + 0 ];
  21047. vertex.y = vertexBuffer[ i + 1 ];
  21048. vertex.z = vertexBuffer[ i + 2 ];
  21049. vertex.normalize().multiplyScalar( radius );
  21050. vertexBuffer[ i + 0 ] = vertex.x;
  21051. vertexBuffer[ i + 1 ] = vertex.y;
  21052. vertexBuffer[ i + 2 ] = vertex.z;
  21053. }
  21054. }
  21055. function generateUVs() {
  21056. var vertex = new Vector3();
  21057. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  21058. vertex.x = vertexBuffer[ i + 0 ];
  21059. vertex.y = vertexBuffer[ i + 1 ];
  21060. vertex.z = vertexBuffer[ i + 2 ];
  21061. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  21062. var v = inclination( vertex ) / Math.PI + 0.5;
  21063. uvBuffer.push( u, 1 - v );
  21064. }
  21065. correctUVs();
  21066. correctSeam();
  21067. }
  21068. function correctSeam() {
  21069. // handle case when face straddles the seam, see #3269
  21070. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  21071. // uv data of a single face
  21072. var x0 = uvBuffer[ i + 0 ];
  21073. var x1 = uvBuffer[ i + 2 ];
  21074. var x2 = uvBuffer[ i + 4 ];
  21075. var max = Math.max( x0, x1, x2 );
  21076. var min = Math.min( x0, x1, x2 );
  21077. // 0.9 is somewhat arbitrary
  21078. if ( max > 0.9 && min < 0.1 ) {
  21079. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  21080. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  21081. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  21082. }
  21083. }
  21084. }
  21085. function pushVertex( vertex ) {
  21086. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  21087. }
  21088. function getVertexByIndex( index, vertex ) {
  21089. var stride = index * 3;
  21090. vertex.x = vertices[ stride + 0 ];
  21091. vertex.y = vertices[ stride + 1 ];
  21092. vertex.z = vertices[ stride + 2 ];
  21093. }
  21094. function correctUVs() {
  21095. var a = new Vector3();
  21096. var b = new Vector3();
  21097. var c = new Vector3();
  21098. var centroid = new Vector3();
  21099. var uvA = new Vector2();
  21100. var uvB = new Vector2();
  21101. var uvC = new Vector2();
  21102. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21103. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21104. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21105. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21106. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21107. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21108. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21109. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21110. var azi = azimuth( centroid );
  21111. correctUV( uvA, j + 0, a, azi );
  21112. correctUV( uvB, j + 2, b, azi );
  21113. correctUV( uvC, j + 4, c, azi );
  21114. }
  21115. }
  21116. function correctUV( uv, stride, vector, azimuth ) {
  21117. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21118. uvBuffer[ stride ] = uv.x - 1;
  21119. }
  21120. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21121. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21122. }
  21123. }
  21124. // Angle around the Y axis, counter-clockwise when looking from above.
  21125. function azimuth( vector ) {
  21126. return Math.atan2( vector.z, - vector.x );
  21127. }
  21128. // Angle above the XZ plane.
  21129. function inclination( vector ) {
  21130. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21131. }
  21132. }
  21133. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21134. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  21135. /**
  21136. * @author timothypratley / https://github.com/timothypratley
  21137. * @author Mugen87 / https://github.com/Mugen87
  21138. */
  21139. // TetrahedronGeometry
  21140. function TetrahedronGeometry( radius, detail ) {
  21141. Geometry.call( this );
  21142. this.type = 'TetrahedronGeometry';
  21143. this.parameters = {
  21144. radius: radius,
  21145. detail: detail
  21146. };
  21147. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  21148. this.mergeVertices();
  21149. }
  21150. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  21151. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  21152. // TetrahedronBufferGeometry
  21153. function TetrahedronBufferGeometry( radius, detail ) {
  21154. var vertices = [
  21155. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21156. ];
  21157. var indices = [
  21158. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21159. ];
  21160. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21161. this.type = 'TetrahedronBufferGeometry';
  21162. this.parameters = {
  21163. radius: radius,
  21164. detail: detail
  21165. };
  21166. }
  21167. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21168. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  21169. /**
  21170. * @author timothypratley / https://github.com/timothypratley
  21171. * @author Mugen87 / https://github.com/Mugen87
  21172. */
  21173. // OctahedronGeometry
  21174. function OctahedronGeometry( radius, detail ) {
  21175. Geometry.call( this );
  21176. this.type = 'OctahedronGeometry';
  21177. this.parameters = {
  21178. radius: radius,
  21179. detail: detail
  21180. };
  21181. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  21182. this.mergeVertices();
  21183. }
  21184. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  21185. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  21186. // OctahedronBufferGeometry
  21187. function OctahedronBufferGeometry( radius, detail ) {
  21188. var vertices = [
  21189. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21190. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21191. ];
  21192. var indices = [
  21193. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21194. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21195. 1, 3, 4, 1, 4, 2
  21196. ];
  21197. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21198. this.type = 'OctahedronBufferGeometry';
  21199. this.parameters = {
  21200. radius: radius,
  21201. detail: detail
  21202. };
  21203. }
  21204. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21205. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  21206. /**
  21207. * @author timothypratley / https://github.com/timothypratley
  21208. * @author Mugen87 / https://github.com/Mugen87
  21209. */
  21210. // IcosahedronGeometry
  21211. function IcosahedronGeometry( radius, detail ) {
  21212. Geometry.call( this );
  21213. this.type = 'IcosahedronGeometry';
  21214. this.parameters = {
  21215. radius: radius,
  21216. detail: detail
  21217. };
  21218. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  21219. this.mergeVertices();
  21220. }
  21221. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  21222. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  21223. // IcosahedronBufferGeometry
  21224. function IcosahedronBufferGeometry( radius, detail ) {
  21225. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21226. var vertices = [
  21227. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21228. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21229. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21230. ];
  21231. var indices = [
  21232. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21233. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21234. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21235. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21236. ];
  21237. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21238. this.type = 'IcosahedronBufferGeometry';
  21239. this.parameters = {
  21240. radius: radius,
  21241. detail: detail
  21242. };
  21243. }
  21244. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21245. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  21246. /**
  21247. * @author Abe Pazos / https://hamoid.com
  21248. * @author Mugen87 / https://github.com/Mugen87
  21249. */
  21250. // DodecahedronGeometry
  21251. function DodecahedronGeometry( radius, detail ) {
  21252. Geometry.call( this );
  21253. this.type = 'DodecahedronGeometry';
  21254. this.parameters = {
  21255. radius: radius,
  21256. detail: detail
  21257. };
  21258. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  21259. this.mergeVertices();
  21260. }
  21261. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  21262. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  21263. // DodecahedronBufferGeometry
  21264. function DodecahedronBufferGeometry( radius, detail ) {
  21265. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21266. var r = 1 / t;
  21267. var vertices = [
  21268. // (±1, ±1, ±1)
  21269. - 1, - 1, - 1, - 1, - 1, 1,
  21270. - 1, 1, - 1, - 1, 1, 1,
  21271. 1, - 1, - 1, 1, - 1, 1,
  21272. 1, 1, - 1, 1, 1, 1,
  21273. // (0, ±1/φ, ±φ)
  21274. 0, - r, - t, 0, - r, t,
  21275. 0, r, - t, 0, r, t,
  21276. // (±1/φ, ±φ, 0)
  21277. - r, - t, 0, - r, t, 0,
  21278. r, - t, 0, r, t, 0,
  21279. // (±φ, 0, ±1/φ)
  21280. - t, 0, - r, t, 0, - r,
  21281. - t, 0, r, t, 0, r
  21282. ];
  21283. var indices = [
  21284. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21285. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21286. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21287. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21288. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21289. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21290. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21291. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21292. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21293. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21294. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21295. 1, 12, 14, 1, 14, 5, 1, 5, 9
  21296. ];
  21297. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  21298. this.type = 'DodecahedronBufferGeometry';
  21299. this.parameters = {
  21300. radius: radius,
  21301. detail: detail
  21302. };
  21303. }
  21304. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  21305. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  21306. /**
  21307. * @author oosmoxiecode / https://github.com/oosmoxiecode
  21308. * @author WestLangley / https://github.com/WestLangley
  21309. * @author zz85 / https://github.com/zz85
  21310. * @author miningold / https://github.com/miningold
  21311. * @author jonobr1 / https://github.com/jonobr1
  21312. * @author Mugen87 / https://github.com/Mugen87
  21313. *
  21314. */
  21315. // TubeGeometry
  21316. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  21317. Geometry.call( this );
  21318. this.type = 'TubeGeometry';
  21319. this.parameters = {
  21320. path: path,
  21321. tubularSegments: tubularSegments,
  21322. radius: radius,
  21323. radialSegments: radialSegments,
  21324. closed: closed
  21325. };
  21326. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  21327. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  21328. // expose internals
  21329. this.tangents = bufferGeometry.tangents;
  21330. this.normals = bufferGeometry.normals;
  21331. this.binormals = bufferGeometry.binormals;
  21332. // create geometry
  21333. this.fromBufferGeometry( bufferGeometry );
  21334. this.mergeVertices();
  21335. }
  21336. TubeGeometry.prototype = Object.create( Geometry.prototype );
  21337. TubeGeometry.prototype.constructor = TubeGeometry;
  21338. // TubeBufferGeometry
  21339. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  21340. BufferGeometry.call( this );
  21341. this.type = 'TubeBufferGeometry';
  21342. this.parameters = {
  21343. path: path,
  21344. tubularSegments: tubularSegments,
  21345. radius: radius,
  21346. radialSegments: radialSegments,
  21347. closed: closed
  21348. };
  21349. tubularSegments = tubularSegments || 64;
  21350. radius = radius || 1;
  21351. radialSegments = radialSegments || 8;
  21352. closed = closed || false;
  21353. var frames = path.computeFrenetFrames( tubularSegments, closed );
  21354. // expose internals
  21355. this.tangents = frames.tangents;
  21356. this.normals = frames.normals;
  21357. this.binormals = frames.binormals;
  21358. // helper variables
  21359. var vertex = new Vector3();
  21360. var normal = new Vector3();
  21361. var uv = new Vector2();
  21362. var P = new Vector3();
  21363. var i, j;
  21364. // buffer
  21365. var vertices = [];
  21366. var normals = [];
  21367. var uvs = [];
  21368. var indices = [];
  21369. // create buffer data
  21370. generateBufferData();
  21371. // build geometry
  21372. this.setIndex( indices );
  21373. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21374. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21375. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21376. // functions
  21377. function generateBufferData() {
  21378. for ( i = 0; i < tubularSegments; i ++ ) {
  21379. generateSegment( i );
  21380. }
  21381. // if the geometry is not closed, generate the last row of vertices and normals
  21382. // at the regular position on the given path
  21383. //
  21384. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21385. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21386. // uvs are generated in a separate function.
  21387. // this makes it easy compute correct values for closed geometries
  21388. generateUVs();
  21389. // finally create faces
  21390. generateIndices();
  21391. }
  21392. function generateSegment( i ) {
  21393. // we use getPointAt to sample evenly distributed points from the given path
  21394. P = path.getPointAt( i / tubularSegments, P );
  21395. // retrieve corresponding normal and binormal
  21396. var N = frames.normals[ i ];
  21397. var B = frames.binormals[ i ];
  21398. // generate normals and vertices for the current segment
  21399. for ( j = 0; j <= radialSegments; j ++ ) {
  21400. var v = j / radialSegments * Math.PI * 2;
  21401. var sin = Math.sin( v );
  21402. var cos = - Math.cos( v );
  21403. // normal
  21404. normal.x = ( cos * N.x + sin * B.x );
  21405. normal.y = ( cos * N.y + sin * B.y );
  21406. normal.z = ( cos * N.z + sin * B.z );
  21407. normal.normalize();
  21408. normals.push( normal.x, normal.y, normal.z );
  21409. // vertex
  21410. vertex.x = P.x + radius * normal.x;
  21411. vertex.y = P.y + radius * normal.y;
  21412. vertex.z = P.z + radius * normal.z;
  21413. vertices.push( vertex.x, vertex.y, vertex.z );
  21414. }
  21415. }
  21416. function generateIndices() {
  21417. for ( j = 1; j <= tubularSegments; j ++ ) {
  21418. for ( i = 1; i <= radialSegments; i ++ ) {
  21419. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21420. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  21421. var c = ( radialSegments + 1 ) * j + i;
  21422. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21423. // faces
  21424. indices.push( a, b, d );
  21425. indices.push( b, c, d );
  21426. }
  21427. }
  21428. }
  21429. function generateUVs() {
  21430. for ( i = 0; i <= tubularSegments; i ++ ) {
  21431. for ( j = 0; j <= radialSegments; j ++ ) {
  21432. uv.x = i / tubularSegments;
  21433. uv.y = j / radialSegments;
  21434. uvs.push( uv.x, uv.y );
  21435. }
  21436. }
  21437. }
  21438. }
  21439. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21440. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  21441. TubeBufferGeometry.prototype.toJSON = function () {
  21442. var data = BufferGeometry.prototype.toJSON.call( this );
  21443. data.path = this.parameters.path.toJSON();
  21444. return data;
  21445. };
  21446. /**
  21447. * @author oosmoxiecode
  21448. * @author Mugen87 / https://github.com/Mugen87
  21449. *
  21450. * based on http://www.blackpawn.com/texts/pqtorus/
  21451. */
  21452. // TorusKnotGeometry
  21453. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  21454. Geometry.call( this );
  21455. this.type = 'TorusKnotGeometry';
  21456. this.parameters = {
  21457. radius: radius,
  21458. tube: tube,
  21459. tubularSegments: tubularSegments,
  21460. radialSegments: radialSegments,
  21461. p: p,
  21462. q: q
  21463. };
  21464. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  21465. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  21466. this.mergeVertices();
  21467. }
  21468. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  21469. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  21470. // TorusKnotBufferGeometry
  21471. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  21472. BufferGeometry.call( this );
  21473. this.type = 'TorusKnotBufferGeometry';
  21474. this.parameters = {
  21475. radius: radius,
  21476. tube: tube,
  21477. tubularSegments: tubularSegments,
  21478. radialSegments: radialSegments,
  21479. p: p,
  21480. q: q
  21481. };
  21482. radius = radius || 1;
  21483. tube = tube || 0.4;
  21484. tubularSegments = Math.floor( tubularSegments ) || 64;
  21485. radialSegments = Math.floor( radialSegments ) || 8;
  21486. p = p || 2;
  21487. q = q || 3;
  21488. // buffers
  21489. var indices = [];
  21490. var vertices = [];
  21491. var normals = [];
  21492. var uvs = [];
  21493. // helper variables
  21494. var i, j;
  21495. var vertex = new Vector3();
  21496. var normal = new Vector3();
  21497. var P1 = new Vector3();
  21498. var P2 = new Vector3();
  21499. var B = new Vector3();
  21500. var T = new Vector3();
  21501. var N = new Vector3();
  21502. // generate vertices, normals and uvs
  21503. for ( i = 0; i <= tubularSegments; ++ i ) {
  21504. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  21505. var u = i / tubularSegments * p * Math.PI * 2;
  21506. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21507. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21508. calculatePositionOnCurve( u, p, q, radius, P1 );
  21509. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21510. // calculate orthonormal basis
  21511. T.subVectors( P2, P1 );
  21512. N.addVectors( P2, P1 );
  21513. B.crossVectors( T, N );
  21514. N.crossVectors( B, T );
  21515. // normalize B, N. T can be ignored, we don't use it
  21516. B.normalize();
  21517. N.normalize();
  21518. for ( j = 0; j <= radialSegments; ++ j ) {
  21519. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21520. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21521. var v = j / radialSegments * Math.PI * 2;
  21522. var cx = - tube * Math.cos( v );
  21523. var cy = tube * Math.sin( v );
  21524. // now calculate the final vertex position.
  21525. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  21526. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21527. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21528. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21529. vertices.push( vertex.x, vertex.y, vertex.z );
  21530. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21531. normal.subVectors( vertex, P1 ).normalize();
  21532. normals.push( normal.x, normal.y, normal.z );
  21533. // uv
  21534. uvs.push( i / tubularSegments );
  21535. uvs.push( j / radialSegments );
  21536. }
  21537. }
  21538. // generate indices
  21539. for ( j = 1; j <= tubularSegments; j ++ ) {
  21540. for ( i = 1; i <= radialSegments; i ++ ) {
  21541. // indices
  21542. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21543. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  21544. var c = ( radialSegments + 1 ) * j + i;
  21545. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21546. // faces
  21547. indices.push( a, b, d );
  21548. indices.push( b, c, d );
  21549. }
  21550. }
  21551. // build geometry
  21552. this.setIndex( indices );
  21553. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21554. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21555. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21556. // this function calculates the current position on the torus curve
  21557. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21558. var cu = Math.cos( u );
  21559. var su = Math.sin( u );
  21560. var quOverP = q / p * u;
  21561. var cs = Math.cos( quOverP );
  21562. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21563. position.y = radius * ( 2 + cs ) * su * 0.5;
  21564. position.z = radius * Math.sin( quOverP ) * 0.5;
  21565. }
  21566. }
  21567. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21568. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  21569. /**
  21570. * @author oosmoxiecode
  21571. * @author mrdoob / http://mrdoob.com/
  21572. * @author Mugen87 / https://github.com/Mugen87
  21573. */
  21574. // TorusGeometry
  21575. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  21576. Geometry.call( this );
  21577. this.type = 'TorusGeometry';
  21578. this.parameters = {
  21579. radius: radius,
  21580. tube: tube,
  21581. radialSegments: radialSegments,
  21582. tubularSegments: tubularSegments,
  21583. arc: arc
  21584. };
  21585. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  21586. this.mergeVertices();
  21587. }
  21588. TorusGeometry.prototype = Object.create( Geometry.prototype );
  21589. TorusGeometry.prototype.constructor = TorusGeometry;
  21590. // TorusBufferGeometry
  21591. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  21592. BufferGeometry.call( this );
  21593. this.type = 'TorusBufferGeometry';
  21594. this.parameters = {
  21595. radius: radius,
  21596. tube: tube,
  21597. radialSegments: radialSegments,
  21598. tubularSegments: tubularSegments,
  21599. arc: arc
  21600. };
  21601. radius = radius || 1;
  21602. tube = tube || 0.4;
  21603. radialSegments = Math.floor( radialSegments ) || 8;
  21604. tubularSegments = Math.floor( tubularSegments ) || 6;
  21605. arc = arc || Math.PI * 2;
  21606. // buffers
  21607. var indices = [];
  21608. var vertices = [];
  21609. var normals = [];
  21610. var uvs = [];
  21611. // helper variables
  21612. var center = new Vector3();
  21613. var vertex = new Vector3();
  21614. var normal = new Vector3();
  21615. var j, i;
  21616. // generate vertices, normals and uvs
  21617. for ( j = 0; j <= radialSegments; j ++ ) {
  21618. for ( i = 0; i <= tubularSegments; i ++ ) {
  21619. var u = i / tubularSegments * arc;
  21620. var v = j / radialSegments * Math.PI * 2;
  21621. // vertex
  21622. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21623. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21624. vertex.z = tube * Math.sin( v );
  21625. vertices.push( vertex.x, vertex.y, vertex.z );
  21626. // normal
  21627. center.x = radius * Math.cos( u );
  21628. center.y = radius * Math.sin( u );
  21629. normal.subVectors( vertex, center ).normalize();
  21630. normals.push( normal.x, normal.y, normal.z );
  21631. // uv
  21632. uvs.push( i / tubularSegments );
  21633. uvs.push( j / radialSegments );
  21634. }
  21635. }
  21636. // generate indices
  21637. for ( j = 1; j <= radialSegments; j ++ ) {
  21638. for ( i = 1; i <= tubularSegments; i ++ ) {
  21639. // indices
  21640. var a = ( tubularSegments + 1 ) * j + i - 1;
  21641. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21642. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21643. var d = ( tubularSegments + 1 ) * j + i;
  21644. // faces
  21645. indices.push( a, b, d );
  21646. indices.push( b, c, d );
  21647. }
  21648. }
  21649. // build geometry
  21650. this.setIndex( indices );
  21651. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21652. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21653. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21654. }
  21655. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21656. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  21657. /**
  21658. * @author Mugen87 / https://github.com/Mugen87
  21659. * Port from https://github.com/mapbox/earcut (v2.1.2)
  21660. */
  21661. var Earcut = {
  21662. triangulate: function ( data, holeIndices, dim ) {
  21663. dim = dim || 2;
  21664. var hasHoles = holeIndices && holeIndices.length,
  21665. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  21666. outerNode = linkedList( data, 0, outerLen, dim, true ),
  21667. triangles = [];
  21668. if ( ! outerNode ) return triangles;
  21669. var minX, minY, maxX, maxY, x, y, invSize;
  21670. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  21671. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  21672. if ( data.length > 80 * dim ) {
  21673. minX = maxX = data[ 0 ];
  21674. minY = maxY = data[ 1 ];
  21675. for ( var i = dim; i < outerLen; i += dim ) {
  21676. x = data[ i ];
  21677. y = data[ i + 1 ];
  21678. if ( x < minX ) minX = x;
  21679. if ( y < minY ) minY = y;
  21680. if ( x > maxX ) maxX = x;
  21681. if ( y > maxY ) maxY = y;
  21682. }
  21683. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  21684. invSize = Math.max( maxX - minX, maxY - minY );
  21685. invSize = invSize !== 0 ? 1 / invSize : 0;
  21686. }
  21687. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  21688. return triangles;
  21689. }
  21690. };
  21691. // create a circular doubly linked list from polygon points in the specified winding order
  21692. function linkedList( data, start, end, dim, clockwise ) {
  21693. var i, last;
  21694. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  21695. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21696. } else {
  21697. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21698. }
  21699. if ( last && equals( last, last.next ) ) {
  21700. removeNode( last );
  21701. last = last.next;
  21702. }
  21703. return last;
  21704. }
  21705. // eliminate colinear or duplicate points
  21706. function filterPoints( start, end ) {
  21707. if ( ! start ) return start;
  21708. if ( ! end ) end = start;
  21709. var p = start, again;
  21710. do {
  21711. again = false;
  21712. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  21713. removeNode( p );
  21714. p = end = p.prev;
  21715. if ( p === p.next ) break;
  21716. again = true;
  21717. } else {
  21718. p = p.next;
  21719. }
  21720. } while ( again || p !== end );
  21721. return end;
  21722. }
  21723. // main ear slicing loop which triangulates a polygon (given as a linked list)
  21724. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  21725. if ( ! ear ) return;
  21726. // interlink polygon nodes in z-order
  21727. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  21728. var stop = ear, prev, next;
  21729. // iterate through ears, slicing them one by one
  21730. while ( ear.prev !== ear.next ) {
  21731. prev = ear.prev;
  21732. next = ear.next;
  21733. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  21734. // cut off the triangle
  21735. triangles.push( prev.i / dim );
  21736. triangles.push( ear.i / dim );
  21737. triangles.push( next.i / dim );
  21738. removeNode( ear );
  21739. // skipping the next vertice leads to less sliver triangles
  21740. ear = next.next;
  21741. stop = next.next;
  21742. continue;
  21743. }
  21744. ear = next;
  21745. // if we looped through the whole remaining polygon and can't find any more ears
  21746. if ( ear === stop ) {
  21747. // try filtering points and slicing again
  21748. if ( ! pass ) {
  21749. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  21750. // if this didn't work, try curing all small self-intersections locally
  21751. } else if ( pass === 1 ) {
  21752. ear = cureLocalIntersections( ear, triangles, dim );
  21753. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  21754. // as a last resort, try splitting the remaining polygon into two
  21755. } else if ( pass === 2 ) {
  21756. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  21757. }
  21758. break;
  21759. }
  21760. }
  21761. }
  21762. // check whether a polygon node forms a valid ear with adjacent nodes
  21763. function isEar( ear ) {
  21764. var a = ear.prev,
  21765. b = ear,
  21766. c = ear.next;
  21767. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21768. // now make sure we don't have other points inside the potential ear
  21769. var p = ear.next.next;
  21770. while ( p !== ear.prev ) {
  21771. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) {
  21772. return false;
  21773. }
  21774. p = p.next;
  21775. }
  21776. return true;
  21777. }
  21778. function isEarHashed( ear, minX, minY, invSize ) {
  21779. var a = ear.prev,
  21780. b = ear,
  21781. c = ear.next;
  21782. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21783. // triangle bbox; min & max are calculated like this for speed
  21784. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  21785. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  21786. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  21787. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  21788. // z-order range for the current triangle bbox;
  21789. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  21790. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  21791. // first look for points inside the triangle in increasing z-order
  21792. var p = ear.nextZ;
  21793. while ( p && p.z <= maxZ ) {
  21794. if ( p !== ear.prev && p !== ear.next &&
  21795. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  21796. area( p.prev, p, p.next ) >= 0 ) return false;
  21797. p = p.nextZ;
  21798. }
  21799. // then look for points in decreasing z-order
  21800. p = ear.prevZ;
  21801. while ( p && p.z >= minZ ) {
  21802. if ( p !== ear.prev && p !== ear.next &&
  21803. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  21804. area( p.prev, p, p.next ) >= 0 ) return false;
  21805. p = p.prevZ;
  21806. }
  21807. return true;
  21808. }
  21809. // go through all polygon nodes and cure small local self-intersections
  21810. function cureLocalIntersections( start, triangles, dim ) {
  21811. var p = start;
  21812. do {
  21813. var a = p.prev, b = p.next.next;
  21814. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21815. triangles.push( a.i / dim );
  21816. triangles.push( p.i / dim );
  21817. triangles.push( b.i / dim );
  21818. // remove two nodes involved
  21819. removeNode( p );
  21820. removeNode( p.next );
  21821. p = start = b;
  21822. }
  21823. p = p.next;
  21824. } while ( p !== start );
  21825. return p;
  21826. }
  21827. // try splitting polygon into two and triangulate them independently
  21828. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21829. // look for a valid diagonal that divides the polygon into two
  21830. var a = start;
  21831. do {
  21832. var b = a.next.next;
  21833. while ( b !== a.prev ) {
  21834. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21835. // split the polygon in two by the diagonal
  21836. var c = splitPolygon( a, b );
  21837. // filter colinear points around the cuts
  21838. a = filterPoints( a, a.next );
  21839. c = filterPoints( c, c.next );
  21840. // run earcut on each half
  21841. earcutLinked( a, triangles, dim, minX, minY, invSize );
  21842. earcutLinked( c, triangles, dim, minX, minY, invSize );
  21843. return;
  21844. }
  21845. b = b.next;
  21846. }
  21847. a = a.next;
  21848. } while ( a !== start );
  21849. }
  21850. // link every hole into the outer loop, producing a single-ring polygon without holes
  21851. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21852. var queue = [], i, len, start, end, list;
  21853. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21854. start = holeIndices[ i ] * dim;
  21855. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21856. list = linkedList( data, start, end, dim, false );
  21857. if ( list === list.next ) list.steiner = true;
  21858. queue.push( getLeftmost( list ) );
  21859. }
  21860. queue.sort( compareX );
  21861. // process holes from left to right
  21862. for ( i = 0; i < queue.length; i ++ ) {
  21863. eliminateHole( queue[ i ], outerNode );
  21864. outerNode = filterPoints( outerNode, outerNode.next );
  21865. }
  21866. return outerNode;
  21867. }
  21868. function compareX( a, b ) {
  21869. return a.x - b.x;
  21870. }
  21871. // find a bridge between vertices that connects hole with an outer ring and and link it
  21872. function eliminateHole( hole, outerNode ) {
  21873. outerNode = findHoleBridge( hole, outerNode );
  21874. if ( outerNode ) {
  21875. var b = splitPolygon( outerNode, hole );
  21876. filterPoints( b, b.next );
  21877. }
  21878. }
  21879. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21880. function findHoleBridge( hole, outerNode ) {
  21881. var p = outerNode,
  21882. hx = hole.x,
  21883. hy = hole.y,
  21884. qx = - Infinity,
  21885. m;
  21886. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21887. // segment's endpoint with lesser x will be potential connection point
  21888. do {
  21889. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21890. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21891. if ( x <= hx && x > qx ) {
  21892. qx = x;
  21893. if ( x === hx ) {
  21894. if ( hy === p.y ) return p;
  21895. if ( hy === p.next.y ) return p.next;
  21896. }
  21897. m = p.x < p.next.x ? p : p.next;
  21898. }
  21899. }
  21900. p = p.next;
  21901. } while ( p !== outerNode );
  21902. if ( ! m ) return null;
  21903. if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint
  21904. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21905. // if there are no points found, we have a valid connection;
  21906. // otherwise choose the point of the minimum angle with the ray as connection point
  21907. var stop = m,
  21908. mx = m.x,
  21909. my = m.y,
  21910. tanMin = Infinity,
  21911. tan;
  21912. p = m.next;
  21913. while ( p !== stop ) {
  21914. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21915. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21916. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21917. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  21918. m = p;
  21919. tanMin = tan;
  21920. }
  21921. }
  21922. p = p.next;
  21923. }
  21924. return m;
  21925. }
  21926. // interlink polygon nodes in z-order
  21927. function indexCurve( start, minX, minY, invSize ) {
  21928. var p = start;
  21929. do {
  21930. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21931. p.prevZ = p.prev;
  21932. p.nextZ = p.next;
  21933. p = p.next;
  21934. } while ( p !== start );
  21935. p.prevZ.nextZ = null;
  21936. p.prevZ = null;
  21937. sortLinked( p );
  21938. }
  21939. // Simon Tatham's linked list merge sort algorithm
  21940. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21941. function sortLinked( list ) {
  21942. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  21943. do {
  21944. p = list;
  21945. list = null;
  21946. tail = null;
  21947. numMerges = 0;
  21948. while ( p ) {
  21949. numMerges ++;
  21950. q = p;
  21951. pSize = 0;
  21952. for ( i = 0; i < inSize; i ++ ) {
  21953. pSize ++;
  21954. q = q.nextZ;
  21955. if ( ! q ) break;
  21956. }
  21957. qSize = inSize;
  21958. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21959. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21960. e = p;
  21961. p = p.nextZ;
  21962. pSize --;
  21963. } else {
  21964. e = q;
  21965. q = q.nextZ;
  21966. qSize --;
  21967. }
  21968. if ( tail ) tail.nextZ = e;
  21969. else list = e;
  21970. e.prevZ = tail;
  21971. tail = e;
  21972. }
  21973. p = q;
  21974. }
  21975. tail.nextZ = null;
  21976. inSize *= 2;
  21977. } while ( numMerges > 1 );
  21978. return list;
  21979. }
  21980. // z-order of a point given coords and inverse of the longer side of data bbox
  21981. function zOrder( x, y, minX, minY, invSize ) {
  21982. // coords are transformed into non-negative 15-bit integer range
  21983. x = 32767 * ( x - minX ) * invSize;
  21984. y = 32767 * ( y - minY ) * invSize;
  21985. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21986. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21987. x = ( x | ( x << 2 ) ) & 0x33333333;
  21988. x = ( x | ( x << 1 ) ) & 0x55555555;
  21989. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21990. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21991. y = ( y | ( y << 2 ) ) & 0x33333333;
  21992. y = ( y | ( y << 1 ) ) & 0x55555555;
  21993. return x | ( y << 1 );
  21994. }
  21995. // find the leftmost node of a polygon ring
  21996. function getLeftmost( start ) {
  21997. var p = start, leftmost = start;
  21998. do {
  21999. if ( p.x < leftmost.x ) leftmost = p;
  22000. p = p.next;
  22001. } while ( p !== start );
  22002. return leftmost;
  22003. }
  22004. // check if a point lies within a convex triangle
  22005. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22006. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  22007. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  22008. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  22009. }
  22010. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22011. function isValidDiagonal( a, b ) {
  22012. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  22013. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  22014. }
  22015. // signed area of a triangle
  22016. function area( p, q, r ) {
  22017. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22018. }
  22019. // check if two points are equal
  22020. function equals( p1, p2 ) {
  22021. return p1.x === p2.x && p1.y === p2.y;
  22022. }
  22023. // check if two segments intersect
  22024. function intersects( p1, q1, p2, q2 ) {
  22025. if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) ||
  22026. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true;
  22027. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  22028. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  22029. }
  22030. // check if a polygon diagonal intersects any polygon segments
  22031. function intersectsPolygon( a, b ) {
  22032. var p = a;
  22033. do {
  22034. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22035. intersects( p, p.next, a, b ) ) {
  22036. return true;
  22037. }
  22038. p = p.next;
  22039. } while ( p !== a );
  22040. return false;
  22041. }
  22042. // check if a polygon diagonal is locally inside the polygon
  22043. function locallyInside( a, b ) {
  22044. return area( a.prev, a, a.next ) < 0 ?
  22045. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22046. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22047. }
  22048. // check if the middle point of a polygon diagonal is inside the polygon
  22049. function middleInside( a, b ) {
  22050. var p = a,
  22051. inside = false,
  22052. px = ( a.x + b.x ) / 2,
  22053. py = ( a.y + b.y ) / 2;
  22054. do {
  22055. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22056. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) {
  22057. inside = ! inside;
  22058. }
  22059. p = p.next;
  22060. } while ( p !== a );
  22061. return inside;
  22062. }
  22063. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22064. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22065. function splitPolygon( a, b ) {
  22066. var a2 = new Node( a.i, a.x, a.y ),
  22067. b2 = new Node( b.i, b.x, b.y ),
  22068. an = a.next,
  22069. bp = b.prev;
  22070. a.next = b;
  22071. b.prev = a;
  22072. a2.next = an;
  22073. an.prev = a2;
  22074. b2.next = a2;
  22075. a2.prev = b2;
  22076. bp.next = b2;
  22077. b2.prev = bp;
  22078. return b2;
  22079. }
  22080. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22081. function insertNode( i, x, y, last ) {
  22082. var p = new Node( i, x, y );
  22083. if ( ! last ) {
  22084. p.prev = p;
  22085. p.next = p;
  22086. } else {
  22087. p.next = last.next;
  22088. p.prev = last;
  22089. last.next.prev = p;
  22090. last.next = p;
  22091. }
  22092. return p;
  22093. }
  22094. function removeNode( p ) {
  22095. p.next.prev = p.prev;
  22096. p.prev.next = p.next;
  22097. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  22098. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  22099. }
  22100. function Node( i, x, y ) {
  22101. // vertice index in coordinates array
  22102. this.i = i;
  22103. // vertex coordinates
  22104. this.x = x;
  22105. this.y = y;
  22106. // previous and next vertice nodes in a polygon ring
  22107. this.prev = null;
  22108. this.next = null;
  22109. // z-order curve value
  22110. this.z = null;
  22111. // previous and next nodes in z-order
  22112. this.prevZ = null;
  22113. this.nextZ = null;
  22114. // indicates whether this is a steiner point
  22115. this.steiner = false;
  22116. }
  22117. function signedArea( data, start, end, dim ) {
  22118. var sum = 0;
  22119. for ( var i = start, j = end - dim; i < end; i += dim ) {
  22120. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  22121. j = i;
  22122. }
  22123. return sum;
  22124. }
  22125. /**
  22126. * @author zz85 / http://www.lab4games.net/zz85/blog
  22127. */
  22128. var ShapeUtils = {
  22129. // calculate area of the contour polygon
  22130. area: function ( contour ) {
  22131. var n = contour.length;
  22132. var a = 0.0;
  22133. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  22134. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  22135. }
  22136. return a * 0.5;
  22137. },
  22138. isClockWise: function ( pts ) {
  22139. return ShapeUtils.area( pts ) < 0;
  22140. },
  22141. triangulateShape: function ( contour, holes ) {
  22142. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  22143. var holeIndices = []; // array of hole indices
  22144. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  22145. removeDupEndPts( contour );
  22146. addContour( vertices, contour );
  22147. //
  22148. var holeIndex = contour.length;
  22149. holes.forEach( removeDupEndPts );
  22150. for ( var i = 0; i < holes.length; i ++ ) {
  22151. holeIndices.push( holeIndex );
  22152. holeIndex += holes[ i ].length;
  22153. addContour( vertices, holes[ i ] );
  22154. }
  22155. //
  22156. var triangles = Earcut.triangulate( vertices, holeIndices );
  22157. //
  22158. for ( var i = 0; i < triangles.length; i += 3 ) {
  22159. faces.push( triangles.slice( i, i + 3 ) );
  22160. }
  22161. return faces;
  22162. }
  22163. };
  22164. function removeDupEndPts( points ) {
  22165. var l = points.length;
  22166. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  22167. points.pop();
  22168. }
  22169. }
  22170. function addContour( vertices, contour ) {
  22171. for ( var i = 0; i < contour.length; i ++ ) {
  22172. vertices.push( contour[ i ].x );
  22173. vertices.push( contour[ i ].y );
  22174. }
  22175. }
  22176. /**
  22177. * @author zz85 / http://www.lab4games.net/zz85/blog
  22178. *
  22179. * Creates extruded geometry from a path shape.
  22180. *
  22181. * parameters = {
  22182. *
  22183. * curveSegments: <int>, // number of points on the curves
  22184. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  22185. * depth: <float>, // Depth to extrude the shape
  22186. *
  22187. * bevelEnabled: <bool>, // turn on bevel
  22188. * bevelThickness: <float>, // how deep into the original shape bevel goes
  22189. * bevelSize: <float>, // how far from shape outline is bevel
  22190. * bevelSegments: <int>, // number of bevel layers
  22191. *
  22192. * extrudePath: <THREE.Curve> // curve to extrude shape along
  22193. *
  22194. * UVGenerator: <Object> // object that provides UV generator functions
  22195. *
  22196. * }
  22197. */
  22198. // ExtrudeGeometry
  22199. function ExtrudeGeometry( shapes, options ) {
  22200. Geometry.call( this );
  22201. this.type = 'ExtrudeGeometry';
  22202. this.parameters = {
  22203. shapes: shapes,
  22204. options: options
  22205. };
  22206. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  22207. this.mergeVertices();
  22208. }
  22209. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  22210. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  22211. ExtrudeGeometry.prototype.toJSON = function () {
  22212. var data = Geometry.prototype.toJSON.call( this );
  22213. var shapes = this.parameters.shapes;
  22214. var options = this.parameters.options;
  22215. return toJSON( shapes, options, data );
  22216. };
  22217. // ExtrudeBufferGeometry
  22218. function ExtrudeBufferGeometry( shapes, options ) {
  22219. BufferGeometry.call( this );
  22220. this.type = 'ExtrudeBufferGeometry';
  22221. this.parameters = {
  22222. shapes: shapes,
  22223. options: options
  22224. };
  22225. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  22226. var scope = this;
  22227. var verticesArray = [];
  22228. var uvArray = [];
  22229. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22230. var shape = shapes[ i ];
  22231. addShape( shape );
  22232. }
  22233. // build geometry
  22234. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  22235. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  22236. this.computeVertexNormals();
  22237. // functions
  22238. function addShape( shape ) {
  22239. var placeholder = [];
  22240. // options
  22241. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22242. var steps = options.steps !== undefined ? options.steps : 1;
  22243. var depth = options.depth !== undefined ? options.depth : 100;
  22244. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  22245. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  22246. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  22247. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  22248. var extrudePath = options.extrudePath;
  22249. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  22250. // deprecated options
  22251. if ( options.amount !== undefined ) {
  22252. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  22253. depth = options.amount;
  22254. }
  22255. //
  22256. var extrudePts, extrudeByPath = false;
  22257. var splineTube, binormal, normal, position2;
  22258. if ( extrudePath ) {
  22259. extrudePts = extrudePath.getSpacedPoints( steps );
  22260. extrudeByPath = true;
  22261. bevelEnabled = false; // bevels not supported for path extrusion
  22262. // SETUP TNB variables
  22263. // TODO1 - have a .isClosed in spline?
  22264. splineTube = extrudePath.computeFrenetFrames( steps, false );
  22265. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  22266. binormal = new Vector3();
  22267. normal = new Vector3();
  22268. position2 = new Vector3();
  22269. }
  22270. // Safeguards if bevels are not enabled
  22271. if ( ! bevelEnabled ) {
  22272. bevelSegments = 0;
  22273. bevelThickness = 0;
  22274. bevelSize = 0;
  22275. }
  22276. // Variables initialization
  22277. var ahole, h, hl; // looping of holes
  22278. var shapePoints = shape.extractPoints( curveSegments );
  22279. var vertices = shapePoints.shape;
  22280. var holes = shapePoints.holes;
  22281. var reverse = ! ShapeUtils.isClockWise( vertices );
  22282. if ( reverse ) {
  22283. vertices = vertices.reverse();
  22284. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22285. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22286. ahole = holes[ h ];
  22287. if ( ShapeUtils.isClockWise( ahole ) ) {
  22288. holes[ h ] = ahole.reverse();
  22289. }
  22290. }
  22291. }
  22292. var faces = ShapeUtils.triangulateShape( vertices, holes );
  22293. /* Vertices */
  22294. var contour = vertices; // vertices has all points but contour has only points of circumference
  22295. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22296. ahole = holes[ h ];
  22297. vertices = vertices.concat( ahole );
  22298. }
  22299. function scalePt2( pt, vec, size ) {
  22300. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  22301. return vec.clone().multiplyScalar( size ).add( pt );
  22302. }
  22303. var b, bs, t, z,
  22304. vert, vlen = vertices.length,
  22305. face, flen = faces.length;
  22306. // Find directions for point movement
  22307. function getBevelVec( inPt, inPrev, inNext ) {
  22308. // computes for inPt the corresponding point inPt' on a new contour
  22309. // shifted by 1 unit (length of normalized vector) to the left
  22310. // if we walk along contour clockwise, this new contour is outside the old one
  22311. //
  22312. // inPt' is the intersection of the two lines parallel to the two
  22313. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22314. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  22315. // good reading for geometry algorithms (here: line-line intersection)
  22316. // http://geomalgorithms.com/a05-_intersect-1.html
  22317. var v_prev_x = inPt.x - inPrev.x,
  22318. v_prev_y = inPt.y - inPrev.y;
  22319. var v_next_x = inNext.x - inPt.x,
  22320. v_next_y = inNext.y - inPt.y;
  22321. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22322. // check for collinear edges
  22323. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22324. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22325. // not collinear
  22326. // length of vectors for normalizing
  22327. var v_prev_len = Math.sqrt( v_prev_lensq );
  22328. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22329. // shift adjacent points by unit vectors to the left
  22330. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22331. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22332. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22333. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22334. // scaling factor for v_prev to intersection point
  22335. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22336. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22337. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22338. // vector from inPt to intersection point
  22339. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22340. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22341. // Don't normalize!, otherwise sharp corners become ugly
  22342. // but prevent crazy spikes
  22343. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22344. if ( v_trans_lensq <= 2 ) {
  22345. return new Vector2( v_trans_x, v_trans_y );
  22346. } else {
  22347. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22348. }
  22349. } else {
  22350. // handle special case of collinear edges
  22351. var direction_eq = false; // assumes: opposite
  22352. if ( v_prev_x > Number.EPSILON ) {
  22353. if ( v_next_x > Number.EPSILON ) {
  22354. direction_eq = true;
  22355. }
  22356. } else {
  22357. if ( v_prev_x < - Number.EPSILON ) {
  22358. if ( v_next_x < - Number.EPSILON ) {
  22359. direction_eq = true;
  22360. }
  22361. } else {
  22362. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  22363. direction_eq = true;
  22364. }
  22365. }
  22366. }
  22367. if ( direction_eq ) {
  22368. // console.log("Warning: lines are a straight sequence");
  22369. v_trans_x = - v_prev_y;
  22370. v_trans_y = v_prev_x;
  22371. shrink_by = Math.sqrt( v_prev_lensq );
  22372. } else {
  22373. // console.log("Warning: lines are a straight spike");
  22374. v_trans_x = v_prev_x;
  22375. v_trans_y = v_prev_y;
  22376. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  22377. }
  22378. }
  22379. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  22380. }
  22381. var contourMovements = [];
  22382. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22383. if ( j === il ) j = 0;
  22384. if ( k === il ) k = 0;
  22385. // (j)---(i)---(k)
  22386. // console.log('i,j,k', i, j , k)
  22387. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  22388. }
  22389. var holesMovements = [],
  22390. oneHoleMovements, verticesMovements = contourMovements.concat();
  22391. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22392. ahole = holes[ h ];
  22393. oneHoleMovements = [];
  22394. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22395. if ( j === il ) j = 0;
  22396. if ( k === il ) k = 0;
  22397. // (j)---(i)---(k)
  22398. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  22399. }
  22400. holesMovements.push( oneHoleMovements );
  22401. verticesMovements = verticesMovements.concat( oneHoleMovements );
  22402. }
  22403. // Loop bevelSegments, 1 for the front, 1 for the back
  22404. for ( b = 0; b < bevelSegments; b ++ ) {
  22405. //for ( b = bevelSegments; b > 0; b -- ) {
  22406. t = b / bevelSegments;
  22407. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22408. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  22409. // contract shape
  22410. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22411. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22412. v( vert.x, vert.y, - z );
  22413. }
  22414. // expand holes
  22415. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22416. ahole = holes[ h ];
  22417. oneHoleMovements = holesMovements[ h ];
  22418. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22419. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22420. v( vert.x, vert.y, - z );
  22421. }
  22422. }
  22423. }
  22424. bs = bevelSize;
  22425. // Back facing vertices
  22426. for ( i = 0; i < vlen; i ++ ) {
  22427. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22428. if ( ! extrudeByPath ) {
  22429. v( vert.x, vert.y, 0 );
  22430. } else {
  22431. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22432. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22433. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22434. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22435. v( position2.x, position2.y, position2.z );
  22436. }
  22437. }
  22438. // Add stepped vertices...
  22439. // Including front facing vertices
  22440. var s;
  22441. for ( s = 1; s <= steps; s ++ ) {
  22442. for ( i = 0; i < vlen; i ++ ) {
  22443. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22444. if ( ! extrudeByPath ) {
  22445. v( vert.x, vert.y, depth / steps * s );
  22446. } else {
  22447. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22448. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22449. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22450. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22451. v( position2.x, position2.y, position2.z );
  22452. }
  22453. }
  22454. }
  22455. // Add bevel segments planes
  22456. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22457. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  22458. t = b / bevelSegments;
  22459. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22460. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  22461. // contract shape
  22462. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22463. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22464. v( vert.x, vert.y, depth + z );
  22465. }
  22466. // expand holes
  22467. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22468. ahole = holes[ h ];
  22469. oneHoleMovements = holesMovements[ h ];
  22470. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22471. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22472. if ( ! extrudeByPath ) {
  22473. v( vert.x, vert.y, depth + z );
  22474. } else {
  22475. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22476. }
  22477. }
  22478. }
  22479. }
  22480. /* Faces */
  22481. // Top and bottom faces
  22482. buildLidFaces();
  22483. // Sides faces
  22484. buildSideFaces();
  22485. ///// Internal functions
  22486. function buildLidFaces() {
  22487. var start = verticesArray.length / 3;
  22488. if ( bevelEnabled ) {
  22489. var layer = 0; // steps + 1
  22490. var offset = vlen * layer;
  22491. // Bottom faces
  22492. for ( i = 0; i < flen; i ++ ) {
  22493. face = faces[ i ];
  22494. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22495. }
  22496. layer = steps + bevelSegments * 2;
  22497. offset = vlen * layer;
  22498. // Top faces
  22499. for ( i = 0; i < flen; i ++ ) {
  22500. face = faces[ i ];
  22501. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22502. }
  22503. } else {
  22504. // Bottom faces
  22505. for ( i = 0; i < flen; i ++ ) {
  22506. face = faces[ i ];
  22507. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22508. }
  22509. // Top faces
  22510. for ( i = 0; i < flen; i ++ ) {
  22511. face = faces[ i ];
  22512. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22513. }
  22514. }
  22515. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  22516. }
  22517. // Create faces for the z-sides of the shape
  22518. function buildSideFaces() {
  22519. var start = verticesArray.length / 3;
  22520. var layeroffset = 0;
  22521. sidewalls( contour, layeroffset );
  22522. layeroffset += contour.length;
  22523. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22524. ahole = holes[ h ];
  22525. sidewalls( ahole, layeroffset );
  22526. //, true
  22527. layeroffset += ahole.length;
  22528. }
  22529. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  22530. }
  22531. function sidewalls( contour, layeroffset ) {
  22532. var j, k;
  22533. i = contour.length;
  22534. while ( -- i >= 0 ) {
  22535. j = i;
  22536. k = i - 1;
  22537. if ( k < 0 ) k = contour.length - 1;
  22538. //console.log('b', i,j, i-1, k,vertices.length);
  22539. var s = 0,
  22540. sl = steps + bevelSegments * 2;
  22541. for ( s = 0; s < sl; s ++ ) {
  22542. var slen1 = vlen * s;
  22543. var slen2 = vlen * ( s + 1 );
  22544. var a = layeroffset + j + slen1,
  22545. b = layeroffset + k + slen1,
  22546. c = layeroffset + k + slen2,
  22547. d = layeroffset + j + slen2;
  22548. f4( a, b, c, d );
  22549. }
  22550. }
  22551. }
  22552. function v( x, y, z ) {
  22553. placeholder.push( x );
  22554. placeholder.push( y );
  22555. placeholder.push( z );
  22556. }
  22557. function f3( a, b, c ) {
  22558. addVertex( a );
  22559. addVertex( b );
  22560. addVertex( c );
  22561. var nextIndex = verticesArray.length / 3;
  22562. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22563. addUV( uvs[ 0 ] );
  22564. addUV( uvs[ 1 ] );
  22565. addUV( uvs[ 2 ] );
  22566. }
  22567. function f4( a, b, c, d ) {
  22568. addVertex( a );
  22569. addVertex( b );
  22570. addVertex( d );
  22571. addVertex( b );
  22572. addVertex( c );
  22573. addVertex( d );
  22574. var nextIndex = verticesArray.length / 3;
  22575. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22576. addUV( uvs[ 0 ] );
  22577. addUV( uvs[ 1 ] );
  22578. addUV( uvs[ 3 ] );
  22579. addUV( uvs[ 1 ] );
  22580. addUV( uvs[ 2 ] );
  22581. addUV( uvs[ 3 ] );
  22582. }
  22583. function addVertex( index ) {
  22584. verticesArray.push( placeholder[ index * 3 + 0 ] );
  22585. verticesArray.push( placeholder[ index * 3 + 1 ] );
  22586. verticesArray.push( placeholder[ index * 3 + 2 ] );
  22587. }
  22588. function addUV( vector2 ) {
  22589. uvArray.push( vector2.x );
  22590. uvArray.push( vector2.y );
  22591. }
  22592. }
  22593. }
  22594. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22595. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  22596. ExtrudeBufferGeometry.prototype.toJSON = function () {
  22597. var data = BufferGeometry.prototype.toJSON.call( this );
  22598. var shapes = this.parameters.shapes;
  22599. var options = this.parameters.options;
  22600. return toJSON( shapes, options, data );
  22601. };
  22602. //
  22603. var WorldUVGenerator = {
  22604. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  22605. var a_x = vertices[ indexA * 3 ];
  22606. var a_y = vertices[ indexA * 3 + 1 ];
  22607. var b_x = vertices[ indexB * 3 ];
  22608. var b_y = vertices[ indexB * 3 + 1 ];
  22609. var c_x = vertices[ indexC * 3 ];
  22610. var c_y = vertices[ indexC * 3 + 1 ];
  22611. return [
  22612. new Vector2( a_x, a_y ),
  22613. new Vector2( b_x, b_y ),
  22614. new Vector2( c_x, c_y )
  22615. ];
  22616. },
  22617. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  22618. var a_x = vertices[ indexA * 3 ];
  22619. var a_y = vertices[ indexA * 3 + 1 ];
  22620. var a_z = vertices[ indexA * 3 + 2 ];
  22621. var b_x = vertices[ indexB * 3 ];
  22622. var b_y = vertices[ indexB * 3 + 1 ];
  22623. var b_z = vertices[ indexB * 3 + 2 ];
  22624. var c_x = vertices[ indexC * 3 ];
  22625. var c_y = vertices[ indexC * 3 + 1 ];
  22626. var c_z = vertices[ indexC * 3 + 2 ];
  22627. var d_x = vertices[ indexD * 3 ];
  22628. var d_y = vertices[ indexD * 3 + 1 ];
  22629. var d_z = vertices[ indexD * 3 + 2 ];
  22630. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  22631. return [
  22632. new Vector2( a_x, 1 - a_z ),
  22633. new Vector2( b_x, 1 - b_z ),
  22634. new Vector2( c_x, 1 - c_z ),
  22635. new Vector2( d_x, 1 - d_z )
  22636. ];
  22637. } else {
  22638. return [
  22639. new Vector2( a_y, 1 - a_z ),
  22640. new Vector2( b_y, 1 - b_z ),
  22641. new Vector2( c_y, 1 - c_z ),
  22642. new Vector2( d_y, 1 - d_z )
  22643. ];
  22644. }
  22645. }
  22646. };
  22647. function toJSON( shapes, options, data ) {
  22648. //
  22649. data.shapes = [];
  22650. if ( Array.isArray( shapes ) ) {
  22651. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22652. var shape = shapes[ i ];
  22653. data.shapes.push( shape.uuid );
  22654. }
  22655. } else {
  22656. data.shapes.push( shapes.uuid );
  22657. }
  22658. //
  22659. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  22660. return data;
  22661. }
  22662. /**
  22663. * @author zz85 / http://www.lab4games.net/zz85/blog
  22664. * @author alteredq / http://alteredqualia.com/
  22665. *
  22666. * Text = 3D Text
  22667. *
  22668. * parameters = {
  22669. * font: <THREE.Font>, // font
  22670. *
  22671. * size: <float>, // size of the text
  22672. * height: <float>, // thickness to extrude text
  22673. * curveSegments: <int>, // number of points on the curves
  22674. *
  22675. * bevelEnabled: <bool>, // turn on bevel
  22676. * bevelThickness: <float>, // how deep into text bevel goes
  22677. * bevelSize: <float> // how far from text outline is bevel
  22678. * }
  22679. */
  22680. // TextGeometry
  22681. function TextGeometry( text, parameters ) {
  22682. Geometry.call( this );
  22683. this.type = 'TextGeometry';
  22684. this.parameters = {
  22685. text: text,
  22686. parameters: parameters
  22687. };
  22688. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  22689. this.mergeVertices();
  22690. }
  22691. TextGeometry.prototype = Object.create( Geometry.prototype );
  22692. TextGeometry.prototype.constructor = TextGeometry;
  22693. // TextBufferGeometry
  22694. function TextBufferGeometry( text, parameters ) {
  22695. parameters = parameters || {};
  22696. var font = parameters.font;
  22697. if ( ! ( font && font.isFont ) ) {
  22698. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  22699. return new Geometry();
  22700. }
  22701. var shapes = font.generateShapes( text, parameters.size );
  22702. // translate parameters to ExtrudeGeometry API
  22703. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  22704. // defaults
  22705. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  22706. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  22707. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  22708. ExtrudeBufferGeometry.call( this, shapes, parameters );
  22709. this.type = 'TextBufferGeometry';
  22710. }
  22711. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  22712. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  22713. /**
  22714. * @author mrdoob / http://mrdoob.com/
  22715. * @author benaadams / https://twitter.com/ben_a_adams
  22716. * @author Mugen87 / https://github.com/Mugen87
  22717. */
  22718. // SphereGeometry
  22719. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22720. Geometry.call( this );
  22721. this.type = 'SphereGeometry';
  22722. this.parameters = {
  22723. radius: radius,
  22724. widthSegments: widthSegments,
  22725. heightSegments: heightSegments,
  22726. phiStart: phiStart,
  22727. phiLength: phiLength,
  22728. thetaStart: thetaStart,
  22729. thetaLength: thetaLength
  22730. };
  22731. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22732. this.mergeVertices();
  22733. }
  22734. SphereGeometry.prototype = Object.create( Geometry.prototype );
  22735. SphereGeometry.prototype.constructor = SphereGeometry;
  22736. // SphereBufferGeometry
  22737. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22738. BufferGeometry.call( this );
  22739. this.type = 'SphereBufferGeometry';
  22740. this.parameters = {
  22741. radius: radius,
  22742. widthSegments: widthSegments,
  22743. heightSegments: heightSegments,
  22744. phiStart: phiStart,
  22745. phiLength: phiLength,
  22746. thetaStart: thetaStart,
  22747. thetaLength: thetaLength
  22748. };
  22749. radius = radius || 1;
  22750. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22751. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22752. phiStart = phiStart !== undefined ? phiStart : 0;
  22753. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22754. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22755. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22756. var thetaEnd = thetaStart + thetaLength;
  22757. var ix, iy;
  22758. var index = 0;
  22759. var grid = [];
  22760. var vertex = new Vector3();
  22761. var normal = new Vector3();
  22762. // buffers
  22763. var indices = [];
  22764. var vertices = [];
  22765. var normals = [];
  22766. var uvs = [];
  22767. // generate vertices, normals and uvs
  22768. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  22769. var verticesRow = [];
  22770. var v = iy / heightSegments;
  22771. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  22772. var u = ix / widthSegments;
  22773. // vertex
  22774. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22775. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22776. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22777. vertices.push( vertex.x, vertex.y, vertex.z );
  22778. // normal
  22779. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  22780. normals.push( normal.x, normal.y, normal.z );
  22781. // uv
  22782. uvs.push( u, 1 - v );
  22783. verticesRow.push( index ++ );
  22784. }
  22785. grid.push( verticesRow );
  22786. }
  22787. // indices
  22788. for ( iy = 0; iy < heightSegments; iy ++ ) {
  22789. for ( ix = 0; ix < widthSegments; ix ++ ) {
  22790. var a = grid[ iy ][ ix + 1 ];
  22791. var b = grid[ iy ][ ix ];
  22792. var c = grid[ iy + 1 ][ ix ];
  22793. var d = grid[ iy + 1 ][ ix + 1 ];
  22794. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22795. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22796. }
  22797. }
  22798. // build geometry
  22799. this.setIndex( indices );
  22800. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22801. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22802. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22803. }
  22804. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22805. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  22806. /**
  22807. * @author Kaleb Murphy
  22808. * @author Mugen87 / https://github.com/Mugen87
  22809. */
  22810. // RingGeometry
  22811. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22812. Geometry.call( this );
  22813. this.type = 'RingGeometry';
  22814. this.parameters = {
  22815. innerRadius: innerRadius,
  22816. outerRadius: outerRadius,
  22817. thetaSegments: thetaSegments,
  22818. phiSegments: phiSegments,
  22819. thetaStart: thetaStart,
  22820. thetaLength: thetaLength
  22821. };
  22822. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  22823. this.mergeVertices();
  22824. }
  22825. RingGeometry.prototype = Object.create( Geometry.prototype );
  22826. RingGeometry.prototype.constructor = RingGeometry;
  22827. // RingBufferGeometry
  22828. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22829. BufferGeometry.call( this );
  22830. this.type = 'RingBufferGeometry';
  22831. this.parameters = {
  22832. innerRadius: innerRadius,
  22833. outerRadius: outerRadius,
  22834. thetaSegments: thetaSegments,
  22835. phiSegments: phiSegments,
  22836. thetaStart: thetaStart,
  22837. thetaLength: thetaLength
  22838. };
  22839. innerRadius = innerRadius || 0.5;
  22840. outerRadius = outerRadius || 1;
  22841. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22842. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22843. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22844. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  22845. // buffers
  22846. var indices = [];
  22847. var vertices = [];
  22848. var normals = [];
  22849. var uvs = [];
  22850. // some helper variables
  22851. var segment;
  22852. var radius = innerRadius;
  22853. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22854. var vertex = new Vector3();
  22855. var uv = new Vector2();
  22856. var j, i;
  22857. // generate vertices, normals and uvs
  22858. for ( j = 0; j <= phiSegments; j ++ ) {
  22859. for ( i = 0; i <= thetaSegments; i ++ ) {
  22860. // values are generate from the inside of the ring to the outside
  22861. segment = thetaStart + i / thetaSegments * thetaLength;
  22862. // vertex
  22863. vertex.x = radius * Math.cos( segment );
  22864. vertex.y = radius * Math.sin( segment );
  22865. vertices.push( vertex.x, vertex.y, vertex.z );
  22866. // normal
  22867. normals.push( 0, 0, 1 );
  22868. // uv
  22869. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22870. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22871. uvs.push( uv.x, uv.y );
  22872. }
  22873. // increase the radius for next row of vertices
  22874. radius += radiusStep;
  22875. }
  22876. // indices
  22877. for ( j = 0; j < phiSegments; j ++ ) {
  22878. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  22879. for ( i = 0; i < thetaSegments; i ++ ) {
  22880. segment = i + thetaSegmentLevel;
  22881. var a = segment;
  22882. var b = segment + thetaSegments + 1;
  22883. var c = segment + thetaSegments + 2;
  22884. var d = segment + 1;
  22885. // faces
  22886. indices.push( a, b, d );
  22887. indices.push( b, c, d );
  22888. }
  22889. }
  22890. // build geometry
  22891. this.setIndex( indices );
  22892. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22893. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22894. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22895. }
  22896. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22897. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  22898. /**
  22899. * @author zz85 / https://github.com/zz85
  22900. * @author bhouston / http://clara.io
  22901. * @author Mugen87 / https://github.com/Mugen87
  22902. */
  22903. // LatheGeometry
  22904. function LatheGeometry( points, segments, phiStart, phiLength ) {
  22905. Geometry.call( this );
  22906. this.type = 'LatheGeometry';
  22907. this.parameters = {
  22908. points: points,
  22909. segments: segments,
  22910. phiStart: phiStart,
  22911. phiLength: phiLength
  22912. };
  22913. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  22914. this.mergeVertices();
  22915. }
  22916. LatheGeometry.prototype = Object.create( Geometry.prototype );
  22917. LatheGeometry.prototype.constructor = LatheGeometry;
  22918. // LatheBufferGeometry
  22919. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  22920. BufferGeometry.call( this );
  22921. this.type = 'LatheBufferGeometry';
  22922. this.parameters = {
  22923. points: points,
  22924. segments: segments,
  22925. phiStart: phiStart,
  22926. phiLength: phiLength
  22927. };
  22928. segments = Math.floor( segments ) || 12;
  22929. phiStart = phiStart || 0;
  22930. phiLength = phiLength || Math.PI * 2;
  22931. // clamp phiLength so it's in range of [ 0, 2PI ]
  22932. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  22933. // buffers
  22934. var indices = [];
  22935. var vertices = [];
  22936. var uvs = [];
  22937. // helper variables
  22938. var base;
  22939. var inverseSegments = 1.0 / segments;
  22940. var vertex = new Vector3();
  22941. var uv = new Vector2();
  22942. var i, j;
  22943. // generate vertices and uvs
  22944. for ( i = 0; i <= segments; i ++ ) {
  22945. var phi = phiStart + i * inverseSegments * phiLength;
  22946. var sin = Math.sin( phi );
  22947. var cos = Math.cos( phi );
  22948. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  22949. // vertex
  22950. vertex.x = points[ j ].x * sin;
  22951. vertex.y = points[ j ].y;
  22952. vertex.z = points[ j ].x * cos;
  22953. vertices.push( vertex.x, vertex.y, vertex.z );
  22954. // uv
  22955. uv.x = i / segments;
  22956. uv.y = j / ( points.length - 1 );
  22957. uvs.push( uv.x, uv.y );
  22958. }
  22959. }
  22960. // indices
  22961. for ( i = 0; i < segments; i ++ ) {
  22962. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  22963. base = j + i * points.length;
  22964. var a = base;
  22965. var b = base + points.length;
  22966. var c = base + points.length + 1;
  22967. var d = base + 1;
  22968. // faces
  22969. indices.push( a, b, d );
  22970. indices.push( b, c, d );
  22971. }
  22972. }
  22973. // build geometry
  22974. this.setIndex( indices );
  22975. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22976. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22977. // generate normals
  22978. this.computeVertexNormals();
  22979. // if the geometry is closed, we need to average the normals along the seam.
  22980. // because the corresponding vertices are identical (but still have different UVs).
  22981. if ( phiLength === Math.PI * 2 ) {
  22982. var normals = this.attributes.normal.array;
  22983. var n1 = new Vector3();
  22984. var n2 = new Vector3();
  22985. var n = new Vector3();
  22986. // this is the buffer offset for the last line of vertices
  22987. base = segments * points.length * 3;
  22988. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  22989. // select the normal of the vertex in the first line
  22990. n1.x = normals[ j + 0 ];
  22991. n1.y = normals[ j + 1 ];
  22992. n1.z = normals[ j + 2 ];
  22993. // select the normal of the vertex in the last line
  22994. n2.x = normals[ base + j + 0 ];
  22995. n2.y = normals[ base + j + 1 ];
  22996. n2.z = normals[ base + j + 2 ];
  22997. // average normals
  22998. n.addVectors( n1, n2 ).normalize();
  22999. // assign the new values to both normals
  23000. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  23001. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  23002. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  23003. }
  23004. }
  23005. }
  23006. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23007. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  23008. /**
  23009. * @author jonobr1 / http://jonobr1.com
  23010. * @author Mugen87 / https://github.com/Mugen87
  23011. */
  23012. // ShapeGeometry
  23013. function ShapeGeometry( shapes, curveSegments ) {
  23014. Geometry.call( this );
  23015. this.type = 'ShapeGeometry';
  23016. if ( typeof curveSegments === 'object' ) {
  23017. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  23018. curveSegments = curveSegments.curveSegments;
  23019. }
  23020. this.parameters = {
  23021. shapes: shapes,
  23022. curveSegments: curveSegments
  23023. };
  23024. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  23025. this.mergeVertices();
  23026. }
  23027. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  23028. ShapeGeometry.prototype.constructor = ShapeGeometry;
  23029. ShapeGeometry.prototype.toJSON = function () {
  23030. var data = Geometry.prototype.toJSON.call( this );
  23031. var shapes = this.parameters.shapes;
  23032. return toJSON$1( shapes, data );
  23033. };
  23034. // ShapeBufferGeometry
  23035. function ShapeBufferGeometry( shapes, curveSegments ) {
  23036. BufferGeometry.call( this );
  23037. this.type = 'ShapeBufferGeometry';
  23038. this.parameters = {
  23039. shapes: shapes,
  23040. curveSegments: curveSegments
  23041. };
  23042. curveSegments = curveSegments || 12;
  23043. // buffers
  23044. var indices = [];
  23045. var vertices = [];
  23046. var normals = [];
  23047. var uvs = [];
  23048. // helper variables
  23049. var groupStart = 0;
  23050. var groupCount = 0;
  23051. // allow single and array values for "shapes" parameter
  23052. if ( Array.isArray( shapes ) === false ) {
  23053. addShape( shapes );
  23054. } else {
  23055. for ( var i = 0; i < shapes.length; i ++ ) {
  23056. addShape( shapes[ i ] );
  23057. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23058. groupStart += groupCount;
  23059. groupCount = 0;
  23060. }
  23061. }
  23062. // build geometry
  23063. this.setIndex( indices );
  23064. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23065. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23066. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23067. // helper functions
  23068. function addShape( shape ) {
  23069. var i, l, shapeHole;
  23070. var indexOffset = vertices.length / 3;
  23071. var points = shape.extractPoints( curveSegments );
  23072. var shapeVertices = points.shape;
  23073. var shapeHoles = points.holes;
  23074. // check direction of vertices
  23075. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23076. shapeVertices = shapeVertices.reverse();
  23077. }
  23078. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23079. shapeHole = shapeHoles[ i ];
  23080. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23081. shapeHoles[ i ] = shapeHole.reverse();
  23082. }
  23083. }
  23084. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23085. // join vertices of inner and outer paths to a single array
  23086. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23087. shapeHole = shapeHoles[ i ];
  23088. shapeVertices = shapeVertices.concat( shapeHole );
  23089. }
  23090. // vertices, normals, uvs
  23091. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23092. var vertex = shapeVertices[ i ];
  23093. vertices.push( vertex.x, vertex.y, 0 );
  23094. normals.push( 0, 0, 1 );
  23095. uvs.push( vertex.x, vertex.y ); // world uvs
  23096. }
  23097. // incides
  23098. for ( i = 0, l = faces.length; i < l; i ++ ) {
  23099. var face = faces[ i ];
  23100. var a = face[ 0 ] + indexOffset;
  23101. var b = face[ 1 ] + indexOffset;
  23102. var c = face[ 2 ] + indexOffset;
  23103. indices.push( a, b, c );
  23104. groupCount += 3;
  23105. }
  23106. }
  23107. }
  23108. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23109. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  23110. ShapeBufferGeometry.prototype.toJSON = function () {
  23111. var data = BufferGeometry.prototype.toJSON.call( this );
  23112. var shapes = this.parameters.shapes;
  23113. return toJSON$1( shapes, data );
  23114. };
  23115. //
  23116. function toJSON$1( shapes, data ) {
  23117. data.shapes = [];
  23118. if ( Array.isArray( shapes ) ) {
  23119. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  23120. var shape = shapes[ i ];
  23121. data.shapes.push( shape.uuid );
  23122. }
  23123. } else {
  23124. data.shapes.push( shapes.uuid );
  23125. }
  23126. return data;
  23127. }
  23128. /**
  23129. * @author WestLangley / http://github.com/WestLangley
  23130. * @author Mugen87 / https://github.com/Mugen87
  23131. */
  23132. function EdgesGeometry( geometry, thresholdAngle ) {
  23133. BufferGeometry.call( this );
  23134. this.type = 'EdgesGeometry';
  23135. this.parameters = {
  23136. thresholdAngle: thresholdAngle
  23137. };
  23138. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  23139. // buffer
  23140. var vertices = [];
  23141. // helper variables
  23142. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  23143. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  23144. var key, keys = [ 'a', 'b', 'c' ];
  23145. // prepare source geometry
  23146. var geometry2;
  23147. if ( geometry.isBufferGeometry ) {
  23148. geometry2 = new Geometry();
  23149. geometry2.fromBufferGeometry( geometry );
  23150. } else {
  23151. geometry2 = geometry.clone();
  23152. }
  23153. geometry2.mergeVertices();
  23154. geometry2.computeFaceNormals();
  23155. var sourceVertices = geometry2.vertices;
  23156. var faces = geometry2.faces;
  23157. // now create a data structure where each entry represents an edge with its adjoining faces
  23158. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23159. var face = faces[ i ];
  23160. for ( var j = 0; j < 3; j ++ ) {
  23161. edge1 = face[ keys[ j ] ];
  23162. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  23163. edge[ 0 ] = Math.min( edge1, edge2 );
  23164. edge[ 1 ] = Math.max( edge1, edge2 );
  23165. key = edge[ 0 ] + ',' + edge[ 1 ];
  23166. if ( edges[ key ] === undefined ) {
  23167. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  23168. } else {
  23169. edges[ key ].face2 = i;
  23170. }
  23171. }
  23172. }
  23173. // generate vertices
  23174. for ( key in edges ) {
  23175. var e = edges[ key ];
  23176. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  23177. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  23178. var vertex = sourceVertices[ e.index1 ];
  23179. vertices.push( vertex.x, vertex.y, vertex.z );
  23180. vertex = sourceVertices[ e.index2 ];
  23181. vertices.push( vertex.x, vertex.y, vertex.z );
  23182. }
  23183. }
  23184. // build geometry
  23185. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23186. }
  23187. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  23188. EdgesGeometry.prototype.constructor = EdgesGeometry;
  23189. /**
  23190. * @author mrdoob / http://mrdoob.com/
  23191. * @author Mugen87 / https://github.com/Mugen87
  23192. */
  23193. // CylinderGeometry
  23194. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23195. Geometry.call( this );
  23196. this.type = 'CylinderGeometry';
  23197. this.parameters = {
  23198. radiusTop: radiusTop,
  23199. radiusBottom: radiusBottom,
  23200. height: height,
  23201. radialSegments: radialSegments,
  23202. heightSegments: heightSegments,
  23203. openEnded: openEnded,
  23204. thetaStart: thetaStart,
  23205. thetaLength: thetaLength
  23206. };
  23207. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  23208. this.mergeVertices();
  23209. }
  23210. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  23211. CylinderGeometry.prototype.constructor = CylinderGeometry;
  23212. // CylinderBufferGeometry
  23213. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23214. BufferGeometry.call( this );
  23215. this.type = 'CylinderBufferGeometry';
  23216. this.parameters = {
  23217. radiusTop: radiusTop,
  23218. radiusBottom: radiusBottom,
  23219. height: height,
  23220. radialSegments: radialSegments,
  23221. heightSegments: heightSegments,
  23222. openEnded: openEnded,
  23223. thetaStart: thetaStart,
  23224. thetaLength: thetaLength
  23225. };
  23226. var scope = this;
  23227. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  23228. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  23229. height = height || 1;
  23230. radialSegments = Math.floor( radialSegments ) || 8;
  23231. heightSegments = Math.floor( heightSegments ) || 1;
  23232. openEnded = openEnded !== undefined ? openEnded : false;
  23233. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  23234. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23235. // buffers
  23236. var indices = [];
  23237. var vertices = [];
  23238. var normals = [];
  23239. var uvs = [];
  23240. // helper variables
  23241. var index = 0;
  23242. var indexArray = [];
  23243. var halfHeight = height / 2;
  23244. var groupStart = 0;
  23245. // generate geometry
  23246. generateTorso();
  23247. if ( openEnded === false ) {
  23248. if ( radiusTop > 0 ) generateCap( true );
  23249. if ( radiusBottom > 0 ) generateCap( false );
  23250. }
  23251. // build geometry
  23252. this.setIndex( indices );
  23253. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23254. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23255. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23256. function generateTorso() {
  23257. var x, y;
  23258. var normal = new Vector3();
  23259. var vertex = new Vector3();
  23260. var groupCount = 0;
  23261. // this will be used to calculate the normal
  23262. var slope = ( radiusBottom - radiusTop ) / height;
  23263. // generate vertices, normals and uvs
  23264. for ( y = 0; y <= heightSegments; y ++ ) {
  23265. var indexRow = [];
  23266. var v = y / heightSegments;
  23267. // calculate the radius of the current row
  23268. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  23269. for ( x = 0; x <= radialSegments; x ++ ) {
  23270. var u = x / radialSegments;
  23271. var theta = u * thetaLength + thetaStart;
  23272. var sinTheta = Math.sin( theta );
  23273. var cosTheta = Math.cos( theta );
  23274. // vertex
  23275. vertex.x = radius * sinTheta;
  23276. vertex.y = - v * height + halfHeight;
  23277. vertex.z = radius * cosTheta;
  23278. vertices.push( vertex.x, vertex.y, vertex.z );
  23279. // normal
  23280. normal.set( sinTheta, slope, cosTheta ).normalize();
  23281. normals.push( normal.x, normal.y, normal.z );
  23282. // uv
  23283. uvs.push( u, 1 - v );
  23284. // save index of vertex in respective row
  23285. indexRow.push( index ++ );
  23286. }
  23287. // now save vertices of the row in our index array
  23288. indexArray.push( indexRow );
  23289. }
  23290. // generate indices
  23291. for ( x = 0; x < radialSegments; x ++ ) {
  23292. for ( y = 0; y < heightSegments; y ++ ) {
  23293. // we use the index array to access the correct indices
  23294. var a = indexArray[ y ][ x ];
  23295. var b = indexArray[ y + 1 ][ x ];
  23296. var c = indexArray[ y + 1 ][ x + 1 ];
  23297. var d = indexArray[ y ][ x + 1 ];
  23298. // faces
  23299. indices.push( a, b, d );
  23300. indices.push( b, c, d );
  23301. // update group counter
  23302. groupCount += 6;
  23303. }
  23304. }
  23305. // add a group to the geometry. this will ensure multi material support
  23306. scope.addGroup( groupStart, groupCount, 0 );
  23307. // calculate new start value for groups
  23308. groupStart += groupCount;
  23309. }
  23310. function generateCap( top ) {
  23311. var x, centerIndexStart, centerIndexEnd;
  23312. var uv = new Vector2();
  23313. var vertex = new Vector3();
  23314. var groupCount = 0;
  23315. var radius = ( top === true ) ? radiusTop : radiusBottom;
  23316. var sign = ( top === true ) ? 1 : - 1;
  23317. // save the index of the first center vertex
  23318. centerIndexStart = index;
  23319. // first we generate the center vertex data of the cap.
  23320. // because the geometry needs one set of uvs per face,
  23321. // we must generate a center vertex per face/segment
  23322. for ( x = 1; x <= radialSegments; x ++ ) {
  23323. // vertex
  23324. vertices.push( 0, halfHeight * sign, 0 );
  23325. // normal
  23326. normals.push( 0, sign, 0 );
  23327. // uv
  23328. uvs.push( 0.5, 0.5 );
  23329. // increase index
  23330. index ++;
  23331. }
  23332. // save the index of the last center vertex
  23333. centerIndexEnd = index;
  23334. // now we generate the surrounding vertices, normals and uvs
  23335. for ( x = 0; x <= radialSegments; x ++ ) {
  23336. var u = x / radialSegments;
  23337. var theta = u * thetaLength + thetaStart;
  23338. var cosTheta = Math.cos( theta );
  23339. var sinTheta = Math.sin( theta );
  23340. // vertex
  23341. vertex.x = radius * sinTheta;
  23342. vertex.y = halfHeight * sign;
  23343. vertex.z = radius * cosTheta;
  23344. vertices.push( vertex.x, vertex.y, vertex.z );
  23345. // normal
  23346. normals.push( 0, sign, 0 );
  23347. // uv
  23348. uv.x = ( cosTheta * 0.5 ) + 0.5;
  23349. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  23350. uvs.push( uv.x, uv.y );
  23351. // increase index
  23352. index ++;
  23353. }
  23354. // generate indices
  23355. for ( x = 0; x < radialSegments; x ++ ) {
  23356. var c = centerIndexStart + x;
  23357. var i = centerIndexEnd + x;
  23358. if ( top === true ) {
  23359. // face top
  23360. indices.push( i, i + 1, c );
  23361. } else {
  23362. // face bottom
  23363. indices.push( i + 1, i, c );
  23364. }
  23365. groupCount += 3;
  23366. }
  23367. // add a group to the geometry. this will ensure multi material support
  23368. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  23369. // calculate new start value for groups
  23370. groupStart += groupCount;
  23371. }
  23372. }
  23373. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23374. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  23375. /**
  23376. * @author abelnation / http://github.com/abelnation
  23377. */
  23378. // ConeGeometry
  23379. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23380. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23381. this.type = 'ConeGeometry';
  23382. this.parameters = {
  23383. radius: radius,
  23384. height: height,
  23385. radialSegments: radialSegments,
  23386. heightSegments: heightSegments,
  23387. openEnded: openEnded,
  23388. thetaStart: thetaStart,
  23389. thetaLength: thetaLength
  23390. };
  23391. }
  23392. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  23393. ConeGeometry.prototype.constructor = ConeGeometry;
  23394. // ConeBufferGeometry
  23395. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23396. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23397. this.type = 'ConeBufferGeometry';
  23398. this.parameters = {
  23399. radius: radius,
  23400. height: height,
  23401. radialSegments: radialSegments,
  23402. heightSegments: heightSegments,
  23403. openEnded: openEnded,
  23404. thetaStart: thetaStart,
  23405. thetaLength: thetaLength
  23406. };
  23407. }
  23408. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  23409. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  23410. /**
  23411. * @author benaadams / https://twitter.com/ben_a_adams
  23412. * @author Mugen87 / https://github.com/Mugen87
  23413. * @author hughes
  23414. */
  23415. // CircleGeometry
  23416. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  23417. Geometry.call( this );
  23418. this.type = 'CircleGeometry';
  23419. this.parameters = {
  23420. radius: radius,
  23421. segments: segments,
  23422. thetaStart: thetaStart,
  23423. thetaLength: thetaLength
  23424. };
  23425. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  23426. this.mergeVertices();
  23427. }
  23428. CircleGeometry.prototype = Object.create( Geometry.prototype );
  23429. CircleGeometry.prototype.constructor = CircleGeometry;
  23430. // CircleBufferGeometry
  23431. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  23432. BufferGeometry.call( this );
  23433. this.type = 'CircleBufferGeometry';
  23434. this.parameters = {
  23435. radius: radius,
  23436. segments: segments,
  23437. thetaStart: thetaStart,
  23438. thetaLength: thetaLength
  23439. };
  23440. radius = radius || 1;
  23441. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  23442. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23443. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23444. // buffers
  23445. var indices = [];
  23446. var vertices = [];
  23447. var normals = [];
  23448. var uvs = [];
  23449. // helper variables
  23450. var i, s;
  23451. var vertex = new Vector3();
  23452. var uv = new Vector2();
  23453. // center point
  23454. vertices.push( 0, 0, 0 );
  23455. normals.push( 0, 0, 1 );
  23456. uvs.push( 0.5, 0.5 );
  23457. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  23458. var segment = thetaStart + s / segments * thetaLength;
  23459. // vertex
  23460. vertex.x = radius * Math.cos( segment );
  23461. vertex.y = radius * Math.sin( segment );
  23462. vertices.push( vertex.x, vertex.y, vertex.z );
  23463. // normal
  23464. normals.push( 0, 0, 1 );
  23465. // uvs
  23466. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  23467. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  23468. uvs.push( uv.x, uv.y );
  23469. }
  23470. // indices
  23471. for ( i = 1; i <= segments; i ++ ) {
  23472. indices.push( i, i + 1, 0 );
  23473. }
  23474. // build geometry
  23475. this.setIndex( indices );
  23476. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23477. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23478. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23479. }
  23480. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23481. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  23482. var Geometries = /*#__PURE__*/Object.freeze({
  23483. WireframeGeometry: WireframeGeometry,
  23484. ParametricGeometry: ParametricGeometry,
  23485. ParametricBufferGeometry: ParametricBufferGeometry,
  23486. TetrahedronGeometry: TetrahedronGeometry,
  23487. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  23488. OctahedronGeometry: OctahedronGeometry,
  23489. OctahedronBufferGeometry: OctahedronBufferGeometry,
  23490. IcosahedronGeometry: IcosahedronGeometry,
  23491. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  23492. DodecahedronGeometry: DodecahedronGeometry,
  23493. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  23494. PolyhedronGeometry: PolyhedronGeometry,
  23495. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  23496. TubeGeometry: TubeGeometry,
  23497. TubeBufferGeometry: TubeBufferGeometry,
  23498. TorusKnotGeometry: TorusKnotGeometry,
  23499. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  23500. TorusGeometry: TorusGeometry,
  23501. TorusBufferGeometry: TorusBufferGeometry,
  23502. TextGeometry: TextGeometry,
  23503. TextBufferGeometry: TextBufferGeometry,
  23504. SphereGeometry: SphereGeometry,
  23505. SphereBufferGeometry: SphereBufferGeometry,
  23506. RingGeometry: RingGeometry,
  23507. RingBufferGeometry: RingBufferGeometry,
  23508. PlaneGeometry: PlaneGeometry,
  23509. PlaneBufferGeometry: PlaneBufferGeometry,
  23510. LatheGeometry: LatheGeometry,
  23511. LatheBufferGeometry: LatheBufferGeometry,
  23512. ShapeGeometry: ShapeGeometry,
  23513. ShapeBufferGeometry: ShapeBufferGeometry,
  23514. ExtrudeGeometry: ExtrudeGeometry,
  23515. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  23516. EdgesGeometry: EdgesGeometry,
  23517. ConeGeometry: ConeGeometry,
  23518. ConeBufferGeometry: ConeBufferGeometry,
  23519. CylinderGeometry: CylinderGeometry,
  23520. CylinderBufferGeometry: CylinderBufferGeometry,
  23521. CircleGeometry: CircleGeometry,
  23522. CircleBufferGeometry: CircleBufferGeometry,
  23523. BoxGeometry: BoxGeometry,
  23524. BoxBufferGeometry: BoxBufferGeometry
  23525. });
  23526. /**
  23527. * @author mrdoob / http://mrdoob.com/
  23528. *
  23529. * parameters = {
  23530. * color: <THREE.Color>
  23531. * }
  23532. */
  23533. function ShadowMaterial( parameters ) {
  23534. Material.call( this );
  23535. this.type = 'ShadowMaterial';
  23536. this.color = new Color( 0x000000 );
  23537. this.transparent = true;
  23538. this.setValues( parameters );
  23539. }
  23540. ShadowMaterial.prototype = Object.create( Material.prototype );
  23541. ShadowMaterial.prototype.constructor = ShadowMaterial;
  23542. ShadowMaterial.prototype.isShadowMaterial = true;
  23543. ShadowMaterial.prototype.copy = function ( source ) {
  23544. Material.prototype.copy.call( this, source );
  23545. this.color.copy( source.color );
  23546. return this;
  23547. };
  23548. /**
  23549. * @author mrdoob / http://mrdoob.com/
  23550. */
  23551. function RawShaderMaterial( parameters ) {
  23552. ShaderMaterial.call( this, parameters );
  23553. this.type = 'RawShaderMaterial';
  23554. }
  23555. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  23556. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  23557. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  23558. /**
  23559. * @author WestLangley / http://github.com/WestLangley
  23560. *
  23561. * parameters = {
  23562. * color: <hex>,
  23563. * roughness: <float>,
  23564. * metalness: <float>,
  23565. * opacity: <float>,
  23566. *
  23567. * map: new THREE.Texture( <Image> ),
  23568. *
  23569. * lightMap: new THREE.Texture( <Image> ),
  23570. * lightMapIntensity: <float>
  23571. *
  23572. * aoMap: new THREE.Texture( <Image> ),
  23573. * aoMapIntensity: <float>
  23574. *
  23575. * emissive: <hex>,
  23576. * emissiveIntensity: <float>
  23577. * emissiveMap: new THREE.Texture( <Image> ),
  23578. *
  23579. * bumpMap: new THREE.Texture( <Image> ),
  23580. * bumpScale: <float>,
  23581. *
  23582. * normalMap: new THREE.Texture( <Image> ),
  23583. * normalMapType: THREE.TangentSpaceNormalMap,
  23584. * normalScale: <Vector2>,
  23585. *
  23586. * displacementMap: new THREE.Texture( <Image> ),
  23587. * displacementScale: <float>,
  23588. * displacementBias: <float>,
  23589. *
  23590. * roughnessMap: new THREE.Texture( <Image> ),
  23591. *
  23592. * metalnessMap: new THREE.Texture( <Image> ),
  23593. *
  23594. * alphaMap: new THREE.Texture( <Image> ),
  23595. *
  23596. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23597. * envMapIntensity: <float>
  23598. *
  23599. * refractionRatio: <float>,
  23600. *
  23601. * wireframe: <boolean>,
  23602. * wireframeLinewidth: <float>,
  23603. *
  23604. * skinning: <bool>,
  23605. * morphTargets: <bool>,
  23606. * morphNormals: <bool>
  23607. * }
  23608. */
  23609. function MeshStandardMaterial( parameters ) {
  23610. Material.call( this );
  23611. this.defines = { 'STANDARD': '' };
  23612. this.type = 'MeshStandardMaterial';
  23613. this.color = new Color( 0xffffff ); // diffuse
  23614. this.roughness = 0.5;
  23615. this.metalness = 0.5;
  23616. this.map = null;
  23617. this.lightMap = null;
  23618. this.lightMapIntensity = 1.0;
  23619. this.aoMap = null;
  23620. this.aoMapIntensity = 1.0;
  23621. this.emissive = new Color( 0x000000 );
  23622. this.emissiveIntensity = 1.0;
  23623. this.emissiveMap = null;
  23624. this.bumpMap = null;
  23625. this.bumpScale = 1;
  23626. this.normalMap = null;
  23627. this.normalMapType = TangentSpaceNormalMap;
  23628. this.normalScale = new Vector2( 1, 1 );
  23629. this.displacementMap = null;
  23630. this.displacementScale = 1;
  23631. this.displacementBias = 0;
  23632. this.roughnessMap = null;
  23633. this.metalnessMap = null;
  23634. this.alphaMap = null;
  23635. this.envMap = null;
  23636. this.envMapIntensity = 1.0;
  23637. this.refractionRatio = 0.98;
  23638. this.wireframe = false;
  23639. this.wireframeLinewidth = 1;
  23640. this.wireframeLinecap = 'round';
  23641. this.wireframeLinejoin = 'round';
  23642. this.skinning = false;
  23643. this.morphTargets = false;
  23644. this.morphNormals = false;
  23645. this.setValues( parameters );
  23646. }
  23647. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  23648. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  23649. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  23650. MeshStandardMaterial.prototype.copy = function ( source ) {
  23651. Material.prototype.copy.call( this, source );
  23652. this.defines = { 'STANDARD': '' };
  23653. this.color.copy( source.color );
  23654. this.roughness = source.roughness;
  23655. this.metalness = source.metalness;
  23656. this.map = source.map;
  23657. this.lightMap = source.lightMap;
  23658. this.lightMapIntensity = source.lightMapIntensity;
  23659. this.aoMap = source.aoMap;
  23660. this.aoMapIntensity = source.aoMapIntensity;
  23661. this.emissive.copy( source.emissive );
  23662. this.emissiveMap = source.emissiveMap;
  23663. this.emissiveIntensity = source.emissiveIntensity;
  23664. this.bumpMap = source.bumpMap;
  23665. this.bumpScale = source.bumpScale;
  23666. this.normalMap = source.normalMap;
  23667. this.normalMapType = source.normalMapType;
  23668. this.normalScale.copy( source.normalScale );
  23669. this.displacementMap = source.displacementMap;
  23670. this.displacementScale = source.displacementScale;
  23671. this.displacementBias = source.displacementBias;
  23672. this.roughnessMap = source.roughnessMap;
  23673. this.metalnessMap = source.metalnessMap;
  23674. this.alphaMap = source.alphaMap;
  23675. this.envMap = source.envMap;
  23676. this.envMapIntensity = source.envMapIntensity;
  23677. this.refractionRatio = source.refractionRatio;
  23678. this.wireframe = source.wireframe;
  23679. this.wireframeLinewidth = source.wireframeLinewidth;
  23680. this.wireframeLinecap = source.wireframeLinecap;
  23681. this.wireframeLinejoin = source.wireframeLinejoin;
  23682. this.skinning = source.skinning;
  23683. this.morphTargets = source.morphTargets;
  23684. this.morphNormals = source.morphNormals;
  23685. return this;
  23686. };
  23687. /**
  23688. * @author WestLangley / http://github.com/WestLangley
  23689. *
  23690. * parameters = {
  23691. * reflectivity: <float>
  23692. * clearCoat: <float>
  23693. * clearCoatRoughness: <float>
  23694. * }
  23695. */
  23696. function MeshPhysicalMaterial( parameters ) {
  23697. MeshStandardMaterial.call( this );
  23698. this.defines = { 'PHYSICAL': '' };
  23699. this.type = 'MeshPhysicalMaterial';
  23700. this.reflectivity = 0.5; // maps to F0 = 0.04
  23701. this.clearCoat = 0.0;
  23702. this.clearCoatRoughness = 0.0;
  23703. this.setValues( parameters );
  23704. }
  23705. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  23706. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  23707. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  23708. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  23709. MeshStandardMaterial.prototype.copy.call( this, source );
  23710. this.defines = { 'PHYSICAL': '' };
  23711. this.reflectivity = source.reflectivity;
  23712. this.clearCoat = source.clearCoat;
  23713. this.clearCoatRoughness = source.clearCoatRoughness;
  23714. return this;
  23715. };
  23716. /**
  23717. * @author mrdoob / http://mrdoob.com/
  23718. * @author alteredq / http://alteredqualia.com/
  23719. *
  23720. * parameters = {
  23721. * color: <hex>,
  23722. * specular: <hex>,
  23723. * shininess: <float>,
  23724. * opacity: <float>,
  23725. *
  23726. * map: new THREE.Texture( <Image> ),
  23727. *
  23728. * lightMap: new THREE.Texture( <Image> ),
  23729. * lightMapIntensity: <float>
  23730. *
  23731. * aoMap: new THREE.Texture( <Image> ),
  23732. * aoMapIntensity: <float>
  23733. *
  23734. * emissive: <hex>,
  23735. * emissiveIntensity: <float>
  23736. * emissiveMap: new THREE.Texture( <Image> ),
  23737. *
  23738. * bumpMap: new THREE.Texture( <Image> ),
  23739. * bumpScale: <float>,
  23740. *
  23741. * normalMap: new THREE.Texture( <Image> ),
  23742. * normalMapType: THREE.TangentSpaceNormalMap,
  23743. * normalScale: <Vector2>,
  23744. *
  23745. * displacementMap: new THREE.Texture( <Image> ),
  23746. * displacementScale: <float>,
  23747. * displacementBias: <float>,
  23748. *
  23749. * specularMap: new THREE.Texture( <Image> ),
  23750. *
  23751. * alphaMap: new THREE.Texture( <Image> ),
  23752. *
  23753. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23754. * combine: THREE.Multiply,
  23755. * reflectivity: <float>,
  23756. * refractionRatio: <float>,
  23757. *
  23758. * wireframe: <boolean>,
  23759. * wireframeLinewidth: <float>,
  23760. *
  23761. * skinning: <bool>,
  23762. * morphTargets: <bool>,
  23763. * morphNormals: <bool>
  23764. * }
  23765. */
  23766. function MeshPhongMaterial( parameters ) {
  23767. Material.call( this );
  23768. this.type = 'MeshPhongMaterial';
  23769. this.color = new Color( 0xffffff ); // diffuse
  23770. this.specular = new Color( 0x111111 );
  23771. this.shininess = 30;
  23772. this.map = null;
  23773. this.lightMap = null;
  23774. this.lightMapIntensity = 1.0;
  23775. this.aoMap = null;
  23776. this.aoMapIntensity = 1.0;
  23777. this.emissive = new Color( 0x000000 );
  23778. this.emissiveIntensity = 1.0;
  23779. this.emissiveMap = null;
  23780. this.bumpMap = null;
  23781. this.bumpScale = 1;
  23782. this.normalMap = null;
  23783. this.normalMapType = TangentSpaceNormalMap;
  23784. this.normalScale = new Vector2( 1, 1 );
  23785. this.displacementMap = null;
  23786. this.displacementScale = 1;
  23787. this.displacementBias = 0;
  23788. this.specularMap = null;
  23789. this.alphaMap = null;
  23790. this.envMap = null;
  23791. this.combine = MultiplyOperation;
  23792. this.reflectivity = 1;
  23793. this.refractionRatio = 0.98;
  23794. this.wireframe = false;
  23795. this.wireframeLinewidth = 1;
  23796. this.wireframeLinecap = 'round';
  23797. this.wireframeLinejoin = 'round';
  23798. this.skinning = false;
  23799. this.morphTargets = false;
  23800. this.morphNormals = false;
  23801. this.setValues( parameters );
  23802. }
  23803. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  23804. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  23805. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  23806. MeshPhongMaterial.prototype.copy = function ( source ) {
  23807. Material.prototype.copy.call( this, source );
  23808. this.color.copy( source.color );
  23809. this.specular.copy( source.specular );
  23810. this.shininess = source.shininess;
  23811. this.map = source.map;
  23812. this.lightMap = source.lightMap;
  23813. this.lightMapIntensity = source.lightMapIntensity;
  23814. this.aoMap = source.aoMap;
  23815. this.aoMapIntensity = source.aoMapIntensity;
  23816. this.emissive.copy( source.emissive );
  23817. this.emissiveMap = source.emissiveMap;
  23818. this.emissiveIntensity = source.emissiveIntensity;
  23819. this.bumpMap = source.bumpMap;
  23820. this.bumpScale = source.bumpScale;
  23821. this.normalMap = source.normalMap;
  23822. this.normalMapType = source.normalMapType;
  23823. this.normalScale.copy( source.normalScale );
  23824. this.displacementMap = source.displacementMap;
  23825. this.displacementScale = source.displacementScale;
  23826. this.displacementBias = source.displacementBias;
  23827. this.specularMap = source.specularMap;
  23828. this.alphaMap = source.alphaMap;
  23829. this.envMap = source.envMap;
  23830. this.combine = source.combine;
  23831. this.reflectivity = source.reflectivity;
  23832. this.refractionRatio = source.refractionRatio;
  23833. this.wireframe = source.wireframe;
  23834. this.wireframeLinewidth = source.wireframeLinewidth;
  23835. this.wireframeLinecap = source.wireframeLinecap;
  23836. this.wireframeLinejoin = source.wireframeLinejoin;
  23837. this.skinning = source.skinning;
  23838. this.morphTargets = source.morphTargets;
  23839. this.morphNormals = source.morphNormals;
  23840. return this;
  23841. };
  23842. /**
  23843. * @author takahirox / http://github.com/takahirox
  23844. *
  23845. * parameters = {
  23846. * gradientMap: new THREE.Texture( <Image> )
  23847. * }
  23848. */
  23849. function MeshToonMaterial( parameters ) {
  23850. MeshPhongMaterial.call( this );
  23851. this.defines = { 'TOON': '' };
  23852. this.type = 'MeshToonMaterial';
  23853. this.gradientMap = null;
  23854. this.setValues( parameters );
  23855. }
  23856. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  23857. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  23858. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  23859. MeshToonMaterial.prototype.copy = function ( source ) {
  23860. MeshPhongMaterial.prototype.copy.call( this, source );
  23861. this.gradientMap = source.gradientMap;
  23862. return this;
  23863. };
  23864. /**
  23865. * @author mrdoob / http://mrdoob.com/
  23866. * @author WestLangley / http://github.com/WestLangley
  23867. *
  23868. * parameters = {
  23869. * opacity: <float>,
  23870. *
  23871. * bumpMap: new THREE.Texture( <Image> ),
  23872. * bumpScale: <float>,
  23873. *
  23874. * normalMap: new THREE.Texture( <Image> ),
  23875. * normalMapType: THREE.TangentSpaceNormalMap,
  23876. * normalScale: <Vector2>,
  23877. *
  23878. * displacementMap: new THREE.Texture( <Image> ),
  23879. * displacementScale: <float>,
  23880. * displacementBias: <float>,
  23881. *
  23882. * wireframe: <boolean>,
  23883. * wireframeLinewidth: <float>
  23884. *
  23885. * skinning: <bool>,
  23886. * morphTargets: <bool>,
  23887. * morphNormals: <bool>
  23888. * }
  23889. */
  23890. function MeshNormalMaterial( parameters ) {
  23891. Material.call( this );
  23892. this.type = 'MeshNormalMaterial';
  23893. this.bumpMap = null;
  23894. this.bumpScale = 1;
  23895. this.normalMap = null;
  23896. this.normalMapType = TangentSpaceNormalMap;
  23897. this.normalScale = new Vector2( 1, 1 );
  23898. this.displacementMap = null;
  23899. this.displacementScale = 1;
  23900. this.displacementBias = 0;
  23901. this.wireframe = false;
  23902. this.wireframeLinewidth = 1;
  23903. this.fog = false;
  23904. this.lights = false;
  23905. this.skinning = false;
  23906. this.morphTargets = false;
  23907. this.morphNormals = false;
  23908. this.setValues( parameters );
  23909. }
  23910. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  23911. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  23912. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  23913. MeshNormalMaterial.prototype.copy = function ( source ) {
  23914. Material.prototype.copy.call( this, source );
  23915. this.bumpMap = source.bumpMap;
  23916. this.bumpScale = source.bumpScale;
  23917. this.normalMap = source.normalMap;
  23918. this.normalMapType = source.normalMapType;
  23919. this.normalScale.copy( source.normalScale );
  23920. this.displacementMap = source.displacementMap;
  23921. this.displacementScale = source.displacementScale;
  23922. this.displacementBias = source.displacementBias;
  23923. this.wireframe = source.wireframe;
  23924. this.wireframeLinewidth = source.wireframeLinewidth;
  23925. this.skinning = source.skinning;
  23926. this.morphTargets = source.morphTargets;
  23927. this.morphNormals = source.morphNormals;
  23928. return this;
  23929. };
  23930. /**
  23931. * @author mrdoob / http://mrdoob.com/
  23932. * @author alteredq / http://alteredqualia.com/
  23933. *
  23934. * parameters = {
  23935. * color: <hex>,
  23936. * opacity: <float>,
  23937. *
  23938. * map: new THREE.Texture( <Image> ),
  23939. *
  23940. * lightMap: new THREE.Texture( <Image> ),
  23941. * lightMapIntensity: <float>
  23942. *
  23943. * aoMap: new THREE.Texture( <Image> ),
  23944. * aoMapIntensity: <float>
  23945. *
  23946. * emissive: <hex>,
  23947. * emissiveIntensity: <float>
  23948. * emissiveMap: new THREE.Texture( <Image> ),
  23949. *
  23950. * specularMap: new THREE.Texture( <Image> ),
  23951. *
  23952. * alphaMap: new THREE.Texture( <Image> ),
  23953. *
  23954. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  23955. * combine: THREE.Multiply,
  23956. * reflectivity: <float>,
  23957. * refractionRatio: <float>,
  23958. *
  23959. * wireframe: <boolean>,
  23960. * wireframeLinewidth: <float>,
  23961. *
  23962. * skinning: <bool>,
  23963. * morphTargets: <bool>,
  23964. * morphNormals: <bool>
  23965. * }
  23966. */
  23967. function MeshLambertMaterial( parameters ) {
  23968. Material.call( this );
  23969. this.type = 'MeshLambertMaterial';
  23970. this.color = new Color( 0xffffff ); // diffuse
  23971. this.map = null;
  23972. this.lightMap = null;
  23973. this.lightMapIntensity = 1.0;
  23974. this.aoMap = null;
  23975. this.aoMapIntensity = 1.0;
  23976. this.emissive = new Color( 0x000000 );
  23977. this.emissiveIntensity = 1.0;
  23978. this.emissiveMap = null;
  23979. this.specularMap = null;
  23980. this.alphaMap = null;
  23981. this.envMap = null;
  23982. this.combine = MultiplyOperation;
  23983. this.reflectivity = 1;
  23984. this.refractionRatio = 0.98;
  23985. this.wireframe = false;
  23986. this.wireframeLinewidth = 1;
  23987. this.wireframeLinecap = 'round';
  23988. this.wireframeLinejoin = 'round';
  23989. this.skinning = false;
  23990. this.morphTargets = false;
  23991. this.morphNormals = false;
  23992. this.setValues( parameters );
  23993. }
  23994. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  23995. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  23996. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  23997. MeshLambertMaterial.prototype.copy = function ( source ) {
  23998. Material.prototype.copy.call( this, source );
  23999. this.color.copy( source.color );
  24000. this.map = source.map;
  24001. this.lightMap = source.lightMap;
  24002. this.lightMapIntensity = source.lightMapIntensity;
  24003. this.aoMap = source.aoMap;
  24004. this.aoMapIntensity = source.aoMapIntensity;
  24005. this.emissive.copy( source.emissive );
  24006. this.emissiveMap = source.emissiveMap;
  24007. this.emissiveIntensity = source.emissiveIntensity;
  24008. this.specularMap = source.specularMap;
  24009. this.alphaMap = source.alphaMap;
  24010. this.envMap = source.envMap;
  24011. this.combine = source.combine;
  24012. this.reflectivity = source.reflectivity;
  24013. this.refractionRatio = source.refractionRatio;
  24014. this.wireframe = source.wireframe;
  24015. this.wireframeLinewidth = source.wireframeLinewidth;
  24016. this.wireframeLinecap = source.wireframeLinecap;
  24017. this.wireframeLinejoin = source.wireframeLinejoin;
  24018. this.skinning = source.skinning;
  24019. this.morphTargets = source.morphTargets;
  24020. this.morphNormals = source.morphNormals;
  24021. return this;
  24022. };
  24023. /**
  24024. * @author WestLangley / http://github.com/WestLangley
  24025. *
  24026. * parameters = {
  24027. * color: <hex>,
  24028. * opacity: <float>,
  24029. *
  24030. * matcap: new THREE.Texture( <Image> ),
  24031. *
  24032. * map: new THREE.Texture( <Image> ),
  24033. *
  24034. * bumpMap: new THREE.Texture( <Image> ),
  24035. * bumpScale: <float>,
  24036. *
  24037. * normalMap: new THREE.Texture( <Image> ),
  24038. * normalMapType: THREE.TangentSpaceNormalMap,
  24039. * normalScale: <Vector2>,
  24040. *
  24041. * displacementMap: new THREE.Texture( <Image> ),
  24042. * displacementScale: <float>,
  24043. * displacementBias: <float>,
  24044. *
  24045. * alphaMap: new THREE.Texture( <Image> ),
  24046. *
  24047. * skinning: <bool>,
  24048. * morphTargets: <bool>,
  24049. * morphNormals: <bool>
  24050. * }
  24051. */
  24052. function MeshMatcapMaterial( parameters ) {
  24053. Material.call( this );
  24054. this.defines = { 'MATCAP': '' };
  24055. this.type = 'MeshMatcapMaterial';
  24056. this.color = new Color( 0xffffff ); // diffuse
  24057. this.matcap = null;
  24058. this.map = null;
  24059. this.bumpMap = null;
  24060. this.bumpScale = 1;
  24061. this.normalMap = null;
  24062. this.normalMapType = TangentSpaceNormalMap;
  24063. this.normalScale = new Vector2( 1, 1 );
  24064. this.displacementMap = null;
  24065. this.displacementScale = 1;
  24066. this.displacementBias = 0;
  24067. this.alphaMap = null;
  24068. this.skinning = false;
  24069. this.morphTargets = false;
  24070. this.morphNormals = false;
  24071. this.lights = false;
  24072. this.setValues( parameters );
  24073. }
  24074. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  24075. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  24076. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  24077. MeshMatcapMaterial.prototype.copy = function ( source ) {
  24078. Material.prototype.copy.call( this, source );
  24079. this.defines = { 'MATCAP': '' };
  24080. this.color.copy( source.color );
  24081. this.matcap = source.matcap;
  24082. this.map = source.map;
  24083. this.bumpMap = source.bumpMap;
  24084. this.bumpScale = source.bumpScale;
  24085. this.normalMap = source.normalMap;
  24086. this.normalMapType = source.normalMapType;
  24087. this.normalScale.copy( source.normalScale );
  24088. this.displacementMap = source.displacementMap;
  24089. this.displacementScale = source.displacementScale;
  24090. this.displacementBias = source.displacementBias;
  24091. this.alphaMap = source.alphaMap;
  24092. this.skinning = source.skinning;
  24093. this.morphTargets = source.morphTargets;
  24094. this.morphNormals = source.morphNormals;
  24095. return this;
  24096. };
  24097. /**
  24098. * @author alteredq / http://alteredqualia.com/
  24099. *
  24100. * parameters = {
  24101. * color: <hex>,
  24102. * opacity: <float>,
  24103. *
  24104. * linewidth: <float>,
  24105. *
  24106. * scale: <float>,
  24107. * dashSize: <float>,
  24108. * gapSize: <float>
  24109. * }
  24110. */
  24111. function LineDashedMaterial( parameters ) {
  24112. LineBasicMaterial.call( this );
  24113. this.type = 'LineDashedMaterial';
  24114. this.scale = 1;
  24115. this.dashSize = 3;
  24116. this.gapSize = 1;
  24117. this.setValues( parameters );
  24118. }
  24119. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  24120. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  24121. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  24122. LineDashedMaterial.prototype.copy = function ( source ) {
  24123. LineBasicMaterial.prototype.copy.call( this, source );
  24124. this.scale = source.scale;
  24125. this.dashSize = source.dashSize;
  24126. this.gapSize = source.gapSize;
  24127. return this;
  24128. };
  24129. var Materials = /*#__PURE__*/Object.freeze({
  24130. ShadowMaterial: ShadowMaterial,
  24131. SpriteMaterial: SpriteMaterial,
  24132. RawShaderMaterial: RawShaderMaterial,
  24133. ShaderMaterial: ShaderMaterial,
  24134. PointsMaterial: PointsMaterial,
  24135. MeshPhysicalMaterial: MeshPhysicalMaterial,
  24136. MeshStandardMaterial: MeshStandardMaterial,
  24137. MeshPhongMaterial: MeshPhongMaterial,
  24138. MeshToonMaterial: MeshToonMaterial,
  24139. MeshNormalMaterial: MeshNormalMaterial,
  24140. MeshLambertMaterial: MeshLambertMaterial,
  24141. MeshDepthMaterial: MeshDepthMaterial,
  24142. MeshDistanceMaterial: MeshDistanceMaterial,
  24143. MeshBasicMaterial: MeshBasicMaterial,
  24144. MeshMatcapMaterial: MeshMatcapMaterial,
  24145. LineDashedMaterial: LineDashedMaterial,
  24146. LineBasicMaterial: LineBasicMaterial,
  24147. Material: Material
  24148. });
  24149. /**
  24150. * @author tschw
  24151. * @author Ben Houston / http://clara.io/
  24152. * @author David Sarno / http://lighthaus.us/
  24153. */
  24154. var AnimationUtils = {
  24155. // same as Array.prototype.slice, but also works on typed arrays
  24156. arraySlice: function ( array, from, to ) {
  24157. if ( AnimationUtils.isTypedArray( array ) ) {
  24158. // in ios9 array.subarray(from, undefined) will return empty array
  24159. // but array.subarray(from) or array.subarray(from, len) is correct
  24160. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  24161. }
  24162. return array.slice( from, to );
  24163. },
  24164. // converts an array to a specific type
  24165. convertArray: function ( array, type, forceClone ) {
  24166. if ( ! array || // let 'undefined' and 'null' pass
  24167. ! forceClone && array.constructor === type ) return array;
  24168. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24169. return new type( array ); // create typed array
  24170. }
  24171. return Array.prototype.slice.call( array ); // create Array
  24172. },
  24173. isTypedArray: function ( object ) {
  24174. return ArrayBuffer.isView( object ) &&
  24175. ! ( object instanceof DataView );
  24176. },
  24177. // returns an array by which times and values can be sorted
  24178. getKeyframeOrder: function ( times ) {
  24179. function compareTime( i, j ) {
  24180. return times[ i ] - times[ j ];
  24181. }
  24182. var n = times.length;
  24183. var result = new Array( n );
  24184. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  24185. result.sort( compareTime );
  24186. return result;
  24187. },
  24188. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24189. sortedArray: function ( values, stride, order ) {
  24190. var nValues = values.length;
  24191. var result = new values.constructor( nValues );
  24192. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24193. var srcOffset = order[ i ] * stride;
  24194. for ( var j = 0; j !== stride; ++ j ) {
  24195. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24196. }
  24197. }
  24198. return result;
  24199. },
  24200. // function for parsing AOS keyframe formats
  24201. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  24202. var i = 1, key = jsonKeys[ 0 ];
  24203. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24204. key = jsonKeys[ i ++ ];
  24205. }
  24206. if ( key === undefined ) return; // no data
  24207. var value = key[ valuePropertyName ];
  24208. if ( value === undefined ) return; // no data
  24209. if ( Array.isArray( value ) ) {
  24210. do {
  24211. value = key[ valuePropertyName ];
  24212. if ( value !== undefined ) {
  24213. times.push( key.time );
  24214. values.push.apply( values, value ); // push all elements
  24215. }
  24216. key = jsonKeys[ i ++ ];
  24217. } while ( key !== undefined );
  24218. } else if ( value.toArray !== undefined ) {
  24219. // ...assume THREE.Math-ish
  24220. do {
  24221. value = key[ valuePropertyName ];
  24222. if ( value !== undefined ) {
  24223. times.push( key.time );
  24224. value.toArray( values, values.length );
  24225. }
  24226. key = jsonKeys[ i ++ ];
  24227. } while ( key !== undefined );
  24228. } else {
  24229. // otherwise push as-is
  24230. do {
  24231. value = key[ valuePropertyName ];
  24232. if ( value !== undefined ) {
  24233. times.push( key.time );
  24234. values.push( value );
  24235. }
  24236. key = jsonKeys[ i ++ ];
  24237. } while ( key !== undefined );
  24238. }
  24239. }
  24240. };
  24241. /**
  24242. * Abstract base class of interpolants over parametric samples.
  24243. *
  24244. * The parameter domain is one dimensional, typically the time or a path
  24245. * along a curve defined by the data.
  24246. *
  24247. * The sample values can have any dimensionality and derived classes may
  24248. * apply special interpretations to the data.
  24249. *
  24250. * This class provides the interval seek in a Template Method, deferring
  24251. * the actual interpolation to derived classes.
  24252. *
  24253. * Time complexity is O(1) for linear access crossing at most two points
  24254. * and O(log N) for random access, where N is the number of positions.
  24255. *
  24256. * References:
  24257. *
  24258. * http://www.oodesign.com/template-method-pattern.html
  24259. *
  24260. * @author tschw
  24261. */
  24262. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24263. this.parameterPositions = parameterPositions;
  24264. this._cachedIndex = 0;
  24265. this.resultBuffer = resultBuffer !== undefined ?
  24266. resultBuffer : new sampleValues.constructor( sampleSize );
  24267. this.sampleValues = sampleValues;
  24268. this.valueSize = sampleSize;
  24269. }
  24270. Object.assign( Interpolant.prototype, {
  24271. evaluate: function ( t ) {
  24272. var pp = this.parameterPositions,
  24273. i1 = this._cachedIndex,
  24274. t1 = pp[ i1 ],
  24275. t0 = pp[ i1 - 1 ];
  24276. validate_interval: {
  24277. seek: {
  24278. var right;
  24279. linear_scan: {
  24280. //- See http://jsperf.com/comparison-to-undefined/3
  24281. //- slower code:
  24282. //-
  24283. //- if ( t >= t1 || t1 === undefined ) {
  24284. forward_scan: if ( ! ( t < t1 ) ) {
  24285. for ( var giveUpAt = i1 + 2; ; ) {
  24286. if ( t1 === undefined ) {
  24287. if ( t < t0 ) break forward_scan;
  24288. // after end
  24289. i1 = pp.length;
  24290. this._cachedIndex = i1;
  24291. return this.afterEnd_( i1 - 1, t, t0 );
  24292. }
  24293. if ( i1 === giveUpAt ) break; // this loop
  24294. t0 = t1;
  24295. t1 = pp[ ++ i1 ];
  24296. if ( t < t1 ) {
  24297. // we have arrived at the sought interval
  24298. break seek;
  24299. }
  24300. }
  24301. // prepare binary search on the right side of the index
  24302. right = pp.length;
  24303. break linear_scan;
  24304. }
  24305. //- slower code:
  24306. //- if ( t < t0 || t0 === undefined ) {
  24307. if ( ! ( t >= t0 ) ) {
  24308. // looping?
  24309. var t1global = pp[ 1 ];
  24310. if ( t < t1global ) {
  24311. i1 = 2; // + 1, using the scan for the details
  24312. t0 = t1global;
  24313. }
  24314. // linear reverse scan
  24315. for ( var giveUpAt = i1 - 2; ; ) {
  24316. if ( t0 === undefined ) {
  24317. // before start
  24318. this._cachedIndex = 0;
  24319. return this.beforeStart_( 0, t, t1 );
  24320. }
  24321. if ( i1 === giveUpAt ) break; // this loop
  24322. t1 = t0;
  24323. t0 = pp[ -- i1 - 1 ];
  24324. if ( t >= t0 ) {
  24325. // we have arrived at the sought interval
  24326. break seek;
  24327. }
  24328. }
  24329. // prepare binary search on the left side of the index
  24330. right = i1;
  24331. i1 = 0;
  24332. break linear_scan;
  24333. }
  24334. // the interval is valid
  24335. break validate_interval;
  24336. } // linear scan
  24337. // binary search
  24338. while ( i1 < right ) {
  24339. var mid = ( i1 + right ) >>> 1;
  24340. if ( t < pp[ mid ] ) {
  24341. right = mid;
  24342. } else {
  24343. i1 = mid + 1;
  24344. }
  24345. }
  24346. t1 = pp[ i1 ];
  24347. t0 = pp[ i1 - 1 ];
  24348. // check boundary cases, again
  24349. if ( t0 === undefined ) {
  24350. this._cachedIndex = 0;
  24351. return this.beforeStart_( 0, t, t1 );
  24352. }
  24353. if ( t1 === undefined ) {
  24354. i1 = pp.length;
  24355. this._cachedIndex = i1;
  24356. return this.afterEnd_( i1 - 1, t0, t );
  24357. }
  24358. } // seek
  24359. this._cachedIndex = i1;
  24360. this.intervalChanged_( i1, t0, t1 );
  24361. } // validate_interval
  24362. return this.interpolate_( i1, t0, t, t1 );
  24363. },
  24364. settings: null, // optional, subclass-specific settings structure
  24365. // Note: The indirection allows central control of many interpolants.
  24366. // --- Protected interface
  24367. DefaultSettings_: {},
  24368. getSettings_: function () {
  24369. return this.settings || this.DefaultSettings_;
  24370. },
  24371. copySampleValue_: function ( index ) {
  24372. // copies a sample value to the result buffer
  24373. var result = this.resultBuffer,
  24374. values = this.sampleValues,
  24375. stride = this.valueSize,
  24376. offset = index * stride;
  24377. for ( var i = 0; i !== stride; ++ i ) {
  24378. result[ i ] = values[ offset + i ];
  24379. }
  24380. return result;
  24381. },
  24382. // Template methods for derived classes:
  24383. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  24384. throw new Error( 'call to abstract method' );
  24385. // implementations shall return this.resultBuffer
  24386. },
  24387. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  24388. // empty
  24389. }
  24390. } );
  24391. //!\ DECLARE ALIAS AFTER assign prototype !
  24392. Object.assign( Interpolant.prototype, {
  24393. //( 0, t, t0 ), returns this.resultBuffer
  24394. beforeStart_: Interpolant.prototype.copySampleValue_,
  24395. //( N-1, tN-1, t ), returns this.resultBuffer
  24396. afterEnd_: Interpolant.prototype.copySampleValue_,
  24397. } );
  24398. /**
  24399. * Fast and simple cubic spline interpolant.
  24400. *
  24401. * It was derived from a Hermitian construction setting the first derivative
  24402. * at each sample position to the linear slope between neighboring positions
  24403. * over their parameter interval.
  24404. *
  24405. * @author tschw
  24406. */
  24407. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24408. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24409. this._weightPrev = - 0;
  24410. this._offsetPrev = - 0;
  24411. this._weightNext = - 0;
  24412. this._offsetNext = - 0;
  24413. }
  24414. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24415. constructor: CubicInterpolant,
  24416. DefaultSettings_: {
  24417. endingStart: ZeroCurvatureEnding,
  24418. endingEnd: ZeroCurvatureEnding
  24419. },
  24420. intervalChanged_: function ( i1, t0, t1 ) {
  24421. var pp = this.parameterPositions,
  24422. iPrev = i1 - 2,
  24423. iNext = i1 + 1,
  24424. tPrev = pp[ iPrev ],
  24425. tNext = pp[ iNext ];
  24426. if ( tPrev === undefined ) {
  24427. switch ( this.getSettings_().endingStart ) {
  24428. case ZeroSlopeEnding:
  24429. // f'(t0) = 0
  24430. iPrev = i1;
  24431. tPrev = 2 * t0 - t1;
  24432. break;
  24433. case WrapAroundEnding:
  24434. // use the other end of the curve
  24435. iPrev = pp.length - 2;
  24436. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24437. break;
  24438. default: // ZeroCurvatureEnding
  24439. // f''(t0) = 0 a.k.a. Natural Spline
  24440. iPrev = i1;
  24441. tPrev = t1;
  24442. }
  24443. }
  24444. if ( tNext === undefined ) {
  24445. switch ( this.getSettings_().endingEnd ) {
  24446. case ZeroSlopeEnding:
  24447. // f'(tN) = 0
  24448. iNext = i1;
  24449. tNext = 2 * t1 - t0;
  24450. break;
  24451. case WrapAroundEnding:
  24452. // use the other end of the curve
  24453. iNext = 1;
  24454. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24455. break;
  24456. default: // ZeroCurvatureEnding
  24457. // f''(tN) = 0, a.k.a. Natural Spline
  24458. iNext = i1 - 1;
  24459. tNext = t0;
  24460. }
  24461. }
  24462. var halfDt = ( t1 - t0 ) * 0.5,
  24463. stride = this.valueSize;
  24464. this._weightPrev = halfDt / ( t0 - tPrev );
  24465. this._weightNext = halfDt / ( tNext - t1 );
  24466. this._offsetPrev = iPrev * stride;
  24467. this._offsetNext = iNext * stride;
  24468. },
  24469. interpolate_: function ( i1, t0, t, t1 ) {
  24470. var result = this.resultBuffer,
  24471. values = this.sampleValues,
  24472. stride = this.valueSize,
  24473. o1 = i1 * stride, o0 = o1 - stride,
  24474. oP = this._offsetPrev, oN = this._offsetNext,
  24475. wP = this._weightPrev, wN = this._weightNext,
  24476. p = ( t - t0 ) / ( t1 - t0 ),
  24477. pp = p * p,
  24478. ppp = pp * p;
  24479. // evaluate polynomials
  24480. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  24481. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24482. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24483. var sN = wN * ppp - wN * pp;
  24484. // combine data linearly
  24485. for ( var i = 0; i !== stride; ++ i ) {
  24486. result[ i ] =
  24487. sP * values[ oP + i ] +
  24488. s0 * values[ o0 + i ] +
  24489. s1 * values[ o1 + i ] +
  24490. sN * values[ oN + i ];
  24491. }
  24492. return result;
  24493. }
  24494. } );
  24495. /**
  24496. * @author tschw
  24497. */
  24498. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24499. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24500. }
  24501. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24502. constructor: LinearInterpolant,
  24503. interpolate_: function ( i1, t0, t, t1 ) {
  24504. var result = this.resultBuffer,
  24505. values = this.sampleValues,
  24506. stride = this.valueSize,
  24507. offset1 = i1 * stride,
  24508. offset0 = offset1 - stride,
  24509. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24510. weight0 = 1 - weight1;
  24511. for ( var i = 0; i !== stride; ++ i ) {
  24512. result[ i ] =
  24513. values[ offset0 + i ] * weight0 +
  24514. values[ offset1 + i ] * weight1;
  24515. }
  24516. return result;
  24517. }
  24518. } );
  24519. /**
  24520. *
  24521. * Interpolant that evaluates to the sample value at the position preceeding
  24522. * the parameter.
  24523. *
  24524. * @author tschw
  24525. */
  24526. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24527. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24528. }
  24529. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24530. constructor: DiscreteInterpolant,
  24531. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  24532. return this.copySampleValue_( i1 - 1 );
  24533. }
  24534. } );
  24535. /**
  24536. *
  24537. * A timed sequence of keyframes for a specific property.
  24538. *
  24539. *
  24540. * @author Ben Houston / http://clara.io/
  24541. * @author David Sarno / http://lighthaus.us/
  24542. * @author tschw
  24543. */
  24544. function KeyframeTrack( name, times, values, interpolation ) {
  24545. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  24546. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  24547. this.name = name;
  24548. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  24549. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  24550. this.setInterpolation( interpolation || this.DefaultInterpolation );
  24551. }
  24552. // Static methods
  24553. Object.assign( KeyframeTrack, {
  24554. // Serialization (in static context, because of constructor invocation
  24555. // and automatic invocation of .toJSON):
  24556. toJSON: function ( track ) {
  24557. var trackType = track.constructor;
  24558. var json;
  24559. // derived classes can define a static toJSON method
  24560. if ( trackType.toJSON !== undefined ) {
  24561. json = trackType.toJSON( track );
  24562. } else {
  24563. // by default, we assume the data can be serialized as-is
  24564. json = {
  24565. 'name': track.name,
  24566. 'times': AnimationUtils.convertArray( track.times, Array ),
  24567. 'values': AnimationUtils.convertArray( track.values, Array )
  24568. };
  24569. var interpolation = track.getInterpolation();
  24570. if ( interpolation !== track.DefaultInterpolation ) {
  24571. json.interpolation = interpolation;
  24572. }
  24573. }
  24574. json.type = track.ValueTypeName; // mandatory
  24575. return json;
  24576. }
  24577. } );
  24578. Object.assign( KeyframeTrack.prototype, {
  24579. constructor: KeyframeTrack,
  24580. TimeBufferType: Float32Array,
  24581. ValueBufferType: Float32Array,
  24582. DefaultInterpolation: InterpolateLinear,
  24583. InterpolantFactoryMethodDiscrete: function ( result ) {
  24584. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  24585. },
  24586. InterpolantFactoryMethodLinear: function ( result ) {
  24587. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24588. },
  24589. InterpolantFactoryMethodSmooth: function ( result ) {
  24590. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24591. },
  24592. setInterpolation: function ( interpolation ) {
  24593. var factoryMethod;
  24594. switch ( interpolation ) {
  24595. case InterpolateDiscrete:
  24596. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24597. break;
  24598. case InterpolateLinear:
  24599. factoryMethod = this.InterpolantFactoryMethodLinear;
  24600. break;
  24601. case InterpolateSmooth:
  24602. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24603. break;
  24604. }
  24605. if ( factoryMethod === undefined ) {
  24606. var message = "unsupported interpolation for " +
  24607. this.ValueTypeName + " keyframe track named " + this.name;
  24608. if ( this.createInterpolant === undefined ) {
  24609. // fall back to default, unless the default itself is messed up
  24610. if ( interpolation !== this.DefaultInterpolation ) {
  24611. this.setInterpolation( this.DefaultInterpolation );
  24612. } else {
  24613. throw new Error( message ); // fatal, in this case
  24614. }
  24615. }
  24616. console.warn( 'THREE.KeyframeTrack:', message );
  24617. return this;
  24618. }
  24619. this.createInterpolant = factoryMethod;
  24620. return this;
  24621. },
  24622. getInterpolation: function () {
  24623. switch ( this.createInterpolant ) {
  24624. case this.InterpolantFactoryMethodDiscrete:
  24625. return InterpolateDiscrete;
  24626. case this.InterpolantFactoryMethodLinear:
  24627. return InterpolateLinear;
  24628. case this.InterpolantFactoryMethodSmooth:
  24629. return InterpolateSmooth;
  24630. }
  24631. },
  24632. getValueSize: function () {
  24633. return this.values.length / this.times.length;
  24634. },
  24635. // move all keyframes either forwards or backwards in time
  24636. shift: function ( timeOffset ) {
  24637. if ( timeOffset !== 0.0 ) {
  24638. var times = this.times;
  24639. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  24640. times[ i ] += timeOffset;
  24641. }
  24642. }
  24643. return this;
  24644. },
  24645. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  24646. scale: function ( timeScale ) {
  24647. if ( timeScale !== 1.0 ) {
  24648. var times = this.times;
  24649. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  24650. times[ i ] *= timeScale;
  24651. }
  24652. }
  24653. return this;
  24654. },
  24655. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  24656. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  24657. trim: function ( startTime, endTime ) {
  24658. var times = this.times,
  24659. nKeys = times.length,
  24660. from = 0,
  24661. to = nKeys - 1;
  24662. while ( from !== nKeys && times[ from ] < startTime ) {
  24663. ++ from;
  24664. }
  24665. while ( to !== - 1 && times[ to ] > endTime ) {
  24666. -- to;
  24667. }
  24668. ++ to; // inclusive -> exclusive bound
  24669. if ( from !== 0 || to !== nKeys ) {
  24670. // empty tracks are forbidden, so keep at least one keyframe
  24671. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  24672. var stride = this.getValueSize();
  24673. this.times = AnimationUtils.arraySlice( times, from, to );
  24674. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  24675. }
  24676. return this;
  24677. },
  24678. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  24679. validate: function () {
  24680. var valid = true;
  24681. var valueSize = this.getValueSize();
  24682. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  24683. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  24684. valid = false;
  24685. }
  24686. var times = this.times,
  24687. values = this.values,
  24688. nKeys = times.length;
  24689. if ( nKeys === 0 ) {
  24690. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  24691. valid = false;
  24692. }
  24693. var prevTime = null;
  24694. for ( var i = 0; i !== nKeys; i ++ ) {
  24695. var currTime = times[ i ];
  24696. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  24697. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  24698. valid = false;
  24699. break;
  24700. }
  24701. if ( prevTime !== null && prevTime > currTime ) {
  24702. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  24703. valid = false;
  24704. break;
  24705. }
  24706. prevTime = currTime;
  24707. }
  24708. if ( values !== undefined ) {
  24709. if ( AnimationUtils.isTypedArray( values ) ) {
  24710. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  24711. var value = values[ i ];
  24712. if ( isNaN( value ) ) {
  24713. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24714. valid = false;
  24715. break;
  24716. }
  24717. }
  24718. }
  24719. }
  24720. return valid;
  24721. },
  24722. // removes equivalent sequential keys as common in morph target sequences
  24723. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24724. optimize: function () {
  24725. var times = this.times,
  24726. values = this.values,
  24727. stride = this.getValueSize(),
  24728. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24729. writeIndex = 1,
  24730. lastIndex = times.length - 1;
  24731. for ( var i = 1; i < lastIndex; ++ i ) {
  24732. var keep = false;
  24733. var time = times[ i ];
  24734. var timeNext = times[ i + 1 ];
  24735. // remove adjacent keyframes scheduled at the same time
  24736. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  24737. if ( ! smoothInterpolation ) {
  24738. // remove unnecessary keyframes same as their neighbors
  24739. var offset = i * stride,
  24740. offsetP = offset - stride,
  24741. offsetN = offset + stride;
  24742. for ( var j = 0; j !== stride; ++ j ) {
  24743. var value = values[ offset + j ];
  24744. if ( value !== values[ offsetP + j ] ||
  24745. value !== values[ offsetN + j ] ) {
  24746. keep = true;
  24747. break;
  24748. }
  24749. }
  24750. } else {
  24751. keep = true;
  24752. }
  24753. }
  24754. // in-place compaction
  24755. if ( keep ) {
  24756. if ( i !== writeIndex ) {
  24757. times[ writeIndex ] = times[ i ];
  24758. var readOffset = i * stride,
  24759. writeOffset = writeIndex * stride;
  24760. for ( var j = 0; j !== stride; ++ j ) {
  24761. values[ writeOffset + j ] = values[ readOffset + j ];
  24762. }
  24763. }
  24764. ++ writeIndex;
  24765. }
  24766. }
  24767. // flush last keyframe (compaction looks ahead)
  24768. if ( lastIndex > 0 ) {
  24769. times[ writeIndex ] = times[ lastIndex ];
  24770. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24771. values[ writeOffset + j ] = values[ readOffset + j ];
  24772. }
  24773. ++ writeIndex;
  24774. }
  24775. if ( writeIndex !== times.length ) {
  24776. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  24777. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  24778. }
  24779. return this;
  24780. },
  24781. clone: function () {
  24782. var times = AnimationUtils.arraySlice( this.times, 0 );
  24783. var values = AnimationUtils.arraySlice( this.values, 0 );
  24784. var TypedKeyframeTrack = this.constructor;
  24785. var track = new TypedKeyframeTrack( this.name, times, values );
  24786. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24787. track.createInterpolant = this.createInterpolant;
  24788. return track;
  24789. }
  24790. } );
  24791. /**
  24792. *
  24793. * A Track of Boolean keyframe values.
  24794. *
  24795. *
  24796. * @author Ben Houston / http://clara.io/
  24797. * @author David Sarno / http://lighthaus.us/
  24798. * @author tschw
  24799. */
  24800. function BooleanKeyframeTrack( name, times, values ) {
  24801. KeyframeTrack.call( this, name, times, values );
  24802. }
  24803. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24804. constructor: BooleanKeyframeTrack,
  24805. ValueTypeName: 'bool',
  24806. ValueBufferType: Array,
  24807. DefaultInterpolation: InterpolateDiscrete,
  24808. InterpolantFactoryMethodLinear: undefined,
  24809. InterpolantFactoryMethodSmooth: undefined
  24810. // Note: Actually this track could have a optimized / compressed
  24811. // representation of a single value and a custom interpolant that
  24812. // computes "firstValue ^ isOdd( index )".
  24813. } );
  24814. /**
  24815. *
  24816. * A Track of keyframe values that represent color.
  24817. *
  24818. *
  24819. * @author Ben Houston / http://clara.io/
  24820. * @author David Sarno / http://lighthaus.us/
  24821. * @author tschw
  24822. */
  24823. function ColorKeyframeTrack( name, times, values, interpolation ) {
  24824. KeyframeTrack.call( this, name, times, values, interpolation );
  24825. }
  24826. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24827. constructor: ColorKeyframeTrack,
  24828. ValueTypeName: 'color'
  24829. // ValueBufferType is inherited
  24830. // DefaultInterpolation is inherited
  24831. // Note: Very basic implementation and nothing special yet.
  24832. // However, this is the place for color space parameterization.
  24833. } );
  24834. /**
  24835. *
  24836. * A Track of numeric keyframe values.
  24837. *
  24838. * @author Ben Houston / http://clara.io/
  24839. * @author David Sarno / http://lighthaus.us/
  24840. * @author tschw
  24841. */
  24842. function NumberKeyframeTrack( name, times, values, interpolation ) {
  24843. KeyframeTrack.call( this, name, times, values, interpolation );
  24844. }
  24845. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24846. constructor: NumberKeyframeTrack,
  24847. ValueTypeName: 'number'
  24848. // ValueBufferType is inherited
  24849. // DefaultInterpolation is inherited
  24850. } );
  24851. /**
  24852. * Spherical linear unit quaternion interpolant.
  24853. *
  24854. * @author tschw
  24855. */
  24856. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24857. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24858. }
  24859. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24860. constructor: QuaternionLinearInterpolant,
  24861. interpolate_: function ( i1, t0, t, t1 ) {
  24862. var result = this.resultBuffer,
  24863. values = this.sampleValues,
  24864. stride = this.valueSize,
  24865. offset = i1 * stride,
  24866. alpha = ( t - t0 ) / ( t1 - t0 );
  24867. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  24868. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24869. }
  24870. return result;
  24871. }
  24872. } );
  24873. /**
  24874. *
  24875. * A Track of quaternion keyframe values.
  24876. *
  24877. * @author Ben Houston / http://clara.io/
  24878. * @author David Sarno / http://lighthaus.us/
  24879. * @author tschw
  24880. */
  24881. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  24882. KeyframeTrack.call( this, name, times, values, interpolation );
  24883. }
  24884. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24885. constructor: QuaternionKeyframeTrack,
  24886. ValueTypeName: 'quaternion',
  24887. // ValueBufferType is inherited
  24888. DefaultInterpolation: InterpolateLinear,
  24889. InterpolantFactoryMethodLinear: function ( result ) {
  24890. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24891. },
  24892. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  24893. } );
  24894. /**
  24895. *
  24896. * A Track that interpolates Strings
  24897. *
  24898. *
  24899. * @author Ben Houston / http://clara.io/
  24900. * @author David Sarno / http://lighthaus.us/
  24901. * @author tschw
  24902. */
  24903. function StringKeyframeTrack( name, times, values, interpolation ) {
  24904. KeyframeTrack.call( this, name, times, values, interpolation );
  24905. }
  24906. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24907. constructor: StringKeyframeTrack,
  24908. ValueTypeName: 'string',
  24909. ValueBufferType: Array,
  24910. DefaultInterpolation: InterpolateDiscrete,
  24911. InterpolantFactoryMethodLinear: undefined,
  24912. InterpolantFactoryMethodSmooth: undefined
  24913. } );
  24914. /**
  24915. *
  24916. * A Track of vectored keyframe values.
  24917. *
  24918. *
  24919. * @author Ben Houston / http://clara.io/
  24920. * @author David Sarno / http://lighthaus.us/
  24921. * @author tschw
  24922. */
  24923. function VectorKeyframeTrack( name, times, values, interpolation ) {
  24924. KeyframeTrack.call( this, name, times, values, interpolation );
  24925. }
  24926. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24927. constructor: VectorKeyframeTrack,
  24928. ValueTypeName: 'vector'
  24929. // ValueBufferType is inherited
  24930. // DefaultInterpolation is inherited
  24931. } );
  24932. /**
  24933. *
  24934. * Reusable set of Tracks that represent an animation.
  24935. *
  24936. * @author Ben Houston / http://clara.io/
  24937. * @author David Sarno / http://lighthaus.us/
  24938. */
  24939. function AnimationClip( name, duration, tracks ) {
  24940. this.name = name;
  24941. this.tracks = tracks;
  24942. this.duration = ( duration !== undefined ) ? duration : - 1;
  24943. this.uuid = _Math.generateUUID();
  24944. // this means it should figure out its duration by scanning the tracks
  24945. if ( this.duration < 0 ) {
  24946. this.resetDuration();
  24947. }
  24948. }
  24949. function getTrackTypeForValueTypeName( typeName ) {
  24950. switch ( typeName.toLowerCase() ) {
  24951. case 'scalar':
  24952. case 'double':
  24953. case 'float':
  24954. case 'number':
  24955. case 'integer':
  24956. return NumberKeyframeTrack;
  24957. case 'vector':
  24958. case 'vector2':
  24959. case 'vector3':
  24960. case 'vector4':
  24961. return VectorKeyframeTrack;
  24962. case 'color':
  24963. return ColorKeyframeTrack;
  24964. case 'quaternion':
  24965. return QuaternionKeyframeTrack;
  24966. case 'bool':
  24967. case 'boolean':
  24968. return BooleanKeyframeTrack;
  24969. case 'string':
  24970. return StringKeyframeTrack;
  24971. }
  24972. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24973. }
  24974. function parseKeyframeTrack( json ) {
  24975. if ( json.type === undefined ) {
  24976. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24977. }
  24978. var trackType = getTrackTypeForValueTypeName( json.type );
  24979. if ( json.times === undefined ) {
  24980. var times = [], values = [];
  24981. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  24982. json.times = times;
  24983. json.values = values;
  24984. }
  24985. // derived classes can define a static parse method
  24986. if ( trackType.parse !== undefined ) {
  24987. return trackType.parse( json );
  24988. } else {
  24989. // by default, we assume a constructor compatible with the base
  24990. return new trackType( json.name, json.times, json.values, json.interpolation );
  24991. }
  24992. }
  24993. Object.assign( AnimationClip, {
  24994. parse: function ( json ) {
  24995. var tracks = [],
  24996. jsonTracks = json.tracks,
  24997. frameTime = 1.0 / ( json.fps || 1.0 );
  24998. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24999. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25000. }
  25001. return new AnimationClip( json.name, json.duration, tracks );
  25002. },
  25003. toJSON: function ( clip ) {
  25004. var tracks = [],
  25005. clipTracks = clip.tracks;
  25006. var json = {
  25007. 'name': clip.name,
  25008. 'duration': clip.duration,
  25009. 'tracks': tracks,
  25010. 'uuid': clip.uuid
  25011. };
  25012. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25013. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25014. }
  25015. return json;
  25016. },
  25017. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  25018. var numMorphTargets = morphTargetSequence.length;
  25019. var tracks = [];
  25020. for ( var i = 0; i < numMorphTargets; i ++ ) {
  25021. var times = [];
  25022. var values = [];
  25023. times.push(
  25024. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25025. i,
  25026. ( i + 1 ) % numMorphTargets );
  25027. values.push( 0, 1, 0 );
  25028. var order = AnimationUtils.getKeyframeOrder( times );
  25029. times = AnimationUtils.sortedArray( times, 1, order );
  25030. values = AnimationUtils.sortedArray( values, 1, order );
  25031. // if there is a key at the first frame, duplicate it as the
  25032. // last frame as well for perfect loop.
  25033. if ( ! noLoop && times[ 0 ] === 0 ) {
  25034. times.push( numMorphTargets );
  25035. values.push( values[ 0 ] );
  25036. }
  25037. tracks.push(
  25038. new NumberKeyframeTrack(
  25039. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25040. times, values
  25041. ).scale( 1.0 / fps ) );
  25042. }
  25043. return new AnimationClip( name, - 1, tracks );
  25044. },
  25045. findByName: function ( objectOrClipArray, name ) {
  25046. var clipArray = objectOrClipArray;
  25047. if ( ! Array.isArray( objectOrClipArray ) ) {
  25048. var o = objectOrClipArray;
  25049. clipArray = o.geometry && o.geometry.animations || o.animations;
  25050. }
  25051. for ( var i = 0; i < clipArray.length; i ++ ) {
  25052. if ( clipArray[ i ].name === name ) {
  25053. return clipArray[ i ];
  25054. }
  25055. }
  25056. return null;
  25057. },
  25058. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  25059. var animationToMorphTargets = {};
  25060. // tested with https://regex101.com/ on trick sequences
  25061. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25062. var pattern = /^([\w-]*?)([\d]+)$/;
  25063. // sort morph target names into animation groups based
  25064. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25065. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  25066. var morphTarget = morphTargets[ i ];
  25067. var parts = morphTarget.name.match( pattern );
  25068. if ( parts && parts.length > 1 ) {
  25069. var name = parts[ 1 ];
  25070. var animationMorphTargets = animationToMorphTargets[ name ];
  25071. if ( ! animationMorphTargets ) {
  25072. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25073. }
  25074. animationMorphTargets.push( morphTarget );
  25075. }
  25076. }
  25077. var clips = [];
  25078. for ( var name in animationToMorphTargets ) {
  25079. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25080. }
  25081. return clips;
  25082. },
  25083. // parse the animation.hierarchy format
  25084. parseAnimation: function ( animation, bones ) {
  25085. if ( ! animation ) {
  25086. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25087. return null;
  25088. }
  25089. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25090. // only return track if there are actually keys.
  25091. if ( animationKeys.length !== 0 ) {
  25092. var times = [];
  25093. var values = [];
  25094. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  25095. // empty keys are filtered out, so check again
  25096. if ( times.length !== 0 ) {
  25097. destTracks.push( new trackType( trackName, times, values ) );
  25098. }
  25099. }
  25100. };
  25101. var tracks = [];
  25102. var clipName = animation.name || 'default';
  25103. // automatic length determination in AnimationClip.
  25104. var duration = animation.length || - 1;
  25105. var fps = animation.fps || 30;
  25106. var hierarchyTracks = animation.hierarchy || [];
  25107. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  25108. var animationKeys = hierarchyTracks[ h ].keys;
  25109. // skip empty tracks
  25110. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25111. // process morph targets
  25112. if ( animationKeys[ 0 ].morphTargets ) {
  25113. // figure out all morph targets used in this track
  25114. var morphTargetNames = {};
  25115. for ( var k = 0; k < animationKeys.length; k ++ ) {
  25116. if ( animationKeys[ k ].morphTargets ) {
  25117. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25118. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25119. }
  25120. }
  25121. }
  25122. // create a track for each morph target with all zero
  25123. // morphTargetInfluences except for the keys in which
  25124. // the morphTarget is named.
  25125. for ( var morphTargetName in morphTargetNames ) {
  25126. var times = [];
  25127. var values = [];
  25128. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25129. var animationKey = animationKeys[ k ];
  25130. times.push( animationKey.time );
  25131. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25132. }
  25133. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25134. }
  25135. duration = morphTargetNames.length * ( fps || 1.0 );
  25136. } else {
  25137. // ...assume skeletal animation
  25138. var boneName = '.bones[' + bones[ h ].name + ']';
  25139. addNonemptyTrack(
  25140. VectorKeyframeTrack, boneName + '.position',
  25141. animationKeys, 'pos', tracks );
  25142. addNonemptyTrack(
  25143. QuaternionKeyframeTrack, boneName + '.quaternion',
  25144. animationKeys, 'rot', tracks );
  25145. addNonemptyTrack(
  25146. VectorKeyframeTrack, boneName + '.scale',
  25147. animationKeys, 'scl', tracks );
  25148. }
  25149. }
  25150. if ( tracks.length === 0 ) {
  25151. return null;
  25152. }
  25153. var clip = new AnimationClip( clipName, duration, tracks );
  25154. return clip;
  25155. }
  25156. } );
  25157. Object.assign( AnimationClip.prototype, {
  25158. resetDuration: function () {
  25159. var tracks = this.tracks, duration = 0;
  25160. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  25161. var track = this.tracks[ i ];
  25162. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25163. }
  25164. this.duration = duration;
  25165. return this;
  25166. },
  25167. trim: function () {
  25168. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25169. this.tracks[ i ].trim( 0, this.duration );
  25170. }
  25171. return this;
  25172. },
  25173. validate: function () {
  25174. var valid = true;
  25175. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25176. valid = valid && this.tracks[ i ].validate();
  25177. }
  25178. return valid;
  25179. },
  25180. optimize: function () {
  25181. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25182. this.tracks[ i ].optimize();
  25183. }
  25184. return this;
  25185. },
  25186. clone: function () {
  25187. var tracks = [];
  25188. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25189. tracks.push( this.tracks[ i ].clone() );
  25190. }
  25191. return new AnimationClip( this.name, this.duration, tracks );
  25192. }
  25193. } );
  25194. /**
  25195. * @author mrdoob / http://mrdoob.com/
  25196. */
  25197. var Cache = {
  25198. enabled: false,
  25199. files: {},
  25200. add: function ( key, file ) {
  25201. if ( this.enabled === false ) return;
  25202. // console.log( 'THREE.Cache', 'Adding key:', key );
  25203. this.files[ key ] = file;
  25204. },
  25205. get: function ( key ) {
  25206. if ( this.enabled === false ) return;
  25207. // console.log( 'THREE.Cache', 'Checking key:', key );
  25208. return this.files[ key ];
  25209. },
  25210. remove: function ( key ) {
  25211. delete this.files[ key ];
  25212. },
  25213. clear: function () {
  25214. this.files = {};
  25215. }
  25216. };
  25217. /**
  25218. * @author mrdoob / http://mrdoob.com/
  25219. */
  25220. function LoadingManager( onLoad, onProgress, onError ) {
  25221. var scope = this;
  25222. var isLoading = false;
  25223. var itemsLoaded = 0;
  25224. var itemsTotal = 0;
  25225. var urlModifier = undefined;
  25226. // Refer to #5689 for the reason why we don't set .onStart
  25227. // in the constructor
  25228. this.onStart = undefined;
  25229. this.onLoad = onLoad;
  25230. this.onProgress = onProgress;
  25231. this.onError = onError;
  25232. this.itemStart = function ( url ) {
  25233. itemsTotal ++;
  25234. if ( isLoading === false ) {
  25235. if ( scope.onStart !== undefined ) {
  25236. scope.onStart( url, itemsLoaded, itemsTotal );
  25237. }
  25238. }
  25239. isLoading = true;
  25240. };
  25241. this.itemEnd = function ( url ) {
  25242. itemsLoaded ++;
  25243. if ( scope.onProgress !== undefined ) {
  25244. scope.onProgress( url, itemsLoaded, itemsTotal );
  25245. }
  25246. if ( itemsLoaded === itemsTotal ) {
  25247. isLoading = false;
  25248. if ( scope.onLoad !== undefined ) {
  25249. scope.onLoad();
  25250. }
  25251. }
  25252. };
  25253. this.itemError = function ( url ) {
  25254. if ( scope.onError !== undefined ) {
  25255. scope.onError( url );
  25256. }
  25257. };
  25258. this.resolveURL = function ( url ) {
  25259. if ( urlModifier ) {
  25260. return urlModifier( url );
  25261. }
  25262. return url;
  25263. };
  25264. this.setURLModifier = function ( transform ) {
  25265. urlModifier = transform;
  25266. return this;
  25267. };
  25268. }
  25269. var DefaultLoadingManager = new LoadingManager();
  25270. /**
  25271. * @author mrdoob / http://mrdoob.com/
  25272. */
  25273. var loading = {};
  25274. function FileLoader( manager ) {
  25275. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25276. }
  25277. Object.assign( FileLoader.prototype, {
  25278. load: function ( url, onLoad, onProgress, onError ) {
  25279. if ( url === undefined ) url = '';
  25280. if ( this.path !== undefined ) url = this.path + url;
  25281. url = this.manager.resolveURL( url );
  25282. var scope = this;
  25283. var cached = Cache.get( url );
  25284. if ( cached !== undefined ) {
  25285. scope.manager.itemStart( url );
  25286. setTimeout( function () {
  25287. if ( onLoad ) onLoad( cached );
  25288. scope.manager.itemEnd( url );
  25289. }, 0 );
  25290. return cached;
  25291. }
  25292. // Check if request is duplicate
  25293. if ( loading[ url ] !== undefined ) {
  25294. loading[ url ].push( {
  25295. onLoad: onLoad,
  25296. onProgress: onProgress,
  25297. onError: onError
  25298. } );
  25299. return;
  25300. }
  25301. // Check for data: URI
  25302. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  25303. var dataUriRegexResult = url.match( dataUriRegex );
  25304. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  25305. if ( dataUriRegexResult ) {
  25306. var mimeType = dataUriRegexResult[ 1 ];
  25307. var isBase64 = !! dataUriRegexResult[ 2 ];
  25308. var data = dataUriRegexResult[ 3 ];
  25309. data = decodeURIComponent( data );
  25310. if ( isBase64 ) data = atob( data );
  25311. try {
  25312. var response;
  25313. var responseType = ( this.responseType || '' ).toLowerCase();
  25314. switch ( responseType ) {
  25315. case 'arraybuffer':
  25316. case 'blob':
  25317. var view = new Uint8Array( data.length );
  25318. for ( var i = 0; i < data.length; i ++ ) {
  25319. view[ i ] = data.charCodeAt( i );
  25320. }
  25321. if ( responseType === 'blob' ) {
  25322. response = new Blob( [ view.buffer ], { type: mimeType } );
  25323. } else {
  25324. response = view.buffer;
  25325. }
  25326. break;
  25327. case 'document':
  25328. var parser = new DOMParser();
  25329. response = parser.parseFromString( data, mimeType );
  25330. break;
  25331. case 'json':
  25332. response = JSON.parse( data );
  25333. break;
  25334. default: // 'text' or other
  25335. response = data;
  25336. break;
  25337. }
  25338. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  25339. setTimeout( function () {
  25340. if ( onLoad ) onLoad( response );
  25341. scope.manager.itemEnd( url );
  25342. }, 0 );
  25343. } catch ( error ) {
  25344. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  25345. setTimeout( function () {
  25346. if ( onError ) onError( error );
  25347. scope.manager.itemError( url );
  25348. scope.manager.itemEnd( url );
  25349. }, 0 );
  25350. }
  25351. } else {
  25352. // Initialise array for duplicate requests
  25353. loading[ url ] = [];
  25354. loading[ url ].push( {
  25355. onLoad: onLoad,
  25356. onProgress: onProgress,
  25357. onError: onError
  25358. } );
  25359. var request = new XMLHttpRequest();
  25360. request.open( 'GET', url, true );
  25361. request.addEventListener( 'load', function ( event ) {
  25362. var response = this.response;
  25363. Cache.add( url, response );
  25364. var callbacks = loading[ url ];
  25365. delete loading[ url ];
  25366. if ( this.status === 200 || this.status === 0 ) {
  25367. // Some browsers return HTTP Status 0 when using non-http protocol
  25368. // e.g. 'file://' or 'data://'. Handle as success.
  25369. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  25370. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25371. var callback = callbacks[ i ];
  25372. if ( callback.onLoad ) callback.onLoad( response );
  25373. }
  25374. scope.manager.itemEnd( url );
  25375. } else {
  25376. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25377. var callback = callbacks[ i ];
  25378. if ( callback.onError ) callback.onError( event );
  25379. }
  25380. scope.manager.itemError( url );
  25381. scope.manager.itemEnd( url );
  25382. }
  25383. }, false );
  25384. request.addEventListener( 'progress', function ( event ) {
  25385. var callbacks = loading[ url ];
  25386. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25387. var callback = callbacks[ i ];
  25388. if ( callback.onProgress ) callback.onProgress( event );
  25389. }
  25390. }, false );
  25391. request.addEventListener( 'error', function ( event ) {
  25392. var callbacks = loading[ url ];
  25393. delete loading[ url ];
  25394. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25395. var callback = callbacks[ i ];
  25396. if ( callback.onError ) callback.onError( event );
  25397. }
  25398. scope.manager.itemError( url );
  25399. scope.manager.itemEnd( url );
  25400. }, false );
  25401. request.addEventListener( 'abort', function ( event ) {
  25402. var callbacks = loading[ url ];
  25403. delete loading[ url ];
  25404. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  25405. var callback = callbacks[ i ];
  25406. if ( callback.onError ) callback.onError( event );
  25407. }
  25408. scope.manager.itemError( url );
  25409. scope.manager.itemEnd( url );
  25410. }, false );
  25411. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  25412. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  25413. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  25414. for ( var header in this.requestHeader ) {
  25415. request.setRequestHeader( header, this.requestHeader[ header ] );
  25416. }
  25417. request.send( null );
  25418. }
  25419. scope.manager.itemStart( url );
  25420. return request;
  25421. },
  25422. setPath: function ( value ) {
  25423. this.path = value;
  25424. return this;
  25425. },
  25426. setResponseType: function ( value ) {
  25427. this.responseType = value;
  25428. return this;
  25429. },
  25430. setWithCredentials: function ( value ) {
  25431. this.withCredentials = value;
  25432. return this;
  25433. },
  25434. setMimeType: function ( value ) {
  25435. this.mimeType = value;
  25436. return this;
  25437. },
  25438. setRequestHeader: function ( value ) {
  25439. this.requestHeader = value;
  25440. return this;
  25441. }
  25442. } );
  25443. /**
  25444. * @author bhouston / http://clara.io/
  25445. */
  25446. function AnimationLoader( manager ) {
  25447. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25448. }
  25449. Object.assign( AnimationLoader.prototype, {
  25450. load: function ( url, onLoad, onProgress, onError ) {
  25451. var scope = this;
  25452. var loader = new FileLoader( scope.manager );
  25453. loader.setPath( scope.path );
  25454. loader.load( url, function ( text ) {
  25455. onLoad( scope.parse( JSON.parse( text ) ) );
  25456. }, onProgress, onError );
  25457. },
  25458. parse: function ( json ) {
  25459. var animations = [];
  25460. for ( var i = 0; i < json.length; i ++ ) {
  25461. var clip = AnimationClip.parse( json[ i ] );
  25462. animations.push( clip );
  25463. }
  25464. return animations;
  25465. },
  25466. setPath: function ( value ) {
  25467. this.path = value;
  25468. return this;
  25469. }
  25470. } );
  25471. /**
  25472. * @author mrdoob / http://mrdoob.com/
  25473. *
  25474. * Abstract Base class to block based textures loader (dds, pvr, ...)
  25475. */
  25476. function CompressedTextureLoader( manager ) {
  25477. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25478. // override in sub classes
  25479. this._parser = null;
  25480. }
  25481. Object.assign( CompressedTextureLoader.prototype, {
  25482. load: function ( url, onLoad, onProgress, onError ) {
  25483. var scope = this;
  25484. var images = [];
  25485. var texture = new CompressedTexture();
  25486. texture.image = images;
  25487. var loader = new FileLoader( this.manager );
  25488. loader.setPath( this.path );
  25489. loader.setResponseType( 'arraybuffer' );
  25490. function loadTexture( i ) {
  25491. loader.load( url[ i ], function ( buffer ) {
  25492. var texDatas = scope._parser( buffer, true );
  25493. images[ i ] = {
  25494. width: texDatas.width,
  25495. height: texDatas.height,
  25496. format: texDatas.format,
  25497. mipmaps: texDatas.mipmaps
  25498. };
  25499. loaded += 1;
  25500. if ( loaded === 6 ) {
  25501. if ( texDatas.mipmapCount === 1 )
  25502. texture.minFilter = LinearFilter;
  25503. texture.format = texDatas.format;
  25504. texture.needsUpdate = true;
  25505. if ( onLoad ) onLoad( texture );
  25506. }
  25507. }, onProgress, onError );
  25508. }
  25509. if ( Array.isArray( url ) ) {
  25510. var loaded = 0;
  25511. for ( var i = 0, il = url.length; i < il; ++ i ) {
  25512. loadTexture( i );
  25513. }
  25514. } else {
  25515. // compressed cubemap texture stored in a single DDS file
  25516. loader.load( url, function ( buffer ) {
  25517. var texDatas = scope._parser( buffer, true );
  25518. if ( texDatas.isCubemap ) {
  25519. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  25520. for ( var f = 0; f < faces; f ++ ) {
  25521. images[ f ] = { mipmaps: [] };
  25522. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  25523. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  25524. images[ f ].format = texDatas.format;
  25525. images[ f ].width = texDatas.width;
  25526. images[ f ].height = texDatas.height;
  25527. }
  25528. }
  25529. } else {
  25530. texture.image.width = texDatas.width;
  25531. texture.image.height = texDatas.height;
  25532. texture.mipmaps = texDatas.mipmaps;
  25533. }
  25534. if ( texDatas.mipmapCount === 1 ) {
  25535. texture.minFilter = LinearFilter;
  25536. }
  25537. texture.format = texDatas.format;
  25538. texture.needsUpdate = true;
  25539. if ( onLoad ) onLoad( texture );
  25540. }, onProgress, onError );
  25541. }
  25542. return texture;
  25543. },
  25544. setPath: function ( value ) {
  25545. this.path = value;
  25546. return this;
  25547. }
  25548. } );
  25549. /**
  25550. * @author Nikos M. / https://github.com/foo123/
  25551. *
  25552. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25553. */
  25554. function DataTextureLoader( manager ) {
  25555. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25556. // override in sub classes
  25557. this._parser = null;
  25558. }
  25559. Object.assign( DataTextureLoader.prototype, {
  25560. load: function ( url, onLoad, onProgress, onError ) {
  25561. var scope = this;
  25562. var texture = new DataTexture();
  25563. var loader = new FileLoader( this.manager );
  25564. loader.setResponseType( 'arraybuffer' );
  25565. loader.setPath( this.path );
  25566. loader.load( url, function ( buffer ) {
  25567. var texData = scope._parser( buffer );
  25568. if ( ! texData ) return;
  25569. if ( texData.image !== undefined ) {
  25570. texture.image = texData.image;
  25571. } else if ( texData.data !== undefined ) {
  25572. texture.image.width = texData.width;
  25573. texture.image.height = texData.height;
  25574. texture.image.data = texData.data;
  25575. }
  25576. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25577. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25578. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25579. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearMipMapLinearFilter;
  25580. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25581. if ( texData.format !== undefined ) {
  25582. texture.format = texData.format;
  25583. }
  25584. if ( texData.type !== undefined ) {
  25585. texture.type = texData.type;
  25586. }
  25587. if ( texData.mipmaps !== undefined ) {
  25588. texture.mipmaps = texData.mipmaps;
  25589. }
  25590. if ( texData.mipmapCount === 1 ) {
  25591. texture.minFilter = LinearFilter;
  25592. }
  25593. texture.needsUpdate = true;
  25594. if ( onLoad ) onLoad( texture, texData );
  25595. }, onProgress, onError );
  25596. return texture;
  25597. },
  25598. setPath: function ( value ) {
  25599. this.path = value;
  25600. return this;
  25601. }
  25602. } );
  25603. /**
  25604. * @author mrdoob / http://mrdoob.com/
  25605. */
  25606. function ImageLoader( manager ) {
  25607. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25608. }
  25609. Object.assign( ImageLoader.prototype, {
  25610. crossOrigin: 'anonymous',
  25611. load: function ( url, onLoad, onProgress, onError ) {
  25612. if ( url === undefined ) url = '';
  25613. if ( this.path !== undefined ) url = this.path + url;
  25614. url = this.manager.resolveURL( url );
  25615. var scope = this;
  25616. var cached = Cache.get( url );
  25617. if ( cached !== undefined ) {
  25618. scope.manager.itemStart( url );
  25619. setTimeout( function () {
  25620. if ( onLoad ) onLoad( cached );
  25621. scope.manager.itemEnd( url );
  25622. }, 0 );
  25623. return cached;
  25624. }
  25625. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  25626. function onImageLoad() {
  25627. image.removeEventListener( 'load', onImageLoad, false );
  25628. image.removeEventListener( 'error', onImageError, false );
  25629. Cache.add( url, this );
  25630. if ( onLoad ) onLoad( this );
  25631. scope.manager.itemEnd( url );
  25632. }
  25633. function onImageError( event ) {
  25634. image.removeEventListener( 'load', onImageLoad, false );
  25635. image.removeEventListener( 'error', onImageError, false );
  25636. if ( onError ) onError( event );
  25637. scope.manager.itemError( url );
  25638. scope.manager.itemEnd( url );
  25639. }
  25640. image.addEventListener( 'load', onImageLoad, false );
  25641. image.addEventListener( 'error', onImageError, false );
  25642. if ( url.substr( 0, 5 ) !== 'data:' ) {
  25643. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25644. }
  25645. scope.manager.itemStart( url );
  25646. image.src = url;
  25647. return image;
  25648. },
  25649. setCrossOrigin: function ( value ) {
  25650. this.crossOrigin = value;
  25651. return this;
  25652. },
  25653. setPath: function ( value ) {
  25654. this.path = value;
  25655. return this;
  25656. }
  25657. } );
  25658. /**
  25659. * @author mrdoob / http://mrdoob.com/
  25660. */
  25661. function CubeTextureLoader( manager ) {
  25662. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25663. }
  25664. Object.assign( CubeTextureLoader.prototype, {
  25665. crossOrigin: 'anonymous',
  25666. load: function ( urls, onLoad, onProgress, onError ) {
  25667. var texture = new CubeTexture();
  25668. var loader = new ImageLoader( this.manager );
  25669. loader.setCrossOrigin( this.crossOrigin );
  25670. loader.setPath( this.path );
  25671. var loaded = 0;
  25672. function loadTexture( i ) {
  25673. loader.load( urls[ i ], function ( image ) {
  25674. texture.images[ i ] = image;
  25675. loaded ++;
  25676. if ( loaded === 6 ) {
  25677. texture.needsUpdate = true;
  25678. if ( onLoad ) onLoad( texture );
  25679. }
  25680. }, undefined, onError );
  25681. }
  25682. for ( var i = 0; i < urls.length; ++ i ) {
  25683. loadTexture( i );
  25684. }
  25685. return texture;
  25686. },
  25687. setCrossOrigin: function ( value ) {
  25688. this.crossOrigin = value;
  25689. return this;
  25690. },
  25691. setPath: function ( value ) {
  25692. this.path = value;
  25693. return this;
  25694. }
  25695. } );
  25696. /**
  25697. * @author mrdoob / http://mrdoob.com/
  25698. */
  25699. function TextureLoader( manager ) {
  25700. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25701. }
  25702. Object.assign( TextureLoader.prototype, {
  25703. crossOrigin: 'anonymous',
  25704. load: function ( url, onLoad, onProgress, onError ) {
  25705. var texture = new Texture();
  25706. var loader = new ImageLoader( this.manager );
  25707. loader.setCrossOrigin( this.crossOrigin );
  25708. loader.setPath( this.path );
  25709. loader.load( url, function ( image ) {
  25710. texture.image = image;
  25711. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  25712. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  25713. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  25714. texture.needsUpdate = true;
  25715. if ( onLoad !== undefined ) {
  25716. onLoad( texture );
  25717. }
  25718. }, onProgress, onError );
  25719. return texture;
  25720. },
  25721. setCrossOrigin: function ( value ) {
  25722. this.crossOrigin = value;
  25723. return this;
  25724. },
  25725. setPath: function ( value ) {
  25726. this.path = value;
  25727. return this;
  25728. }
  25729. } );
  25730. /**
  25731. * @author zz85 / http://www.lab4games.net/zz85/blog
  25732. * Extensible curve object
  25733. *
  25734. * Some common of curve methods:
  25735. * .getPoint( t, optionalTarget ), .getTangent( t )
  25736. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  25737. * .getPoints(), .getSpacedPoints()
  25738. * .getLength()
  25739. * .updateArcLengths()
  25740. *
  25741. * This following curves inherit from THREE.Curve:
  25742. *
  25743. * -- 2D curves --
  25744. * THREE.ArcCurve
  25745. * THREE.CubicBezierCurve
  25746. * THREE.EllipseCurve
  25747. * THREE.LineCurve
  25748. * THREE.QuadraticBezierCurve
  25749. * THREE.SplineCurve
  25750. *
  25751. * -- 3D curves --
  25752. * THREE.CatmullRomCurve3
  25753. * THREE.CubicBezierCurve3
  25754. * THREE.LineCurve3
  25755. * THREE.QuadraticBezierCurve3
  25756. *
  25757. * A series of curves can be represented as a THREE.CurvePath.
  25758. *
  25759. **/
  25760. /**************************************************************
  25761. * Abstract Curve base class
  25762. **************************************************************/
  25763. function Curve() {
  25764. this.type = 'Curve';
  25765. this.arcLengthDivisions = 200;
  25766. }
  25767. Object.assign( Curve.prototype, {
  25768. // Virtual base class method to overwrite and implement in subclasses
  25769. // - t [0 .. 1]
  25770. getPoint: function ( /* t, optionalTarget */ ) {
  25771. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  25772. return null;
  25773. },
  25774. // Get point at relative position in curve according to arc length
  25775. // - u [0 .. 1]
  25776. getPointAt: function ( u, optionalTarget ) {
  25777. var t = this.getUtoTmapping( u );
  25778. return this.getPoint( t, optionalTarget );
  25779. },
  25780. // Get sequence of points using getPoint( t )
  25781. getPoints: function ( divisions ) {
  25782. if ( divisions === undefined ) divisions = 5;
  25783. var points = [];
  25784. for ( var d = 0; d <= divisions; d ++ ) {
  25785. points.push( this.getPoint( d / divisions ) );
  25786. }
  25787. return points;
  25788. },
  25789. // Get sequence of points using getPointAt( u )
  25790. getSpacedPoints: function ( divisions ) {
  25791. if ( divisions === undefined ) divisions = 5;
  25792. var points = [];
  25793. for ( var d = 0; d <= divisions; d ++ ) {
  25794. points.push( this.getPointAt( d / divisions ) );
  25795. }
  25796. return points;
  25797. },
  25798. // Get total curve arc length
  25799. getLength: function () {
  25800. var lengths = this.getLengths();
  25801. return lengths[ lengths.length - 1 ];
  25802. },
  25803. // Get list of cumulative segment lengths
  25804. getLengths: function ( divisions ) {
  25805. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  25806. if ( this.cacheArcLengths &&
  25807. ( this.cacheArcLengths.length === divisions + 1 ) &&
  25808. ! this.needsUpdate ) {
  25809. return this.cacheArcLengths;
  25810. }
  25811. this.needsUpdate = false;
  25812. var cache = [];
  25813. var current, last = this.getPoint( 0 );
  25814. var p, sum = 0;
  25815. cache.push( 0 );
  25816. for ( p = 1; p <= divisions; p ++ ) {
  25817. current = this.getPoint( p / divisions );
  25818. sum += current.distanceTo( last );
  25819. cache.push( sum );
  25820. last = current;
  25821. }
  25822. this.cacheArcLengths = cache;
  25823. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  25824. },
  25825. updateArcLengths: function () {
  25826. this.needsUpdate = true;
  25827. this.getLengths();
  25828. },
  25829. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  25830. getUtoTmapping: function ( u, distance ) {
  25831. var arcLengths = this.getLengths();
  25832. var i = 0, il = arcLengths.length;
  25833. var targetArcLength; // The targeted u distance value to get
  25834. if ( distance ) {
  25835. targetArcLength = distance;
  25836. } else {
  25837. targetArcLength = u * arcLengths[ il - 1 ];
  25838. }
  25839. // binary search for the index with largest value smaller than target u distance
  25840. var low = 0, high = il - 1, comparison;
  25841. while ( low <= high ) {
  25842. 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
  25843. comparison = arcLengths[ i ] - targetArcLength;
  25844. if ( comparison < 0 ) {
  25845. low = i + 1;
  25846. } else if ( comparison > 0 ) {
  25847. high = i - 1;
  25848. } else {
  25849. high = i;
  25850. break;
  25851. // DONE
  25852. }
  25853. }
  25854. i = high;
  25855. if ( arcLengths[ i ] === targetArcLength ) {
  25856. return i / ( il - 1 );
  25857. }
  25858. // we could get finer grain at lengths, or use simple interpolation between two points
  25859. var lengthBefore = arcLengths[ i ];
  25860. var lengthAfter = arcLengths[ i + 1 ];
  25861. var segmentLength = lengthAfter - lengthBefore;
  25862. // determine where we are between the 'before' and 'after' points
  25863. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  25864. // add that fractional amount to t
  25865. var t = ( i + segmentFraction ) / ( il - 1 );
  25866. return t;
  25867. },
  25868. // Returns a unit vector tangent at t
  25869. // In case any sub curve does not implement its tangent derivation,
  25870. // 2 points a small delta apart will be used to find its gradient
  25871. // which seems to give a reasonable approximation
  25872. getTangent: function ( t ) {
  25873. var delta = 0.0001;
  25874. var t1 = t - delta;
  25875. var t2 = t + delta;
  25876. // Capping in case of danger
  25877. if ( t1 < 0 ) t1 = 0;
  25878. if ( t2 > 1 ) t2 = 1;
  25879. var pt1 = this.getPoint( t1 );
  25880. var pt2 = this.getPoint( t2 );
  25881. var vec = pt2.clone().sub( pt1 );
  25882. return vec.normalize();
  25883. },
  25884. getTangentAt: function ( u ) {
  25885. var t = this.getUtoTmapping( u );
  25886. return this.getTangent( t );
  25887. },
  25888. computeFrenetFrames: function ( segments, closed ) {
  25889. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  25890. var normal = new Vector3();
  25891. var tangents = [];
  25892. var normals = [];
  25893. var binormals = [];
  25894. var vec = new Vector3();
  25895. var mat = new Matrix4();
  25896. var i, u, theta;
  25897. // compute the tangent vectors for each segment on the curve
  25898. for ( i = 0; i <= segments; i ++ ) {
  25899. u = i / segments;
  25900. tangents[ i ] = this.getTangentAt( u );
  25901. tangents[ i ].normalize();
  25902. }
  25903. // select an initial normal vector perpendicular to the first tangent vector,
  25904. // and in the direction of the minimum tangent xyz component
  25905. normals[ 0 ] = new Vector3();
  25906. binormals[ 0 ] = new Vector3();
  25907. var min = Number.MAX_VALUE;
  25908. var tx = Math.abs( tangents[ 0 ].x );
  25909. var ty = Math.abs( tangents[ 0 ].y );
  25910. var tz = Math.abs( tangents[ 0 ].z );
  25911. if ( tx <= min ) {
  25912. min = tx;
  25913. normal.set( 1, 0, 0 );
  25914. }
  25915. if ( ty <= min ) {
  25916. min = ty;
  25917. normal.set( 0, 1, 0 );
  25918. }
  25919. if ( tz <= min ) {
  25920. normal.set( 0, 0, 1 );
  25921. }
  25922. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  25923. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  25924. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  25925. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  25926. for ( i = 1; i <= segments; i ++ ) {
  25927. normals[ i ] = normals[ i - 1 ].clone();
  25928. binormals[ i ] = binormals[ i - 1 ].clone();
  25929. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  25930. if ( vec.length() > Number.EPSILON ) {
  25931. vec.normalize();
  25932. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  25933. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  25934. }
  25935. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25936. }
  25937. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  25938. if ( closed === true ) {
  25939. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  25940. theta /= segments;
  25941. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  25942. theta = - theta;
  25943. }
  25944. for ( i = 1; i <= segments; i ++ ) {
  25945. // twist a little...
  25946. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  25947. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25948. }
  25949. }
  25950. return {
  25951. tangents: tangents,
  25952. normals: normals,
  25953. binormals: binormals
  25954. };
  25955. },
  25956. clone: function () {
  25957. return new this.constructor().copy( this );
  25958. },
  25959. copy: function ( source ) {
  25960. this.arcLengthDivisions = source.arcLengthDivisions;
  25961. return this;
  25962. },
  25963. toJSON: function () {
  25964. var data = {
  25965. metadata: {
  25966. version: 4.5,
  25967. type: 'Curve',
  25968. generator: 'Curve.toJSON'
  25969. }
  25970. };
  25971. data.arcLengthDivisions = this.arcLengthDivisions;
  25972. data.type = this.type;
  25973. return data;
  25974. },
  25975. fromJSON: function ( json ) {
  25976. this.arcLengthDivisions = json.arcLengthDivisions;
  25977. return this;
  25978. }
  25979. } );
  25980. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25981. Curve.call( this );
  25982. this.type = 'EllipseCurve';
  25983. this.aX = aX || 0;
  25984. this.aY = aY || 0;
  25985. this.xRadius = xRadius || 1;
  25986. this.yRadius = yRadius || 1;
  25987. this.aStartAngle = aStartAngle || 0;
  25988. this.aEndAngle = aEndAngle || 2 * Math.PI;
  25989. this.aClockwise = aClockwise || false;
  25990. this.aRotation = aRotation || 0;
  25991. }
  25992. EllipseCurve.prototype = Object.create( Curve.prototype );
  25993. EllipseCurve.prototype.constructor = EllipseCurve;
  25994. EllipseCurve.prototype.isEllipseCurve = true;
  25995. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  25996. var point = optionalTarget || new Vector2();
  25997. var twoPi = Math.PI * 2;
  25998. var deltaAngle = this.aEndAngle - this.aStartAngle;
  25999. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  26000. // ensures that deltaAngle is 0 .. 2 PI
  26001. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  26002. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  26003. if ( deltaAngle < Number.EPSILON ) {
  26004. if ( samePoints ) {
  26005. deltaAngle = 0;
  26006. } else {
  26007. deltaAngle = twoPi;
  26008. }
  26009. }
  26010. if ( this.aClockwise === true && ! samePoints ) {
  26011. if ( deltaAngle === twoPi ) {
  26012. deltaAngle = - twoPi;
  26013. } else {
  26014. deltaAngle = deltaAngle - twoPi;
  26015. }
  26016. }
  26017. var angle = this.aStartAngle + t * deltaAngle;
  26018. var x = this.aX + this.xRadius * Math.cos( angle );
  26019. var y = this.aY + this.yRadius * Math.sin( angle );
  26020. if ( this.aRotation !== 0 ) {
  26021. var cos = Math.cos( this.aRotation );
  26022. var sin = Math.sin( this.aRotation );
  26023. var tx = x - this.aX;
  26024. var ty = y - this.aY;
  26025. // Rotate the point about the center of the ellipse.
  26026. x = tx * cos - ty * sin + this.aX;
  26027. y = tx * sin + ty * cos + this.aY;
  26028. }
  26029. return point.set( x, y );
  26030. };
  26031. EllipseCurve.prototype.copy = function ( source ) {
  26032. Curve.prototype.copy.call( this, source );
  26033. this.aX = source.aX;
  26034. this.aY = source.aY;
  26035. this.xRadius = source.xRadius;
  26036. this.yRadius = source.yRadius;
  26037. this.aStartAngle = source.aStartAngle;
  26038. this.aEndAngle = source.aEndAngle;
  26039. this.aClockwise = source.aClockwise;
  26040. this.aRotation = source.aRotation;
  26041. return this;
  26042. };
  26043. EllipseCurve.prototype.toJSON = function () {
  26044. var data = Curve.prototype.toJSON.call( this );
  26045. data.aX = this.aX;
  26046. data.aY = this.aY;
  26047. data.xRadius = this.xRadius;
  26048. data.yRadius = this.yRadius;
  26049. data.aStartAngle = this.aStartAngle;
  26050. data.aEndAngle = this.aEndAngle;
  26051. data.aClockwise = this.aClockwise;
  26052. data.aRotation = this.aRotation;
  26053. return data;
  26054. };
  26055. EllipseCurve.prototype.fromJSON = function ( json ) {
  26056. Curve.prototype.fromJSON.call( this, json );
  26057. this.aX = json.aX;
  26058. this.aY = json.aY;
  26059. this.xRadius = json.xRadius;
  26060. this.yRadius = json.yRadius;
  26061. this.aStartAngle = json.aStartAngle;
  26062. this.aEndAngle = json.aEndAngle;
  26063. this.aClockwise = json.aClockwise;
  26064. this.aRotation = json.aRotation;
  26065. return this;
  26066. };
  26067. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  26068. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  26069. this.type = 'ArcCurve';
  26070. }
  26071. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  26072. ArcCurve.prototype.constructor = ArcCurve;
  26073. ArcCurve.prototype.isArcCurve = true;
  26074. /**
  26075. * @author zz85 https://github.com/zz85
  26076. *
  26077. * Centripetal CatmullRom Curve - which is useful for avoiding
  26078. * cusps and self-intersections in non-uniform catmull rom curves.
  26079. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  26080. *
  26081. * curve.type accepts centripetal(default), chordal and catmullrom
  26082. * curve.tension is used for catmullrom which defaults to 0.5
  26083. */
  26084. /*
  26085. Based on an optimized c++ solution in
  26086. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  26087. - http://ideone.com/NoEbVM
  26088. This CubicPoly class could be used for reusing some variables and calculations,
  26089. but for three.js curve use, it could be possible inlined and flatten into a single function call
  26090. which can be placed in CurveUtils.
  26091. */
  26092. function CubicPoly() {
  26093. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  26094. /*
  26095. * Compute coefficients for a cubic polynomial
  26096. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  26097. * such that
  26098. * p(0) = x0, p(1) = x1
  26099. * and
  26100. * p'(0) = t0, p'(1) = t1.
  26101. */
  26102. function init( x0, x1, t0, t1 ) {
  26103. c0 = x0;
  26104. c1 = t0;
  26105. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  26106. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  26107. }
  26108. return {
  26109. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  26110. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  26111. },
  26112. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  26113. // compute tangents when parameterized in [t1,t2]
  26114. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  26115. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  26116. // rescale tangents for parametrization in [0,1]
  26117. t1 *= dt1;
  26118. t2 *= dt1;
  26119. init( x1, x2, t1, t2 );
  26120. },
  26121. calc: function ( t ) {
  26122. var t2 = t * t;
  26123. var t3 = t2 * t;
  26124. return c0 + c1 * t + c2 * t2 + c3 * t3;
  26125. }
  26126. };
  26127. }
  26128. //
  26129. var tmp = new Vector3();
  26130. var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  26131. function CatmullRomCurve3( points, closed, curveType, tension ) {
  26132. Curve.call( this );
  26133. this.type = 'CatmullRomCurve3';
  26134. this.points = points || [];
  26135. this.closed = closed || false;
  26136. this.curveType = curveType || 'centripetal';
  26137. this.tension = tension || 0.5;
  26138. }
  26139. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  26140. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  26141. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  26142. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26143. var point = optionalTarget || new Vector3();
  26144. var points = this.points;
  26145. var l = points.length;
  26146. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  26147. var intPoint = Math.floor( p );
  26148. var weight = p - intPoint;
  26149. if ( this.closed ) {
  26150. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  26151. } else if ( weight === 0 && intPoint === l - 1 ) {
  26152. intPoint = l - 2;
  26153. weight = 1;
  26154. }
  26155. var p0, p1, p2, p3; // 4 points
  26156. if ( this.closed || intPoint > 0 ) {
  26157. p0 = points[ ( intPoint - 1 ) % l ];
  26158. } else {
  26159. // extrapolate first point
  26160. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  26161. p0 = tmp;
  26162. }
  26163. p1 = points[ intPoint % l ];
  26164. p2 = points[ ( intPoint + 1 ) % l ];
  26165. if ( this.closed || intPoint + 2 < l ) {
  26166. p3 = points[ ( intPoint + 2 ) % l ];
  26167. } else {
  26168. // extrapolate last point
  26169. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  26170. p3 = tmp;
  26171. }
  26172. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  26173. // init Centripetal / Chordal Catmull-Rom
  26174. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  26175. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  26176. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  26177. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  26178. // safety check for repeated points
  26179. if ( dt1 < 1e-4 ) dt1 = 1.0;
  26180. if ( dt0 < 1e-4 ) dt0 = dt1;
  26181. if ( dt2 < 1e-4 ) dt2 = dt1;
  26182. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  26183. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  26184. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  26185. } else if ( this.curveType === 'catmullrom' ) {
  26186. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  26187. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  26188. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  26189. }
  26190. point.set(
  26191. px.calc( weight ),
  26192. py.calc( weight ),
  26193. pz.calc( weight )
  26194. );
  26195. return point;
  26196. };
  26197. CatmullRomCurve3.prototype.copy = function ( source ) {
  26198. Curve.prototype.copy.call( this, source );
  26199. this.points = [];
  26200. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  26201. var point = source.points[ i ];
  26202. this.points.push( point.clone() );
  26203. }
  26204. this.closed = source.closed;
  26205. this.curveType = source.curveType;
  26206. this.tension = source.tension;
  26207. return this;
  26208. };
  26209. CatmullRomCurve3.prototype.toJSON = function () {
  26210. var data = Curve.prototype.toJSON.call( this );
  26211. data.points = [];
  26212. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  26213. var point = this.points[ i ];
  26214. data.points.push( point.toArray() );
  26215. }
  26216. data.closed = this.closed;
  26217. data.curveType = this.curveType;
  26218. data.tension = this.tension;
  26219. return data;
  26220. };
  26221. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  26222. Curve.prototype.fromJSON.call( this, json );
  26223. this.points = [];
  26224. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  26225. var point = json.points[ i ];
  26226. this.points.push( new Vector3().fromArray( point ) );
  26227. }
  26228. this.closed = json.closed;
  26229. this.curveType = json.curveType;
  26230. this.tension = json.tension;
  26231. return this;
  26232. };
  26233. /**
  26234. * @author zz85 / http://www.lab4games.net/zz85/blog
  26235. *
  26236. * Bezier Curves formulas obtained from
  26237. * http://en.wikipedia.org/wiki/Bézier_curve
  26238. */
  26239. function CatmullRom( t, p0, p1, p2, p3 ) {
  26240. var v0 = ( p2 - p0 ) * 0.5;
  26241. var v1 = ( p3 - p1 ) * 0.5;
  26242. var t2 = t * t;
  26243. var t3 = t * t2;
  26244. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  26245. }
  26246. //
  26247. function QuadraticBezierP0( t, p ) {
  26248. var k = 1 - t;
  26249. return k * k * p;
  26250. }
  26251. function QuadraticBezierP1( t, p ) {
  26252. return 2 * ( 1 - t ) * t * p;
  26253. }
  26254. function QuadraticBezierP2( t, p ) {
  26255. return t * t * p;
  26256. }
  26257. function QuadraticBezier( t, p0, p1, p2 ) {
  26258. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  26259. QuadraticBezierP2( t, p2 );
  26260. }
  26261. //
  26262. function CubicBezierP0( t, p ) {
  26263. var k = 1 - t;
  26264. return k * k * k * p;
  26265. }
  26266. function CubicBezierP1( t, p ) {
  26267. var k = 1 - t;
  26268. return 3 * k * k * t * p;
  26269. }
  26270. function CubicBezierP2( t, p ) {
  26271. return 3 * ( 1 - t ) * t * t * p;
  26272. }
  26273. function CubicBezierP3( t, p ) {
  26274. return t * t * t * p;
  26275. }
  26276. function CubicBezier( t, p0, p1, p2, p3 ) {
  26277. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  26278. CubicBezierP3( t, p3 );
  26279. }
  26280. function CubicBezierCurve( v0, v1, v2, v3 ) {
  26281. Curve.call( this );
  26282. this.type = 'CubicBezierCurve';
  26283. this.v0 = v0 || new Vector2();
  26284. this.v1 = v1 || new Vector2();
  26285. this.v2 = v2 || new Vector2();
  26286. this.v3 = v3 || new Vector2();
  26287. }
  26288. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  26289. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  26290. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  26291. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26292. var point = optionalTarget || new Vector2();
  26293. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  26294. point.set(
  26295. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  26296. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  26297. );
  26298. return point;
  26299. };
  26300. CubicBezierCurve.prototype.copy = function ( source ) {
  26301. Curve.prototype.copy.call( this, source );
  26302. this.v0.copy( source.v0 );
  26303. this.v1.copy( source.v1 );
  26304. this.v2.copy( source.v2 );
  26305. this.v3.copy( source.v3 );
  26306. return this;
  26307. };
  26308. CubicBezierCurve.prototype.toJSON = function () {
  26309. var data = Curve.prototype.toJSON.call( this );
  26310. data.v0 = this.v0.toArray();
  26311. data.v1 = this.v1.toArray();
  26312. data.v2 = this.v2.toArray();
  26313. data.v3 = this.v3.toArray();
  26314. return data;
  26315. };
  26316. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  26317. Curve.prototype.fromJSON.call( this, json );
  26318. this.v0.fromArray( json.v0 );
  26319. this.v1.fromArray( json.v1 );
  26320. this.v2.fromArray( json.v2 );
  26321. this.v3.fromArray( json.v3 );
  26322. return this;
  26323. };
  26324. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  26325. Curve.call( this );
  26326. this.type = 'CubicBezierCurve3';
  26327. this.v0 = v0 || new Vector3();
  26328. this.v1 = v1 || new Vector3();
  26329. this.v2 = v2 || new Vector3();
  26330. this.v3 = v3 || new Vector3();
  26331. }
  26332. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  26333. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  26334. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  26335. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26336. var point = optionalTarget || new Vector3();
  26337. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  26338. point.set(
  26339. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  26340. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  26341. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  26342. );
  26343. return point;
  26344. };
  26345. CubicBezierCurve3.prototype.copy = function ( source ) {
  26346. Curve.prototype.copy.call( this, source );
  26347. this.v0.copy( source.v0 );
  26348. this.v1.copy( source.v1 );
  26349. this.v2.copy( source.v2 );
  26350. this.v3.copy( source.v3 );
  26351. return this;
  26352. };
  26353. CubicBezierCurve3.prototype.toJSON = function () {
  26354. var data = Curve.prototype.toJSON.call( this );
  26355. data.v0 = this.v0.toArray();
  26356. data.v1 = this.v1.toArray();
  26357. data.v2 = this.v2.toArray();
  26358. data.v3 = this.v3.toArray();
  26359. return data;
  26360. };
  26361. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  26362. Curve.prototype.fromJSON.call( this, json );
  26363. this.v0.fromArray( json.v0 );
  26364. this.v1.fromArray( json.v1 );
  26365. this.v2.fromArray( json.v2 );
  26366. this.v3.fromArray( json.v3 );
  26367. return this;
  26368. };
  26369. function LineCurve( v1, v2 ) {
  26370. Curve.call( this );
  26371. this.type = 'LineCurve';
  26372. this.v1 = v1 || new Vector2();
  26373. this.v2 = v2 || new Vector2();
  26374. }
  26375. LineCurve.prototype = Object.create( Curve.prototype );
  26376. LineCurve.prototype.constructor = LineCurve;
  26377. LineCurve.prototype.isLineCurve = true;
  26378. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26379. var point = optionalTarget || new Vector2();
  26380. if ( t === 1 ) {
  26381. point.copy( this.v2 );
  26382. } else {
  26383. point.copy( this.v2 ).sub( this.v1 );
  26384. point.multiplyScalar( t ).add( this.v1 );
  26385. }
  26386. return point;
  26387. };
  26388. // Line curve is linear, so we can overwrite default getPointAt
  26389. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  26390. return this.getPoint( u, optionalTarget );
  26391. };
  26392. LineCurve.prototype.getTangent = function ( /* t */ ) {
  26393. var tangent = this.v2.clone().sub( this.v1 );
  26394. return tangent.normalize();
  26395. };
  26396. LineCurve.prototype.copy = function ( source ) {
  26397. Curve.prototype.copy.call( this, source );
  26398. this.v1.copy( source.v1 );
  26399. this.v2.copy( source.v2 );
  26400. return this;
  26401. };
  26402. LineCurve.prototype.toJSON = function () {
  26403. var data = Curve.prototype.toJSON.call( this );
  26404. data.v1 = this.v1.toArray();
  26405. data.v2 = this.v2.toArray();
  26406. return data;
  26407. };
  26408. LineCurve.prototype.fromJSON = function ( json ) {
  26409. Curve.prototype.fromJSON.call( this, json );
  26410. this.v1.fromArray( json.v1 );
  26411. this.v2.fromArray( json.v2 );
  26412. return this;
  26413. };
  26414. function LineCurve3( v1, v2 ) {
  26415. Curve.call( this );
  26416. this.type = 'LineCurve3';
  26417. this.v1 = v1 || new Vector3();
  26418. this.v2 = v2 || new Vector3();
  26419. }
  26420. LineCurve3.prototype = Object.create( Curve.prototype );
  26421. LineCurve3.prototype.constructor = LineCurve3;
  26422. LineCurve3.prototype.isLineCurve3 = true;
  26423. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26424. var point = optionalTarget || new Vector3();
  26425. if ( t === 1 ) {
  26426. point.copy( this.v2 );
  26427. } else {
  26428. point.copy( this.v2 ).sub( this.v1 );
  26429. point.multiplyScalar( t ).add( this.v1 );
  26430. }
  26431. return point;
  26432. };
  26433. // Line curve is linear, so we can overwrite default getPointAt
  26434. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  26435. return this.getPoint( u, optionalTarget );
  26436. };
  26437. LineCurve3.prototype.copy = function ( source ) {
  26438. Curve.prototype.copy.call( this, source );
  26439. this.v1.copy( source.v1 );
  26440. this.v2.copy( source.v2 );
  26441. return this;
  26442. };
  26443. LineCurve3.prototype.toJSON = function () {
  26444. var data = Curve.prototype.toJSON.call( this );
  26445. data.v1 = this.v1.toArray();
  26446. data.v2 = this.v2.toArray();
  26447. return data;
  26448. };
  26449. LineCurve3.prototype.fromJSON = function ( json ) {
  26450. Curve.prototype.fromJSON.call( this, json );
  26451. this.v1.fromArray( json.v1 );
  26452. this.v2.fromArray( json.v2 );
  26453. return this;
  26454. };
  26455. function QuadraticBezierCurve( v0, v1, v2 ) {
  26456. Curve.call( this );
  26457. this.type = 'QuadraticBezierCurve';
  26458. this.v0 = v0 || new Vector2();
  26459. this.v1 = v1 || new Vector2();
  26460. this.v2 = v2 || new Vector2();
  26461. }
  26462. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  26463. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  26464. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  26465. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26466. var point = optionalTarget || new Vector2();
  26467. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  26468. point.set(
  26469. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  26470. QuadraticBezier( t, v0.y, v1.y, v2.y )
  26471. );
  26472. return point;
  26473. };
  26474. QuadraticBezierCurve.prototype.copy = function ( source ) {
  26475. Curve.prototype.copy.call( this, source );
  26476. this.v0.copy( source.v0 );
  26477. this.v1.copy( source.v1 );
  26478. this.v2.copy( source.v2 );
  26479. return this;
  26480. };
  26481. QuadraticBezierCurve.prototype.toJSON = function () {
  26482. var data = Curve.prototype.toJSON.call( this );
  26483. data.v0 = this.v0.toArray();
  26484. data.v1 = this.v1.toArray();
  26485. data.v2 = this.v2.toArray();
  26486. return data;
  26487. };
  26488. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  26489. Curve.prototype.fromJSON.call( this, json );
  26490. this.v0.fromArray( json.v0 );
  26491. this.v1.fromArray( json.v1 );
  26492. this.v2.fromArray( json.v2 );
  26493. return this;
  26494. };
  26495. function QuadraticBezierCurve3( v0, v1, v2 ) {
  26496. Curve.call( this );
  26497. this.type = 'QuadraticBezierCurve3';
  26498. this.v0 = v0 || new Vector3();
  26499. this.v1 = v1 || new Vector3();
  26500. this.v2 = v2 || new Vector3();
  26501. }
  26502. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  26503. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  26504. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  26505. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  26506. var point = optionalTarget || new Vector3();
  26507. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  26508. point.set(
  26509. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  26510. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  26511. QuadraticBezier( t, v0.z, v1.z, v2.z )
  26512. );
  26513. return point;
  26514. };
  26515. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  26516. Curve.prototype.copy.call( this, source );
  26517. this.v0.copy( source.v0 );
  26518. this.v1.copy( source.v1 );
  26519. this.v2.copy( source.v2 );
  26520. return this;
  26521. };
  26522. QuadraticBezierCurve3.prototype.toJSON = function () {
  26523. var data = Curve.prototype.toJSON.call( this );
  26524. data.v0 = this.v0.toArray();
  26525. data.v1 = this.v1.toArray();
  26526. data.v2 = this.v2.toArray();
  26527. return data;
  26528. };
  26529. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  26530. Curve.prototype.fromJSON.call( this, json );
  26531. this.v0.fromArray( json.v0 );
  26532. this.v1.fromArray( json.v1 );
  26533. this.v2.fromArray( json.v2 );
  26534. return this;
  26535. };
  26536. function SplineCurve( points /* array of Vector2 */ ) {
  26537. Curve.call( this );
  26538. this.type = 'SplineCurve';
  26539. this.points = points || [];
  26540. }
  26541. SplineCurve.prototype = Object.create( Curve.prototype );
  26542. SplineCurve.prototype.constructor = SplineCurve;
  26543. SplineCurve.prototype.isSplineCurve = true;
  26544. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  26545. var point = optionalTarget || new Vector2();
  26546. var points = this.points;
  26547. var p = ( points.length - 1 ) * t;
  26548. var intPoint = Math.floor( p );
  26549. var weight = p - intPoint;
  26550. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  26551. var p1 = points[ intPoint ];
  26552. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  26553. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  26554. point.set(
  26555. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  26556. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  26557. );
  26558. return point;
  26559. };
  26560. SplineCurve.prototype.copy = function ( source ) {
  26561. Curve.prototype.copy.call( this, source );
  26562. this.points = [];
  26563. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  26564. var point = source.points[ i ];
  26565. this.points.push( point.clone() );
  26566. }
  26567. return this;
  26568. };
  26569. SplineCurve.prototype.toJSON = function () {
  26570. var data = Curve.prototype.toJSON.call( this );
  26571. data.points = [];
  26572. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  26573. var point = this.points[ i ];
  26574. data.points.push( point.toArray() );
  26575. }
  26576. return data;
  26577. };
  26578. SplineCurve.prototype.fromJSON = function ( json ) {
  26579. Curve.prototype.fromJSON.call( this, json );
  26580. this.points = [];
  26581. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  26582. var point = json.points[ i ];
  26583. this.points.push( new Vector2().fromArray( point ) );
  26584. }
  26585. return this;
  26586. };
  26587. var Curves = /*#__PURE__*/Object.freeze({
  26588. ArcCurve: ArcCurve,
  26589. CatmullRomCurve3: CatmullRomCurve3,
  26590. CubicBezierCurve: CubicBezierCurve,
  26591. CubicBezierCurve3: CubicBezierCurve3,
  26592. EllipseCurve: EllipseCurve,
  26593. LineCurve: LineCurve,
  26594. LineCurve3: LineCurve3,
  26595. QuadraticBezierCurve: QuadraticBezierCurve,
  26596. QuadraticBezierCurve3: QuadraticBezierCurve3,
  26597. SplineCurve: SplineCurve
  26598. });
  26599. /**
  26600. * @author zz85 / http://www.lab4games.net/zz85/blog
  26601. *
  26602. **/
  26603. /**************************************************************
  26604. * Curved Path - a curve path is simply a array of connected
  26605. * curves, but retains the api of a curve
  26606. **************************************************************/
  26607. function CurvePath() {
  26608. Curve.call( this );
  26609. this.type = 'CurvePath';
  26610. this.curves = [];
  26611. this.autoClose = false; // Automatically closes the path
  26612. }
  26613. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  26614. constructor: CurvePath,
  26615. add: function ( curve ) {
  26616. this.curves.push( curve );
  26617. },
  26618. closePath: function () {
  26619. // Add a line curve if start and end of lines are not connected
  26620. var startPoint = this.curves[ 0 ].getPoint( 0 );
  26621. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  26622. if ( ! startPoint.equals( endPoint ) ) {
  26623. this.curves.push( new LineCurve( endPoint, startPoint ) );
  26624. }
  26625. },
  26626. // To get accurate point with reference to
  26627. // entire path distance at time t,
  26628. // following has to be done:
  26629. // 1. Length of each sub path have to be known
  26630. // 2. Locate and identify type of curve
  26631. // 3. Get t for the curve
  26632. // 4. Return curve.getPointAt(t')
  26633. getPoint: function ( t ) {
  26634. var d = t * this.getLength();
  26635. var curveLengths = this.getCurveLengths();
  26636. var i = 0;
  26637. // To think about boundaries points.
  26638. while ( i < curveLengths.length ) {
  26639. if ( curveLengths[ i ] >= d ) {
  26640. var diff = curveLengths[ i ] - d;
  26641. var curve = this.curves[ i ];
  26642. var segmentLength = curve.getLength();
  26643. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  26644. return curve.getPointAt( u );
  26645. }
  26646. i ++;
  26647. }
  26648. return null;
  26649. // loop where sum != 0, sum > d , sum+1 <d
  26650. },
  26651. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  26652. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  26653. // getPoint() depends on getLength
  26654. getLength: function () {
  26655. var lens = this.getCurveLengths();
  26656. return lens[ lens.length - 1 ];
  26657. },
  26658. // cacheLengths must be recalculated.
  26659. updateArcLengths: function () {
  26660. this.needsUpdate = true;
  26661. this.cacheLengths = null;
  26662. this.getCurveLengths();
  26663. },
  26664. // Compute lengths and cache them
  26665. // We cannot overwrite getLengths() because UtoT mapping uses it.
  26666. getCurveLengths: function () {
  26667. // We use cache values if curves and cache array are same length
  26668. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  26669. return this.cacheLengths;
  26670. }
  26671. // Get length of sub-curve
  26672. // Push sums into cached array
  26673. var lengths = [], sums = 0;
  26674. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  26675. sums += this.curves[ i ].getLength();
  26676. lengths.push( sums );
  26677. }
  26678. this.cacheLengths = lengths;
  26679. return lengths;
  26680. },
  26681. getSpacedPoints: function ( divisions ) {
  26682. if ( divisions === undefined ) divisions = 40;
  26683. var points = [];
  26684. for ( var i = 0; i <= divisions; i ++ ) {
  26685. points.push( this.getPoint( i / divisions ) );
  26686. }
  26687. if ( this.autoClose ) {
  26688. points.push( points[ 0 ] );
  26689. }
  26690. return points;
  26691. },
  26692. getPoints: function ( divisions ) {
  26693. divisions = divisions || 12;
  26694. var points = [], last;
  26695. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  26696. var curve = curves[ i ];
  26697. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  26698. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  26699. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  26700. : divisions;
  26701. var pts = curve.getPoints( resolution );
  26702. for ( var j = 0; j < pts.length; j ++ ) {
  26703. var point = pts[ j ];
  26704. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  26705. points.push( point );
  26706. last = point;
  26707. }
  26708. }
  26709. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  26710. points.push( points[ 0 ] );
  26711. }
  26712. return points;
  26713. },
  26714. copy: function ( source ) {
  26715. Curve.prototype.copy.call( this, source );
  26716. this.curves = [];
  26717. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  26718. var curve = source.curves[ i ];
  26719. this.curves.push( curve.clone() );
  26720. }
  26721. this.autoClose = source.autoClose;
  26722. return this;
  26723. },
  26724. toJSON: function () {
  26725. var data = Curve.prototype.toJSON.call( this );
  26726. data.autoClose = this.autoClose;
  26727. data.curves = [];
  26728. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  26729. var curve = this.curves[ i ];
  26730. data.curves.push( curve.toJSON() );
  26731. }
  26732. return data;
  26733. },
  26734. fromJSON: function ( json ) {
  26735. Curve.prototype.fromJSON.call( this, json );
  26736. this.autoClose = json.autoClose;
  26737. this.curves = [];
  26738. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  26739. var curve = json.curves[ i ];
  26740. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  26741. }
  26742. return this;
  26743. }
  26744. } );
  26745. /**
  26746. * @author zz85 / http://www.lab4games.net/zz85/blog
  26747. * Creates free form 2d path using series of points, lines or curves.
  26748. **/
  26749. function Path( points ) {
  26750. CurvePath.call( this );
  26751. this.type = 'Path';
  26752. this.currentPoint = new Vector2();
  26753. if ( points ) {
  26754. this.setFromPoints( points );
  26755. }
  26756. }
  26757. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  26758. constructor: Path,
  26759. setFromPoints: function ( points ) {
  26760. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  26761. for ( var i = 1, l = points.length; i < l; i ++ ) {
  26762. this.lineTo( points[ i ].x, points[ i ].y );
  26763. }
  26764. },
  26765. moveTo: function ( x, y ) {
  26766. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  26767. },
  26768. lineTo: function ( x, y ) {
  26769. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  26770. this.curves.push( curve );
  26771. this.currentPoint.set( x, y );
  26772. },
  26773. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  26774. var curve = new QuadraticBezierCurve(
  26775. this.currentPoint.clone(),
  26776. new Vector2( aCPx, aCPy ),
  26777. new Vector2( aX, aY )
  26778. );
  26779. this.curves.push( curve );
  26780. this.currentPoint.set( aX, aY );
  26781. },
  26782. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  26783. var curve = new CubicBezierCurve(
  26784. this.currentPoint.clone(),
  26785. new Vector2( aCP1x, aCP1y ),
  26786. new Vector2( aCP2x, aCP2y ),
  26787. new Vector2( aX, aY )
  26788. );
  26789. this.curves.push( curve );
  26790. this.currentPoint.set( aX, aY );
  26791. },
  26792. splineThru: function ( pts /*Array of Vector*/ ) {
  26793. var npts = [ this.currentPoint.clone() ].concat( pts );
  26794. var curve = new SplineCurve( npts );
  26795. this.curves.push( curve );
  26796. this.currentPoint.copy( pts[ pts.length - 1 ] );
  26797. },
  26798. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  26799. var x0 = this.currentPoint.x;
  26800. var y0 = this.currentPoint.y;
  26801. this.absarc( aX + x0, aY + y0, aRadius,
  26802. aStartAngle, aEndAngle, aClockwise );
  26803. },
  26804. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  26805. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  26806. },
  26807. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  26808. var x0 = this.currentPoint.x;
  26809. var y0 = this.currentPoint.y;
  26810. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  26811. },
  26812. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  26813. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  26814. if ( this.curves.length > 0 ) {
  26815. // if a previous curve is present, attempt to join
  26816. var firstPoint = curve.getPoint( 0 );
  26817. if ( ! firstPoint.equals( this.currentPoint ) ) {
  26818. this.lineTo( firstPoint.x, firstPoint.y );
  26819. }
  26820. }
  26821. this.curves.push( curve );
  26822. var lastPoint = curve.getPoint( 1 );
  26823. this.currentPoint.copy( lastPoint );
  26824. },
  26825. copy: function ( source ) {
  26826. CurvePath.prototype.copy.call( this, source );
  26827. this.currentPoint.copy( source.currentPoint );
  26828. return this;
  26829. },
  26830. toJSON: function () {
  26831. var data = CurvePath.prototype.toJSON.call( this );
  26832. data.currentPoint = this.currentPoint.toArray();
  26833. return data;
  26834. },
  26835. fromJSON: function ( json ) {
  26836. CurvePath.prototype.fromJSON.call( this, json );
  26837. this.currentPoint.fromArray( json.currentPoint );
  26838. return this;
  26839. }
  26840. } );
  26841. /**
  26842. * @author zz85 / http://www.lab4games.net/zz85/blog
  26843. * Defines a 2d shape plane using paths.
  26844. **/
  26845. // STEP 1 Create a path.
  26846. // STEP 2 Turn path into shape.
  26847. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  26848. // STEP 3a - Extract points from each shape, turn to vertices
  26849. // STEP 3b - Triangulate each shape, add faces.
  26850. function Shape( points ) {
  26851. Path.call( this, points );
  26852. this.uuid = _Math.generateUUID();
  26853. this.type = 'Shape';
  26854. this.holes = [];
  26855. }
  26856. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  26857. constructor: Shape,
  26858. getPointsHoles: function ( divisions ) {
  26859. var holesPts = [];
  26860. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  26861. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  26862. }
  26863. return holesPts;
  26864. },
  26865. // get points of shape and holes (keypoints based on segments parameter)
  26866. extractPoints: function ( divisions ) {
  26867. return {
  26868. shape: this.getPoints( divisions ),
  26869. holes: this.getPointsHoles( divisions )
  26870. };
  26871. },
  26872. copy: function ( source ) {
  26873. Path.prototype.copy.call( this, source );
  26874. this.holes = [];
  26875. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  26876. var hole = source.holes[ i ];
  26877. this.holes.push( hole.clone() );
  26878. }
  26879. return this;
  26880. },
  26881. toJSON: function () {
  26882. var data = Path.prototype.toJSON.call( this );
  26883. data.uuid = this.uuid;
  26884. data.holes = [];
  26885. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  26886. var hole = this.holes[ i ];
  26887. data.holes.push( hole.toJSON() );
  26888. }
  26889. return data;
  26890. },
  26891. fromJSON: function ( json ) {
  26892. Path.prototype.fromJSON.call( this, json );
  26893. this.uuid = json.uuid;
  26894. this.holes = [];
  26895. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  26896. var hole = json.holes[ i ];
  26897. this.holes.push( new Path().fromJSON( hole ) );
  26898. }
  26899. return this;
  26900. }
  26901. } );
  26902. /**
  26903. * @author mrdoob / http://mrdoob.com/
  26904. * @author alteredq / http://alteredqualia.com/
  26905. */
  26906. function Light( color, intensity ) {
  26907. Object3D.call( this );
  26908. this.type = 'Light';
  26909. this.color = new Color( color );
  26910. this.intensity = intensity !== undefined ? intensity : 1;
  26911. this.receiveShadow = undefined;
  26912. }
  26913. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  26914. constructor: Light,
  26915. isLight: true,
  26916. copy: function ( source ) {
  26917. Object3D.prototype.copy.call( this, source );
  26918. this.color.copy( source.color );
  26919. this.intensity = source.intensity;
  26920. return this;
  26921. },
  26922. toJSON: function ( meta ) {
  26923. var data = Object3D.prototype.toJSON.call( this, meta );
  26924. data.object.color = this.color.getHex();
  26925. data.object.intensity = this.intensity;
  26926. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26927. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26928. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26929. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26930. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26931. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26932. return data;
  26933. }
  26934. } );
  26935. /**
  26936. * @author alteredq / http://alteredqualia.com/
  26937. */
  26938. function HemisphereLight( skyColor, groundColor, intensity ) {
  26939. Light.call( this, skyColor, intensity );
  26940. this.type = 'HemisphereLight';
  26941. this.castShadow = undefined;
  26942. this.position.copy( Object3D.DefaultUp );
  26943. this.updateMatrix();
  26944. this.groundColor = new Color( groundColor );
  26945. }
  26946. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  26947. constructor: HemisphereLight,
  26948. isHemisphereLight: true,
  26949. copy: function ( source ) {
  26950. Light.prototype.copy.call( this, source );
  26951. this.groundColor.copy( source.groundColor );
  26952. return this;
  26953. }
  26954. } );
  26955. /**
  26956. * @author mrdoob / http://mrdoob.com/
  26957. */
  26958. function LightShadow( camera ) {
  26959. this.camera = camera;
  26960. this.bias = 0;
  26961. this.radius = 1;
  26962. this.mapSize = new Vector2( 512, 512 );
  26963. this.map = null;
  26964. this.matrix = new Matrix4();
  26965. }
  26966. Object.assign( LightShadow.prototype, {
  26967. copy: function ( source ) {
  26968. this.camera = source.camera.clone();
  26969. this.bias = source.bias;
  26970. this.radius = source.radius;
  26971. this.mapSize.copy( source.mapSize );
  26972. return this;
  26973. },
  26974. clone: function () {
  26975. return new this.constructor().copy( this );
  26976. },
  26977. toJSON: function () {
  26978. var object = {};
  26979. if ( this.bias !== 0 ) object.bias = this.bias;
  26980. if ( this.radius !== 1 ) object.radius = this.radius;
  26981. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26982. object.camera = this.camera.toJSON( false ).object;
  26983. delete object.camera.matrix;
  26984. return object;
  26985. }
  26986. } );
  26987. /**
  26988. * @author mrdoob / http://mrdoob.com/
  26989. */
  26990. function SpotLightShadow() {
  26991. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26992. }
  26993. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  26994. constructor: SpotLightShadow,
  26995. isSpotLightShadow: true,
  26996. update: function ( light ) {
  26997. var camera = this.camera;
  26998. var fov = _Math.RAD2DEG * 2 * light.angle;
  26999. var aspect = this.mapSize.width / this.mapSize.height;
  27000. var far = light.distance || camera.far;
  27001. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  27002. camera.fov = fov;
  27003. camera.aspect = aspect;
  27004. camera.far = far;
  27005. camera.updateProjectionMatrix();
  27006. }
  27007. }
  27008. } );
  27009. /**
  27010. * @author alteredq / http://alteredqualia.com/
  27011. */
  27012. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  27013. Light.call( this, color, intensity );
  27014. this.type = 'SpotLight';
  27015. this.position.copy( Object3D.DefaultUp );
  27016. this.updateMatrix();
  27017. this.target = new Object3D();
  27018. Object.defineProperty( this, 'power', {
  27019. get: function () {
  27020. // intensity = power per solid angle.
  27021. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27022. return this.intensity * Math.PI;
  27023. },
  27024. set: function ( power ) {
  27025. // intensity = power per solid angle.
  27026. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27027. this.intensity = power / Math.PI;
  27028. }
  27029. } );
  27030. this.distance = ( distance !== undefined ) ? distance : 0;
  27031. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  27032. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  27033. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  27034. this.shadow = new SpotLightShadow();
  27035. }
  27036. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27037. constructor: SpotLight,
  27038. isSpotLight: true,
  27039. copy: function ( source ) {
  27040. Light.prototype.copy.call( this, source );
  27041. this.distance = source.distance;
  27042. this.angle = source.angle;
  27043. this.penumbra = source.penumbra;
  27044. this.decay = source.decay;
  27045. this.target = source.target.clone();
  27046. this.shadow = source.shadow.clone();
  27047. return this;
  27048. }
  27049. } );
  27050. /**
  27051. * @author mrdoob / http://mrdoob.com/
  27052. */
  27053. function PointLight( color, intensity, distance, decay ) {
  27054. Light.call( this, color, intensity );
  27055. this.type = 'PointLight';
  27056. Object.defineProperty( this, 'power', {
  27057. get: function () {
  27058. // intensity = power per solid angle.
  27059. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27060. return this.intensity * 4 * Math.PI;
  27061. },
  27062. set: function ( power ) {
  27063. // intensity = power per solid angle.
  27064. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27065. this.intensity = power / ( 4 * Math.PI );
  27066. }
  27067. } );
  27068. this.distance = ( distance !== undefined ) ? distance : 0;
  27069. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  27070. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  27071. }
  27072. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27073. constructor: PointLight,
  27074. isPointLight: true,
  27075. copy: function ( source ) {
  27076. Light.prototype.copy.call( this, source );
  27077. this.distance = source.distance;
  27078. this.decay = source.decay;
  27079. this.shadow = source.shadow.clone();
  27080. return this;
  27081. }
  27082. } );
  27083. /**
  27084. * @author alteredq / http://alteredqualia.com/
  27085. * @author arose / http://github.com/arose
  27086. */
  27087. function OrthographicCamera( left, right, top, bottom, near, far ) {
  27088. Camera.call( this );
  27089. this.type = 'OrthographicCamera';
  27090. this.zoom = 1;
  27091. this.view = null;
  27092. this.left = ( left !== undefined ) ? left : - 1;
  27093. this.right = ( right !== undefined ) ? right : 1;
  27094. this.top = ( top !== undefined ) ? top : 1;
  27095. this.bottom = ( bottom !== undefined ) ? bottom : - 1;
  27096. this.near = ( near !== undefined ) ? near : 0.1;
  27097. this.far = ( far !== undefined ) ? far : 2000;
  27098. this.updateProjectionMatrix();
  27099. }
  27100. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  27101. constructor: OrthographicCamera,
  27102. isOrthographicCamera: true,
  27103. copy: function ( source, recursive ) {
  27104. Camera.prototype.copy.call( this, source, recursive );
  27105. this.left = source.left;
  27106. this.right = source.right;
  27107. this.top = source.top;
  27108. this.bottom = source.bottom;
  27109. this.near = source.near;
  27110. this.far = source.far;
  27111. this.zoom = source.zoom;
  27112. this.view = source.view === null ? null : Object.assign( {}, source.view );
  27113. return this;
  27114. },
  27115. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  27116. if ( this.view === null ) {
  27117. this.view = {
  27118. enabled: true,
  27119. fullWidth: 1,
  27120. fullHeight: 1,
  27121. offsetX: 0,
  27122. offsetY: 0,
  27123. width: 1,
  27124. height: 1
  27125. };
  27126. }
  27127. this.view.enabled = true;
  27128. this.view.fullWidth = fullWidth;
  27129. this.view.fullHeight = fullHeight;
  27130. this.view.offsetX = x;
  27131. this.view.offsetY = y;
  27132. this.view.width = width;
  27133. this.view.height = height;
  27134. this.updateProjectionMatrix();
  27135. },
  27136. clearViewOffset: function () {
  27137. if ( this.view !== null ) {
  27138. this.view.enabled = false;
  27139. }
  27140. this.updateProjectionMatrix();
  27141. },
  27142. updateProjectionMatrix: function () {
  27143. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  27144. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  27145. var cx = ( this.right + this.left ) / 2;
  27146. var cy = ( this.top + this.bottom ) / 2;
  27147. var left = cx - dx;
  27148. var right = cx + dx;
  27149. var top = cy + dy;
  27150. var bottom = cy - dy;
  27151. if ( this.view !== null && this.view.enabled ) {
  27152. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  27153. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  27154. var scaleW = ( this.right - this.left ) / this.view.width;
  27155. var scaleH = ( this.top - this.bottom ) / this.view.height;
  27156. left += scaleW * ( this.view.offsetX / zoomW );
  27157. right = left + scaleW * ( this.view.width / zoomW );
  27158. top -= scaleH * ( this.view.offsetY / zoomH );
  27159. bottom = top - scaleH * ( this.view.height / zoomH );
  27160. }
  27161. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  27162. this.projectionMatrixInverse.getInverse( this.projectionMatrix );
  27163. },
  27164. toJSON: function ( meta ) {
  27165. var data = Object3D.prototype.toJSON.call( this, meta );
  27166. data.object.zoom = this.zoom;
  27167. data.object.left = this.left;
  27168. data.object.right = this.right;
  27169. data.object.top = this.top;
  27170. data.object.bottom = this.bottom;
  27171. data.object.near = this.near;
  27172. data.object.far = this.far;
  27173. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  27174. return data;
  27175. }
  27176. } );
  27177. /**
  27178. * @author mrdoob / http://mrdoob.com/
  27179. */
  27180. function DirectionalLightShadow( ) {
  27181. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  27182. }
  27183. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  27184. constructor: DirectionalLightShadow
  27185. } );
  27186. /**
  27187. * @author mrdoob / http://mrdoob.com/
  27188. * @author alteredq / http://alteredqualia.com/
  27189. */
  27190. function DirectionalLight( color, intensity ) {
  27191. Light.call( this, color, intensity );
  27192. this.type = 'DirectionalLight';
  27193. this.position.copy( Object3D.DefaultUp );
  27194. this.updateMatrix();
  27195. this.target = new Object3D();
  27196. this.shadow = new DirectionalLightShadow();
  27197. }
  27198. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27199. constructor: DirectionalLight,
  27200. isDirectionalLight: true,
  27201. copy: function ( source ) {
  27202. Light.prototype.copy.call( this, source );
  27203. this.target = source.target.clone();
  27204. this.shadow = source.shadow.clone();
  27205. return this;
  27206. }
  27207. } );
  27208. /**
  27209. * @author mrdoob / http://mrdoob.com/
  27210. */
  27211. function AmbientLight( color, intensity ) {
  27212. Light.call( this, color, intensity );
  27213. this.type = 'AmbientLight';
  27214. this.castShadow = undefined;
  27215. }
  27216. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27217. constructor: AmbientLight,
  27218. isAmbientLight: true
  27219. } );
  27220. /**
  27221. * @author abelnation / http://github.com/abelnation
  27222. */
  27223. function RectAreaLight( color, intensity, width, height ) {
  27224. Light.call( this, color, intensity );
  27225. this.type = 'RectAreaLight';
  27226. this.width = ( width !== undefined ) ? width : 10;
  27227. this.height = ( height !== undefined ) ? height : 10;
  27228. }
  27229. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  27230. constructor: RectAreaLight,
  27231. isRectAreaLight: true,
  27232. copy: function ( source ) {
  27233. Light.prototype.copy.call( this, source );
  27234. this.width = source.width;
  27235. this.height = source.height;
  27236. return this;
  27237. },
  27238. toJSON: function ( meta ) {
  27239. var data = Light.prototype.toJSON.call( this, meta );
  27240. data.object.width = this.width;
  27241. data.object.height = this.height;
  27242. return data;
  27243. }
  27244. } );
  27245. /**
  27246. * @author mrdoob / http://mrdoob.com/
  27247. */
  27248. function MaterialLoader( manager ) {
  27249. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27250. this.textures = {};
  27251. }
  27252. Object.assign( MaterialLoader.prototype, {
  27253. load: function ( url, onLoad, onProgress, onError ) {
  27254. var scope = this;
  27255. var loader = new FileLoader( scope.manager );
  27256. loader.setPath( scope.path );
  27257. loader.load( url, function ( text ) {
  27258. onLoad( scope.parse( JSON.parse( text ) ) );
  27259. }, onProgress, onError );
  27260. },
  27261. parse: function ( json ) {
  27262. var textures = this.textures;
  27263. function getTexture( name ) {
  27264. if ( textures[ name ] === undefined ) {
  27265. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  27266. }
  27267. return textures[ name ];
  27268. }
  27269. var material = new Materials[ json.type ]();
  27270. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  27271. if ( json.name !== undefined ) material.name = json.name;
  27272. if ( json.color !== undefined ) material.color.setHex( json.color );
  27273. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  27274. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  27275. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  27276. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  27277. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  27278. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  27279. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  27280. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  27281. if ( json.fog !== undefined ) material.fog = json.fog;
  27282. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  27283. if ( json.blending !== undefined ) material.blending = json.blending;
  27284. if ( json.combine !== undefined ) material.combine = json.combine;
  27285. if ( json.side !== undefined ) material.side = json.side;
  27286. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  27287. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  27288. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  27289. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  27290. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  27291. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  27292. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  27293. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  27294. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  27295. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  27296. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  27297. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  27298. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  27299. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  27300. if ( json.scale !== undefined ) material.scale = json.scale;
  27301. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  27302. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  27303. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  27304. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  27305. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  27306. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  27307. if ( json.visible !== undefined ) material.visible = json.visible;
  27308. if ( json.userData !== undefined ) material.userData = json.userData;
  27309. // Shader Material
  27310. if ( json.uniforms !== undefined ) {
  27311. for ( var name in json.uniforms ) {
  27312. var uniform = json.uniforms[ name ];
  27313. material.uniforms[ name ] = {};
  27314. switch ( uniform.type ) {
  27315. case 't':
  27316. material.uniforms[ name ].value = getTexture( uniform.value );
  27317. break;
  27318. case 'c':
  27319. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  27320. break;
  27321. case 'v2':
  27322. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27323. break;
  27324. case 'v3':
  27325. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27326. break;
  27327. case 'v4':
  27328. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27329. break;
  27330. case 'm3':
  27331. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27332. case 'm4':
  27333. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27334. break;
  27335. default:
  27336. material.uniforms[ name ].value = uniform.value;
  27337. }
  27338. }
  27339. }
  27340. if ( json.defines !== undefined ) material.defines = json.defines;
  27341. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  27342. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  27343. if ( json.extensions !== undefined ) {
  27344. for ( var key in json.extensions ) {
  27345. material.extensions[ key ] = json.extensions[ key ];
  27346. }
  27347. }
  27348. // Deprecated
  27349. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  27350. // for PointsMaterial
  27351. if ( json.size !== undefined ) material.size = json.size;
  27352. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  27353. // maps
  27354. if ( json.map !== undefined ) material.map = getTexture( json.map );
  27355. if ( json.alphaMap !== undefined ) {
  27356. material.alphaMap = getTexture( json.alphaMap );
  27357. material.transparent = true;
  27358. }
  27359. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  27360. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  27361. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  27362. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  27363. if ( json.normalScale !== undefined ) {
  27364. var normalScale = json.normalScale;
  27365. if ( Array.isArray( normalScale ) === false ) {
  27366. // Blender exporter used to export a scalar. See #7459
  27367. normalScale = [ normalScale, normalScale ];
  27368. }
  27369. material.normalScale = new Vector2().fromArray( normalScale );
  27370. }
  27371. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  27372. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  27373. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  27374. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  27375. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  27376. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  27377. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  27378. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  27379. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  27380. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  27381. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  27382. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  27383. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  27384. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  27385. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  27386. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  27387. return material;
  27388. },
  27389. setPath: function ( value ) {
  27390. this.path = value;
  27391. return this;
  27392. },
  27393. setTextures: function ( value ) {
  27394. this.textures = value;
  27395. return this;
  27396. }
  27397. } );
  27398. /**
  27399. * @author Don McCurdy / https://www.donmccurdy.com
  27400. */
  27401. var LoaderUtils = {
  27402. decodeText: function ( array ) {
  27403. if ( typeof TextDecoder !== 'undefined' ) {
  27404. return new TextDecoder().decode( array );
  27405. }
  27406. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  27407. // throws a "maximum call stack size exceeded" error for large arrays.
  27408. var s = '';
  27409. for ( var i = 0, il = array.length; i < il; i ++ ) {
  27410. // Implicitly assumes little-endian.
  27411. s += String.fromCharCode( array[ i ] );
  27412. }
  27413. // Merges multi-byte utf-8 characters.
  27414. return decodeURIComponent( escape( s ) );
  27415. },
  27416. extractUrlBase: function ( url ) {
  27417. var index = url.lastIndexOf( '/' );
  27418. if ( index === - 1 ) return './';
  27419. return url.substr( 0, index + 1 );
  27420. }
  27421. };
  27422. /**
  27423. * @author mrdoob / http://mrdoob.com/
  27424. */
  27425. function BufferGeometryLoader( manager ) {
  27426. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27427. }
  27428. Object.assign( BufferGeometryLoader.prototype, {
  27429. load: function ( url, onLoad, onProgress, onError ) {
  27430. var scope = this;
  27431. var loader = new FileLoader( scope.manager );
  27432. loader.setPath( scope.path );
  27433. loader.load( url, function ( text ) {
  27434. onLoad( scope.parse( JSON.parse( text ) ) );
  27435. }, onProgress, onError );
  27436. },
  27437. parse: function ( json ) {
  27438. var geometry = new BufferGeometry();
  27439. var index = json.data.index;
  27440. if ( index !== undefined ) {
  27441. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  27442. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27443. }
  27444. var attributes = json.data.attributes;
  27445. for ( var key in attributes ) {
  27446. var attribute = attributes[ key ];
  27447. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  27448. var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27449. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27450. geometry.addAttribute( key, bufferAttribute );
  27451. }
  27452. var morphAttributes = json.data.morphAttributes;
  27453. if ( morphAttributes ) {
  27454. for ( var key in morphAttributes ) {
  27455. var attributeArray = morphAttributes[ key ];
  27456. var array = [];
  27457. for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {
  27458. var attribute = attributeArray[ i ];
  27459. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  27460. var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27461. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27462. array.push( bufferAttribute );
  27463. }
  27464. geometry.morphAttributes[ key ] = array;
  27465. }
  27466. }
  27467. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27468. if ( groups !== undefined ) {
  27469. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  27470. var group = groups[ i ];
  27471. geometry.addGroup( group.start, group.count, group.materialIndex );
  27472. }
  27473. }
  27474. var boundingSphere = json.data.boundingSphere;
  27475. if ( boundingSphere !== undefined ) {
  27476. var center = new Vector3();
  27477. if ( boundingSphere.center !== undefined ) {
  27478. center.fromArray( boundingSphere.center );
  27479. }
  27480. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27481. }
  27482. if ( json.name ) geometry.name = json.name;
  27483. if ( json.userData ) geometry.userData = json.userData;
  27484. return geometry;
  27485. },
  27486. setPath: function ( value ) {
  27487. this.path = value;
  27488. return this;
  27489. }
  27490. } );
  27491. var TYPED_ARRAYS = {
  27492. Int8Array: Int8Array,
  27493. Uint8Array: Uint8Array,
  27494. // Workaround for IE11 pre KB2929437. See #11440
  27495. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  27496. Int16Array: Int16Array,
  27497. Uint16Array: Uint16Array,
  27498. Int32Array: Int32Array,
  27499. Uint32Array: Uint32Array,
  27500. Float32Array: Float32Array,
  27501. Float64Array: Float64Array
  27502. };
  27503. /**
  27504. * @author mrdoob / http://mrdoob.com/
  27505. */
  27506. function ObjectLoader( manager ) {
  27507. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27508. this.resourcePath = '';
  27509. }
  27510. Object.assign( ObjectLoader.prototype, {
  27511. crossOrigin: 'anonymous',
  27512. load: function ( url, onLoad, onProgress, onError ) {
  27513. var scope = this;
  27514. var path = ( this.path === undefined ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27515. this.resourcePath = this.resourcePath || path;
  27516. var loader = new FileLoader( scope.manager );
  27517. loader.setPath( this.path );
  27518. loader.load( url, function ( text ) {
  27519. var json = null;
  27520. try {
  27521. json = JSON.parse( text );
  27522. } catch ( error ) {
  27523. if ( onError !== undefined ) onError( error );
  27524. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27525. return;
  27526. }
  27527. var metadata = json.metadata;
  27528. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27529. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27530. return;
  27531. }
  27532. scope.parse( json, onLoad );
  27533. }, onProgress, onError );
  27534. },
  27535. setPath: function ( value ) {
  27536. this.path = value;
  27537. return this;
  27538. },
  27539. setResourcePath: function ( value ) {
  27540. this.resourcePath = value;
  27541. return this;
  27542. },
  27543. setCrossOrigin: function ( value ) {
  27544. this.crossOrigin = value;
  27545. return this;
  27546. },
  27547. parse: function ( json, onLoad ) {
  27548. var shapes = this.parseShape( json.shapes );
  27549. var geometries = this.parseGeometries( json.geometries, shapes );
  27550. var images = this.parseImages( json.images, function () {
  27551. if ( onLoad !== undefined ) onLoad( object );
  27552. } );
  27553. var textures = this.parseTextures( json.textures, images );
  27554. var materials = this.parseMaterials( json.materials, textures );
  27555. var object = this.parseObject( json.object, geometries, materials );
  27556. if ( json.animations ) {
  27557. object.animations = this.parseAnimations( json.animations );
  27558. }
  27559. if ( json.images === undefined || json.images.length === 0 ) {
  27560. if ( onLoad !== undefined ) onLoad( object );
  27561. }
  27562. return object;
  27563. },
  27564. parseShape: function ( json ) {
  27565. var shapes = {};
  27566. if ( json !== undefined ) {
  27567. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27568. var shape = new Shape().fromJSON( json[ i ] );
  27569. shapes[ shape.uuid ] = shape;
  27570. }
  27571. }
  27572. return shapes;
  27573. },
  27574. parseGeometries: function ( json, shapes ) {
  27575. var geometries = {};
  27576. if ( json !== undefined ) {
  27577. var bufferGeometryLoader = new BufferGeometryLoader();
  27578. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27579. var geometry;
  27580. var data = json[ i ];
  27581. switch ( data.type ) {
  27582. case 'PlaneGeometry':
  27583. case 'PlaneBufferGeometry':
  27584. geometry = new Geometries[ data.type ](
  27585. data.width,
  27586. data.height,
  27587. data.widthSegments,
  27588. data.heightSegments
  27589. );
  27590. break;
  27591. case 'BoxGeometry':
  27592. case 'BoxBufferGeometry':
  27593. case 'CubeGeometry': // backwards compatible
  27594. geometry = new Geometries[ data.type ](
  27595. data.width,
  27596. data.height,
  27597. data.depth,
  27598. data.widthSegments,
  27599. data.heightSegments,
  27600. data.depthSegments
  27601. );
  27602. break;
  27603. case 'CircleGeometry':
  27604. case 'CircleBufferGeometry':
  27605. geometry = new Geometries[ data.type ](
  27606. data.radius,
  27607. data.segments,
  27608. data.thetaStart,
  27609. data.thetaLength
  27610. );
  27611. break;
  27612. case 'CylinderGeometry':
  27613. case 'CylinderBufferGeometry':
  27614. geometry = new Geometries[ data.type ](
  27615. data.radiusTop,
  27616. data.radiusBottom,
  27617. data.height,
  27618. data.radialSegments,
  27619. data.heightSegments,
  27620. data.openEnded,
  27621. data.thetaStart,
  27622. data.thetaLength
  27623. );
  27624. break;
  27625. case 'ConeGeometry':
  27626. case 'ConeBufferGeometry':
  27627. geometry = new Geometries[ data.type ](
  27628. data.radius,
  27629. data.height,
  27630. data.radialSegments,
  27631. data.heightSegments,
  27632. data.openEnded,
  27633. data.thetaStart,
  27634. data.thetaLength
  27635. );
  27636. break;
  27637. case 'SphereGeometry':
  27638. case 'SphereBufferGeometry':
  27639. geometry = new Geometries[ data.type ](
  27640. data.radius,
  27641. data.widthSegments,
  27642. data.heightSegments,
  27643. data.phiStart,
  27644. data.phiLength,
  27645. data.thetaStart,
  27646. data.thetaLength
  27647. );
  27648. break;
  27649. case 'DodecahedronGeometry':
  27650. case 'DodecahedronBufferGeometry':
  27651. case 'IcosahedronGeometry':
  27652. case 'IcosahedronBufferGeometry':
  27653. case 'OctahedronGeometry':
  27654. case 'OctahedronBufferGeometry':
  27655. case 'TetrahedronGeometry':
  27656. case 'TetrahedronBufferGeometry':
  27657. geometry = new Geometries[ data.type ](
  27658. data.radius,
  27659. data.detail
  27660. );
  27661. break;
  27662. case 'RingGeometry':
  27663. case 'RingBufferGeometry':
  27664. geometry = new Geometries[ data.type ](
  27665. data.innerRadius,
  27666. data.outerRadius,
  27667. data.thetaSegments,
  27668. data.phiSegments,
  27669. data.thetaStart,
  27670. data.thetaLength
  27671. );
  27672. break;
  27673. case 'TorusGeometry':
  27674. case 'TorusBufferGeometry':
  27675. geometry = new Geometries[ data.type ](
  27676. data.radius,
  27677. data.tube,
  27678. data.radialSegments,
  27679. data.tubularSegments,
  27680. data.arc
  27681. );
  27682. break;
  27683. case 'TorusKnotGeometry':
  27684. case 'TorusKnotBufferGeometry':
  27685. geometry = new Geometries[ data.type ](
  27686. data.radius,
  27687. data.tube,
  27688. data.tubularSegments,
  27689. data.radialSegments,
  27690. data.p,
  27691. data.q
  27692. );
  27693. break;
  27694. case 'TubeGeometry':
  27695. case 'TubeBufferGeometry':
  27696. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27697. // User defined curves or instances of CurvePath will not be deserialized.
  27698. geometry = new Geometries[ data.type ](
  27699. new Curves[ data.path.type ]().fromJSON( data.path ),
  27700. data.tubularSegments,
  27701. data.radius,
  27702. data.radialSegments,
  27703. data.closed
  27704. );
  27705. break;
  27706. case 'LatheGeometry':
  27707. case 'LatheBufferGeometry':
  27708. geometry = new Geometries[ data.type ](
  27709. data.points,
  27710. data.segments,
  27711. data.phiStart,
  27712. data.phiLength
  27713. );
  27714. break;
  27715. case 'PolyhedronGeometry':
  27716. case 'PolyhedronBufferGeometry':
  27717. geometry = new Geometries[ data.type ](
  27718. data.vertices,
  27719. data.indices,
  27720. data.radius,
  27721. data.details
  27722. );
  27723. break;
  27724. case 'ShapeGeometry':
  27725. case 'ShapeBufferGeometry':
  27726. var geometryShapes = [];
  27727. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27728. var shape = shapes[ data.shapes[ j ] ];
  27729. geometryShapes.push( shape );
  27730. }
  27731. geometry = new Geometries[ data.type ](
  27732. geometryShapes,
  27733. data.curveSegments
  27734. );
  27735. break;
  27736. case 'ExtrudeGeometry':
  27737. case 'ExtrudeBufferGeometry':
  27738. var geometryShapes = [];
  27739. for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27740. var shape = shapes[ data.shapes[ j ] ];
  27741. geometryShapes.push( shape );
  27742. }
  27743. var extrudePath = data.options.extrudePath;
  27744. if ( extrudePath !== undefined ) {
  27745. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  27746. }
  27747. geometry = new Geometries[ data.type ](
  27748. geometryShapes,
  27749. data.options
  27750. );
  27751. break;
  27752. case 'BufferGeometry':
  27753. geometry = bufferGeometryLoader.parse( data );
  27754. break;
  27755. case 'Geometry':
  27756. if ( 'THREE' in window && 'LegacyJSONLoader' in THREE ) {
  27757. var geometryLoader = new THREE.LegacyJSONLoader();
  27758. geometry = geometryLoader.parse( data, this.resourcePath ).geometry;
  27759. } else {
  27760. console.error( 'THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".' );
  27761. }
  27762. break;
  27763. default:
  27764. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  27765. continue;
  27766. }
  27767. geometry.uuid = data.uuid;
  27768. if ( data.name !== undefined ) geometry.name = data.name;
  27769. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  27770. geometries[ data.uuid ] = geometry;
  27771. }
  27772. }
  27773. return geometries;
  27774. },
  27775. parseMaterials: function ( json, textures ) {
  27776. var cache = {}; // MultiMaterial
  27777. var materials = {};
  27778. if ( json !== undefined ) {
  27779. var loader = new MaterialLoader();
  27780. loader.setTextures( textures );
  27781. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27782. var data = json[ i ];
  27783. if ( data.type === 'MultiMaterial' ) {
  27784. // Deprecated
  27785. var array = [];
  27786. for ( var j = 0; j < data.materials.length; j ++ ) {
  27787. var material = data.materials[ j ];
  27788. if ( cache[ material.uuid ] === undefined ) {
  27789. cache[ material.uuid ] = loader.parse( material );
  27790. }
  27791. array.push( cache[ material.uuid ] );
  27792. }
  27793. materials[ data.uuid ] = array;
  27794. } else {
  27795. if ( cache[ data.uuid ] === undefined ) {
  27796. cache[ data.uuid ] = loader.parse( data );
  27797. }
  27798. materials[ data.uuid ] = cache[ data.uuid ];
  27799. }
  27800. }
  27801. }
  27802. return materials;
  27803. },
  27804. parseAnimations: function ( json ) {
  27805. var animations = [];
  27806. for ( var i = 0; i < json.length; i ++ ) {
  27807. var data = json[ i ];
  27808. var clip = AnimationClip.parse( data );
  27809. if ( data.uuid !== undefined ) clip.uuid = data.uuid;
  27810. animations.push( clip );
  27811. }
  27812. return animations;
  27813. },
  27814. parseImages: function ( json, onLoad ) {
  27815. var scope = this;
  27816. var images = {};
  27817. function loadImage( url ) {
  27818. scope.manager.itemStart( url );
  27819. return loader.load( url, function () {
  27820. scope.manager.itemEnd( url );
  27821. }, undefined, function () {
  27822. scope.manager.itemError( url );
  27823. scope.manager.itemEnd( url );
  27824. } );
  27825. }
  27826. if ( json !== undefined && json.length > 0 ) {
  27827. var manager = new LoadingManager( onLoad );
  27828. var loader = new ImageLoader( manager );
  27829. loader.setCrossOrigin( this.crossOrigin );
  27830. for ( var i = 0, il = json.length; i < il; i ++ ) {
  27831. var image = json[ i ];
  27832. var url = image.url;
  27833. if ( Array.isArray( url ) ) {
  27834. // load array of images e.g CubeTexture
  27835. images[ image.uuid ] = [];
  27836. for ( var j = 0, jl = url.length; j < jl; j ++ ) {
  27837. var currentUrl = url[ j ];
  27838. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;
  27839. images[ image.uuid ].push( loadImage( path ) );
  27840. }
  27841. } else {
  27842. // load single image
  27843. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;
  27844. images[ image.uuid ] = loadImage( path );
  27845. }
  27846. }
  27847. }
  27848. return images;
  27849. },
  27850. parseTextures: function ( json, images ) {
  27851. function parseConstant( value, type ) {
  27852. if ( typeof value === 'number' ) return value;
  27853. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27854. return type[ value ];
  27855. }
  27856. var textures = {};
  27857. if ( json !== undefined ) {
  27858. for ( var i = 0, l = json.length; i < l; i ++ ) {
  27859. var data = json[ i ];
  27860. if ( data.image === undefined ) {
  27861. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27862. }
  27863. if ( images[ data.image ] === undefined ) {
  27864. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27865. }
  27866. var texture;
  27867. if ( Array.isArray( images[ data.image ] ) ) {
  27868. texture = new CubeTexture( images[ data.image ] );
  27869. } else {
  27870. texture = new Texture( images[ data.image ] );
  27871. }
  27872. texture.needsUpdate = true;
  27873. texture.uuid = data.uuid;
  27874. if ( data.name !== undefined ) texture.name = data.name;
  27875. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27876. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27877. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27878. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27879. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27880. if ( data.wrap !== undefined ) {
  27881. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27882. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27883. }
  27884. if ( data.format !== undefined ) texture.format = data.format;
  27885. if ( data.type !== undefined ) texture.type = data.type;
  27886. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  27887. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27888. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27889. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27890. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27891. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27892. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27893. textures[ data.uuid ] = texture;
  27894. }
  27895. }
  27896. return textures;
  27897. },
  27898. parseObject: function ( data, geometries, materials ) {
  27899. var object;
  27900. function getGeometry( name ) {
  27901. if ( geometries[ name ] === undefined ) {
  27902. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27903. }
  27904. return geometries[ name ];
  27905. }
  27906. function getMaterial( name ) {
  27907. if ( name === undefined ) return undefined;
  27908. if ( Array.isArray( name ) ) {
  27909. var array = [];
  27910. for ( var i = 0, l = name.length; i < l; i ++ ) {
  27911. var uuid = name[ i ];
  27912. if ( materials[ uuid ] === undefined ) {
  27913. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27914. }
  27915. array.push( materials[ uuid ] );
  27916. }
  27917. return array;
  27918. }
  27919. if ( materials[ name ] === undefined ) {
  27920. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27921. }
  27922. return materials[ name ];
  27923. }
  27924. switch ( data.type ) {
  27925. case 'Scene':
  27926. object = new Scene();
  27927. if ( data.background !== undefined ) {
  27928. if ( Number.isInteger( data.background ) ) {
  27929. object.background = new Color( data.background );
  27930. }
  27931. }
  27932. if ( data.fog !== undefined ) {
  27933. if ( data.fog.type === 'Fog' ) {
  27934. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27935. } else if ( data.fog.type === 'FogExp2' ) {
  27936. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27937. }
  27938. }
  27939. break;
  27940. case 'PerspectiveCamera':
  27941. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27942. if ( data.focus !== undefined ) object.focus = data.focus;
  27943. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27944. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27945. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27946. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27947. break;
  27948. case 'OrthographicCamera':
  27949. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27950. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27951. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27952. break;
  27953. case 'AmbientLight':
  27954. object = new AmbientLight( data.color, data.intensity );
  27955. break;
  27956. case 'DirectionalLight':
  27957. object = new DirectionalLight( data.color, data.intensity );
  27958. break;
  27959. case 'PointLight':
  27960. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27961. break;
  27962. case 'RectAreaLight':
  27963. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27964. break;
  27965. case 'SpotLight':
  27966. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27967. break;
  27968. case 'HemisphereLight':
  27969. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27970. break;
  27971. case 'SkinnedMesh':
  27972. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  27973. case 'Mesh':
  27974. var geometry = getGeometry( data.geometry );
  27975. var material = getMaterial( data.material );
  27976. if ( geometry.bones && geometry.bones.length > 0 ) {
  27977. object = new SkinnedMesh( geometry, material );
  27978. } else {
  27979. object = new Mesh( geometry, material );
  27980. }
  27981. if ( data.drawMode !== undefined ) object.setDrawMode( data.drawMode );
  27982. break;
  27983. case 'LOD':
  27984. object = new LOD();
  27985. break;
  27986. case 'Line':
  27987. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  27988. break;
  27989. case 'LineLoop':
  27990. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27991. break;
  27992. case 'LineSegments':
  27993. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27994. break;
  27995. case 'PointCloud':
  27996. case 'Points':
  27997. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27998. break;
  27999. case 'Sprite':
  28000. object = new Sprite( getMaterial( data.material ) );
  28001. break;
  28002. case 'Group':
  28003. object = new Group();
  28004. break;
  28005. default:
  28006. object = new Object3D();
  28007. }
  28008. object.uuid = data.uuid;
  28009. if ( data.name !== undefined ) object.name = data.name;
  28010. if ( data.matrix !== undefined ) {
  28011. object.matrix.fromArray( data.matrix );
  28012. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  28013. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  28014. } else {
  28015. if ( data.position !== undefined ) object.position.fromArray( data.position );
  28016. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  28017. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  28018. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  28019. }
  28020. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  28021. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  28022. if ( data.shadow ) {
  28023. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  28024. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  28025. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  28026. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  28027. }
  28028. if ( data.visible !== undefined ) object.visible = data.visible;
  28029. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  28030. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  28031. if ( data.userData !== undefined ) object.userData = data.userData;
  28032. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  28033. if ( data.children !== undefined ) {
  28034. var children = data.children;
  28035. for ( var i = 0; i < children.length; i ++ ) {
  28036. object.add( this.parseObject( children[ i ], geometries, materials ) );
  28037. }
  28038. }
  28039. if ( data.type === 'LOD' ) {
  28040. var levels = data.levels;
  28041. for ( var l = 0; l < levels.length; l ++ ) {
  28042. var level = levels[ l ];
  28043. var child = object.getObjectByProperty( 'uuid', level.object );
  28044. if ( child !== undefined ) {
  28045. object.addLevel( child, level.distance );
  28046. }
  28047. }
  28048. }
  28049. return object;
  28050. }
  28051. } );
  28052. var TEXTURE_MAPPING = {
  28053. UVMapping: UVMapping,
  28054. CubeReflectionMapping: CubeReflectionMapping,
  28055. CubeRefractionMapping: CubeRefractionMapping,
  28056. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  28057. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  28058. SphericalReflectionMapping: SphericalReflectionMapping,
  28059. CubeUVReflectionMapping: CubeUVReflectionMapping,
  28060. CubeUVRefractionMapping: CubeUVRefractionMapping
  28061. };
  28062. var TEXTURE_WRAPPING = {
  28063. RepeatWrapping: RepeatWrapping,
  28064. ClampToEdgeWrapping: ClampToEdgeWrapping,
  28065. MirroredRepeatWrapping: MirroredRepeatWrapping
  28066. };
  28067. var TEXTURE_FILTER = {
  28068. NearestFilter: NearestFilter,
  28069. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  28070. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  28071. LinearFilter: LinearFilter,
  28072. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  28073. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  28074. };
  28075. /**
  28076. * @author thespite / http://clicktorelease.com/
  28077. */
  28078. function ImageBitmapLoader( manager ) {
  28079. if ( typeof createImageBitmap === 'undefined' ) {
  28080. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  28081. }
  28082. if ( typeof fetch === 'undefined' ) {
  28083. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  28084. }
  28085. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  28086. this.options = undefined;
  28087. }
  28088. ImageBitmapLoader.prototype = {
  28089. constructor: ImageBitmapLoader,
  28090. setOptions: function setOptions( options ) {
  28091. this.options = options;
  28092. return this;
  28093. },
  28094. load: function ( url, onLoad, onProgress, onError ) {
  28095. if ( url === undefined ) url = '';
  28096. if ( this.path !== undefined ) url = this.path + url;
  28097. url = this.manager.resolveURL( url );
  28098. var scope = this;
  28099. var cached = Cache.get( url );
  28100. if ( cached !== undefined ) {
  28101. scope.manager.itemStart( url );
  28102. setTimeout( function () {
  28103. if ( onLoad ) onLoad( cached );
  28104. scope.manager.itemEnd( url );
  28105. }, 0 );
  28106. return cached;
  28107. }
  28108. fetch( url ).then( function ( res ) {
  28109. return res.blob();
  28110. } ).then( function ( blob ) {
  28111. if ( scope.options === undefined ) {
  28112. // Workaround for FireFox. It causes an error if you pass options.
  28113. return createImageBitmap( blob );
  28114. } else {
  28115. return createImageBitmap( blob, scope.options );
  28116. }
  28117. } ).then( function ( imageBitmap ) {
  28118. Cache.add( url, imageBitmap );
  28119. if ( onLoad ) onLoad( imageBitmap );
  28120. scope.manager.itemEnd( url );
  28121. } ).catch( function ( e ) {
  28122. if ( onError ) onError( e );
  28123. scope.manager.itemError( url );
  28124. scope.manager.itemEnd( url );
  28125. } );
  28126. scope.manager.itemStart( url );
  28127. },
  28128. setCrossOrigin: function ( /* value */ ) {
  28129. return this;
  28130. },
  28131. setPath: function ( value ) {
  28132. this.path = value;
  28133. return this;
  28134. }
  28135. };
  28136. /**
  28137. * @author zz85 / http://www.lab4games.net/zz85/blog
  28138. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  28139. **/
  28140. function ShapePath() {
  28141. this.type = 'ShapePath';
  28142. this.color = new Color();
  28143. this.subPaths = [];
  28144. this.currentPath = null;
  28145. }
  28146. Object.assign( ShapePath.prototype, {
  28147. moveTo: function ( x, y ) {
  28148. this.currentPath = new Path();
  28149. this.subPaths.push( this.currentPath );
  28150. this.currentPath.moveTo( x, y );
  28151. },
  28152. lineTo: function ( x, y ) {
  28153. this.currentPath.lineTo( x, y );
  28154. },
  28155. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  28156. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28157. },
  28158. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28159. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28160. },
  28161. splineThru: function ( pts ) {
  28162. this.currentPath.splineThru( pts );
  28163. },
  28164. toShapes: function ( isCCW, noHoles ) {
  28165. function toShapesNoHoles( inSubpaths ) {
  28166. var shapes = [];
  28167. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28168. var tmpPath = inSubpaths[ i ];
  28169. var tmpShape = new Shape();
  28170. tmpShape.curves = tmpPath.curves;
  28171. shapes.push( tmpShape );
  28172. }
  28173. return shapes;
  28174. }
  28175. function isPointInsidePolygon( inPt, inPolygon ) {
  28176. var polyLen = inPolygon.length;
  28177. // inPt on polygon contour => immediate success or
  28178. // toggling of inside/outside at every single! intersection point of an edge
  28179. // with the horizontal line through inPt, left of inPt
  28180. // not counting lowerY endpoints of edges and whole edges on that line
  28181. var inside = false;
  28182. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28183. var edgeLowPt = inPolygon[ p ];
  28184. var edgeHighPt = inPolygon[ q ];
  28185. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  28186. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  28187. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28188. // not parallel
  28189. if ( edgeDy < 0 ) {
  28190. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28191. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28192. }
  28193. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28194. if ( inPt.y === edgeLowPt.y ) {
  28195. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28196. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28197. } else {
  28198. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28199. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28200. if ( perpEdge < 0 ) continue;
  28201. inside = ! inside; // true intersection left of inPt
  28202. }
  28203. } else {
  28204. // parallel or collinear
  28205. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28206. // edge lies on the same horizontal line as inPt
  28207. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28208. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28209. // continue;
  28210. }
  28211. }
  28212. return inside;
  28213. }
  28214. var isClockWise = ShapeUtils.isClockWise;
  28215. var subPaths = this.subPaths;
  28216. if ( subPaths.length === 0 ) return [];
  28217. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28218. var solid, tmpPath, tmpShape, shapes = [];
  28219. if ( subPaths.length === 1 ) {
  28220. tmpPath = subPaths[ 0 ];
  28221. tmpShape = new Shape();
  28222. tmpShape.curves = tmpPath.curves;
  28223. shapes.push( tmpShape );
  28224. return shapes;
  28225. }
  28226. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28227. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28228. // console.log("Holes first", holesFirst);
  28229. var betterShapeHoles = [];
  28230. var newShapes = [];
  28231. var newShapeHoles = [];
  28232. var mainIdx = 0;
  28233. var tmpPoints;
  28234. newShapes[ mainIdx ] = undefined;
  28235. newShapeHoles[ mainIdx ] = [];
  28236. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  28237. tmpPath = subPaths[ i ];
  28238. tmpPoints = tmpPath.getPoints();
  28239. solid = isClockWise( tmpPoints );
  28240. solid = isCCW ? ! solid : solid;
  28241. if ( solid ) {
  28242. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28243. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28244. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28245. if ( holesFirst ) mainIdx ++;
  28246. newShapeHoles[ mainIdx ] = [];
  28247. //console.log('cw', i);
  28248. } else {
  28249. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28250. //console.log('ccw', i);
  28251. }
  28252. }
  28253. // only Holes? -> probably all Shapes with wrong orientation
  28254. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28255. if ( newShapes.length > 1 ) {
  28256. var ambiguous = false;
  28257. var toChange = [];
  28258. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28259. betterShapeHoles[ sIdx ] = [];
  28260. }
  28261. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28262. var sho = newShapeHoles[ sIdx ];
  28263. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28264. var ho = sho[ hIdx ];
  28265. var hole_unassigned = true;
  28266. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28267. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28268. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  28269. if ( hole_unassigned ) {
  28270. hole_unassigned = false;
  28271. betterShapeHoles[ s2Idx ].push( ho );
  28272. } else {
  28273. ambiguous = true;
  28274. }
  28275. }
  28276. }
  28277. if ( hole_unassigned ) {
  28278. betterShapeHoles[ sIdx ].push( ho );
  28279. }
  28280. }
  28281. }
  28282. // console.log("ambiguous: ", ambiguous);
  28283. if ( toChange.length > 0 ) {
  28284. // console.log("to change: ", toChange);
  28285. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  28286. }
  28287. }
  28288. var tmpHoles;
  28289. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  28290. tmpShape = newShapes[ i ].s;
  28291. shapes.push( tmpShape );
  28292. tmpHoles = newShapeHoles[ i ];
  28293. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28294. tmpShape.holes.push( tmpHoles[ j ].h );
  28295. }
  28296. }
  28297. //console.log("shape", shapes);
  28298. return shapes;
  28299. }
  28300. } );
  28301. /**
  28302. * @author zz85 / http://www.lab4games.net/zz85/blog
  28303. * @author mrdoob / http://mrdoob.com/
  28304. */
  28305. function Font( data ) {
  28306. this.type = 'Font';
  28307. this.data = data;
  28308. }
  28309. Object.assign( Font.prototype, {
  28310. isFont: true,
  28311. generateShapes: function ( text, size ) {
  28312. if ( size === undefined ) size = 100;
  28313. var shapes = [];
  28314. var paths = createPaths( text, size, this.data );
  28315. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  28316. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  28317. }
  28318. return shapes;
  28319. }
  28320. } );
  28321. function createPaths( text, size, data ) {
  28322. var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // see #13988
  28323. var scale = size / data.resolution;
  28324. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  28325. var paths = [];
  28326. var offsetX = 0, offsetY = 0;
  28327. for ( var i = 0; i < chars.length; i ++ ) {
  28328. var char = chars[ i ];
  28329. if ( char === '\n' ) {
  28330. offsetX = 0;
  28331. offsetY -= line_height;
  28332. } else {
  28333. var ret = createPath( char, scale, offsetX, offsetY, data );
  28334. offsetX += ret.offsetX;
  28335. paths.push( ret.path );
  28336. }
  28337. }
  28338. return paths;
  28339. }
  28340. function createPath( char, scale, offsetX, offsetY, data ) {
  28341. var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  28342. if ( ! glyph ) return;
  28343. var path = new ShapePath();
  28344. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  28345. if ( glyph.o ) {
  28346. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  28347. for ( var i = 0, l = outline.length; i < l; ) {
  28348. var action = outline[ i ++ ];
  28349. switch ( action ) {
  28350. case 'm': // moveTo
  28351. x = outline[ i ++ ] * scale + offsetX;
  28352. y = outline[ i ++ ] * scale + offsetY;
  28353. path.moveTo( x, y );
  28354. break;
  28355. case 'l': // lineTo
  28356. x = outline[ i ++ ] * scale + offsetX;
  28357. y = outline[ i ++ ] * scale + offsetY;
  28358. path.lineTo( x, y );
  28359. break;
  28360. case 'q': // quadraticCurveTo
  28361. cpx = outline[ i ++ ] * scale + offsetX;
  28362. cpy = outline[ i ++ ] * scale + offsetY;
  28363. cpx1 = outline[ i ++ ] * scale + offsetX;
  28364. cpy1 = outline[ i ++ ] * scale + offsetY;
  28365. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  28366. break;
  28367. case 'b': // bezierCurveTo
  28368. cpx = outline[ i ++ ] * scale + offsetX;
  28369. cpy = outline[ i ++ ] * scale + offsetY;
  28370. cpx1 = outline[ i ++ ] * scale + offsetX;
  28371. cpy1 = outline[ i ++ ] * scale + offsetY;
  28372. cpx2 = outline[ i ++ ] * scale + offsetX;
  28373. cpy2 = outline[ i ++ ] * scale + offsetY;
  28374. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  28375. break;
  28376. }
  28377. }
  28378. }
  28379. return { offsetX: glyph.ha * scale, path: path };
  28380. }
  28381. /**
  28382. * @author mrdoob / http://mrdoob.com/
  28383. */
  28384. function FontLoader( manager ) {
  28385. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  28386. }
  28387. Object.assign( FontLoader.prototype, {
  28388. load: function ( url, onLoad, onProgress, onError ) {
  28389. var scope = this;
  28390. var loader = new FileLoader( this.manager );
  28391. loader.setPath( this.path );
  28392. loader.load( url, function ( text ) {
  28393. var json;
  28394. try {
  28395. json = JSON.parse( text );
  28396. } catch ( e ) {
  28397. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  28398. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  28399. }
  28400. var font = scope.parse( json );
  28401. if ( onLoad ) onLoad( font );
  28402. }, onProgress, onError );
  28403. },
  28404. parse: function ( json ) {
  28405. return new Font( json );
  28406. },
  28407. setPath: function ( value ) {
  28408. this.path = value;
  28409. return this;
  28410. }
  28411. } );
  28412. /**
  28413. * @author alteredq / http://alteredqualia.com/
  28414. */
  28415. function Loader() {}
  28416. Loader.Handlers = {
  28417. handlers: [],
  28418. add: function ( regex, loader ) {
  28419. this.handlers.push( regex, loader );
  28420. },
  28421. get: function ( file ) {
  28422. var handlers = this.handlers;
  28423. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  28424. var regex = handlers[ i ];
  28425. var loader = handlers[ i + 1 ];
  28426. if ( regex.test( file ) ) {
  28427. return loader;
  28428. }
  28429. }
  28430. return null;
  28431. }
  28432. };
  28433. Object.assign( Loader.prototype, {
  28434. crossOrigin: 'anonymous',
  28435. onLoadStart: function () {},
  28436. onLoadProgress: function () {},
  28437. onLoadComplete: function () {},
  28438. initMaterials: function ( materials, texturePath, crossOrigin ) {
  28439. var array = [];
  28440. for ( var i = 0; i < materials.length; ++ i ) {
  28441. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  28442. }
  28443. return array;
  28444. },
  28445. createMaterial: ( function () {
  28446. var BlendingMode = {
  28447. NoBlending: NoBlending,
  28448. NormalBlending: NormalBlending,
  28449. AdditiveBlending: AdditiveBlending,
  28450. SubtractiveBlending: SubtractiveBlending,
  28451. MultiplyBlending: MultiplyBlending,
  28452. CustomBlending: CustomBlending
  28453. };
  28454. var color = new Color();
  28455. var textureLoader = new TextureLoader();
  28456. var materialLoader = new MaterialLoader();
  28457. return function createMaterial( m, texturePath, crossOrigin ) {
  28458. // convert from old material format
  28459. var textures = {};
  28460. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  28461. var fullPath = texturePath + path;
  28462. var loader = Loader.Handlers.get( fullPath );
  28463. var texture;
  28464. if ( loader !== null ) {
  28465. texture = loader.load( fullPath );
  28466. } else {
  28467. textureLoader.setCrossOrigin( crossOrigin );
  28468. texture = textureLoader.load( fullPath );
  28469. }
  28470. if ( repeat !== undefined ) {
  28471. texture.repeat.fromArray( repeat );
  28472. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  28473. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  28474. }
  28475. if ( offset !== undefined ) {
  28476. texture.offset.fromArray( offset );
  28477. }
  28478. if ( wrap !== undefined ) {
  28479. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  28480. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  28481. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  28482. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  28483. }
  28484. if ( anisotropy !== undefined ) {
  28485. texture.anisotropy = anisotropy;
  28486. }
  28487. var uuid = _Math.generateUUID();
  28488. textures[ uuid ] = texture;
  28489. return uuid;
  28490. }
  28491. //
  28492. var json = {
  28493. uuid: _Math.generateUUID(),
  28494. type: 'MeshLambertMaterial'
  28495. };
  28496. for ( var name in m ) {
  28497. var value = m[ name ];
  28498. switch ( name ) {
  28499. case 'DbgColor':
  28500. case 'DbgIndex':
  28501. case 'opticalDensity':
  28502. case 'illumination':
  28503. break;
  28504. case 'DbgName':
  28505. json.name = value;
  28506. break;
  28507. case 'blending':
  28508. json.blending = BlendingMode[ value ];
  28509. break;
  28510. case 'colorAmbient':
  28511. case 'mapAmbient':
  28512. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  28513. break;
  28514. case 'colorDiffuse':
  28515. json.color = color.fromArray( value ).getHex();
  28516. break;
  28517. case 'colorSpecular':
  28518. json.specular = color.fromArray( value ).getHex();
  28519. break;
  28520. case 'colorEmissive':
  28521. json.emissive = color.fromArray( value ).getHex();
  28522. break;
  28523. case 'specularCoef':
  28524. json.shininess = value;
  28525. break;
  28526. case 'shading':
  28527. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  28528. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  28529. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  28530. break;
  28531. case 'mapDiffuse':
  28532. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  28533. break;
  28534. case 'mapDiffuseRepeat':
  28535. case 'mapDiffuseOffset':
  28536. case 'mapDiffuseWrap':
  28537. case 'mapDiffuseAnisotropy':
  28538. break;
  28539. case 'mapEmissive':
  28540. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  28541. break;
  28542. case 'mapEmissiveRepeat':
  28543. case 'mapEmissiveOffset':
  28544. case 'mapEmissiveWrap':
  28545. case 'mapEmissiveAnisotropy':
  28546. break;
  28547. case 'mapLight':
  28548. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  28549. break;
  28550. case 'mapLightRepeat':
  28551. case 'mapLightOffset':
  28552. case 'mapLightWrap':
  28553. case 'mapLightAnisotropy':
  28554. break;
  28555. case 'mapAO':
  28556. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  28557. break;
  28558. case 'mapAORepeat':
  28559. case 'mapAOOffset':
  28560. case 'mapAOWrap':
  28561. case 'mapAOAnisotropy':
  28562. break;
  28563. case 'mapBump':
  28564. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  28565. break;
  28566. case 'mapBumpScale':
  28567. json.bumpScale = value;
  28568. break;
  28569. case 'mapBumpRepeat':
  28570. case 'mapBumpOffset':
  28571. case 'mapBumpWrap':
  28572. case 'mapBumpAnisotropy':
  28573. break;
  28574. case 'mapNormal':
  28575. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  28576. break;
  28577. case 'mapNormalFactor':
  28578. json.normalScale = value;
  28579. break;
  28580. case 'mapNormalRepeat':
  28581. case 'mapNormalOffset':
  28582. case 'mapNormalWrap':
  28583. case 'mapNormalAnisotropy':
  28584. break;
  28585. case 'mapSpecular':
  28586. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  28587. break;
  28588. case 'mapSpecularRepeat':
  28589. case 'mapSpecularOffset':
  28590. case 'mapSpecularWrap':
  28591. case 'mapSpecularAnisotropy':
  28592. break;
  28593. case 'mapMetalness':
  28594. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  28595. break;
  28596. case 'mapMetalnessRepeat':
  28597. case 'mapMetalnessOffset':
  28598. case 'mapMetalnessWrap':
  28599. case 'mapMetalnessAnisotropy':
  28600. break;
  28601. case 'mapRoughness':
  28602. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  28603. break;
  28604. case 'mapRoughnessRepeat':
  28605. case 'mapRoughnessOffset':
  28606. case 'mapRoughnessWrap':
  28607. case 'mapRoughnessAnisotropy':
  28608. break;
  28609. case 'mapAlpha':
  28610. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  28611. break;
  28612. case 'mapAlphaRepeat':
  28613. case 'mapAlphaOffset':
  28614. case 'mapAlphaWrap':
  28615. case 'mapAlphaAnisotropy':
  28616. break;
  28617. case 'flipSided':
  28618. json.side = BackSide;
  28619. break;
  28620. case 'doubleSided':
  28621. json.side = DoubleSide;
  28622. break;
  28623. case 'transparency':
  28624. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  28625. json.opacity = value;
  28626. break;
  28627. case 'depthTest':
  28628. case 'depthWrite':
  28629. case 'colorWrite':
  28630. case 'opacity':
  28631. case 'reflectivity':
  28632. case 'transparent':
  28633. case 'visible':
  28634. case 'wireframe':
  28635. json[ name ] = value;
  28636. break;
  28637. case 'vertexColors':
  28638. if ( value === true ) json.vertexColors = VertexColors;
  28639. if ( value === 'face' ) json.vertexColors = FaceColors;
  28640. break;
  28641. default:
  28642. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  28643. break;
  28644. }
  28645. }
  28646. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  28647. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  28648. if ( json.opacity < 1 ) json.transparent = true;
  28649. materialLoader.setTextures( textures );
  28650. return materialLoader.parse( json );
  28651. };
  28652. } )()
  28653. } );
  28654. /**
  28655. * @author mrdoob / http://mrdoob.com/
  28656. */
  28657. var context;
  28658. var AudioContext = {
  28659. getContext: function () {
  28660. if ( context === undefined ) {
  28661. context = new ( window.AudioContext || window.webkitAudioContext )();
  28662. }
  28663. return context;
  28664. },
  28665. setContext: function ( value ) {
  28666. context = value;
  28667. }
  28668. };
  28669. /**
  28670. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  28671. */
  28672. function AudioLoader( manager ) {
  28673. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  28674. }
  28675. Object.assign( AudioLoader.prototype, {
  28676. load: function ( url, onLoad, onProgress, onError ) {
  28677. var loader = new FileLoader( this.manager );
  28678. loader.setResponseType( 'arraybuffer' );
  28679. loader.setPath( this.path );
  28680. loader.load( url, function ( buffer ) {
  28681. // Create a copy of the buffer. The `decodeAudioData` method
  28682. // detaches the buffer when complete, preventing reuse.
  28683. var bufferCopy = buffer.slice( 0 );
  28684. var context = AudioContext.getContext();
  28685. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  28686. onLoad( audioBuffer );
  28687. } );
  28688. }, onProgress, onError );
  28689. },
  28690. setPath: function ( value ) {
  28691. this.path = value;
  28692. return this;
  28693. }
  28694. } );
  28695. /**
  28696. * @author mrdoob / http://mrdoob.com/
  28697. */
  28698. function StereoCamera() {
  28699. this.type = 'StereoCamera';
  28700. this.aspect = 1;
  28701. this.eyeSep = 0.064;
  28702. this.cameraL = new PerspectiveCamera();
  28703. this.cameraL.layers.enable( 1 );
  28704. this.cameraL.matrixAutoUpdate = false;
  28705. this.cameraR = new PerspectiveCamera();
  28706. this.cameraR.layers.enable( 2 );
  28707. this.cameraR.matrixAutoUpdate = false;
  28708. }
  28709. Object.assign( StereoCamera.prototype, {
  28710. update: ( function () {
  28711. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  28712. var eyeRight = new Matrix4();
  28713. var eyeLeft = new Matrix4();
  28714. return function update( camera ) {
  28715. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  28716. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  28717. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  28718. if ( needsUpdate ) {
  28719. instance = this;
  28720. focus = camera.focus;
  28721. fov = camera.fov;
  28722. aspect = camera.aspect * this.aspect;
  28723. near = camera.near;
  28724. far = camera.far;
  28725. zoom = camera.zoom;
  28726. // Off-axis stereoscopic effect based on
  28727. // http://paulbourke.net/stereographics/stereorender/
  28728. var projectionMatrix = camera.projectionMatrix.clone();
  28729. eyeSep = this.eyeSep / 2;
  28730. var eyeSepOnProjection = eyeSep * near / focus;
  28731. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  28732. var xmin, xmax;
  28733. // translate xOffset
  28734. eyeLeft.elements[ 12 ] = - eyeSep;
  28735. eyeRight.elements[ 12 ] = eyeSep;
  28736. // for left eye
  28737. xmin = - ymax * aspect + eyeSepOnProjection;
  28738. xmax = ymax * aspect + eyeSepOnProjection;
  28739. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  28740. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28741. this.cameraL.projectionMatrix.copy( projectionMatrix );
  28742. // for right eye
  28743. xmin = - ymax * aspect - eyeSepOnProjection;
  28744. xmax = ymax * aspect - eyeSepOnProjection;
  28745. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  28746. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28747. this.cameraR.projectionMatrix.copy( projectionMatrix );
  28748. }
  28749. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  28750. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  28751. };
  28752. } )()
  28753. } );
  28754. /**
  28755. * Camera for rendering cube maps
  28756. * - renders scene into axis-aligned cube
  28757. *
  28758. * @author alteredq / http://alteredqualia.com/
  28759. */
  28760. function CubeCamera( near, far, cubeResolution, options ) {
  28761. Object3D.call( this );
  28762. this.type = 'CubeCamera';
  28763. var fov = 90, aspect = 1;
  28764. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  28765. cameraPX.up.set( 0, - 1, 0 );
  28766. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  28767. this.add( cameraPX );
  28768. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  28769. cameraNX.up.set( 0, - 1, 0 );
  28770. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  28771. this.add( cameraNX );
  28772. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  28773. cameraPY.up.set( 0, 0, 1 );
  28774. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  28775. this.add( cameraPY );
  28776. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  28777. cameraNY.up.set( 0, 0, - 1 );
  28778. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  28779. this.add( cameraNY );
  28780. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  28781. cameraPZ.up.set( 0, - 1, 0 );
  28782. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  28783. this.add( cameraPZ );
  28784. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  28785. cameraNZ.up.set( 0, - 1, 0 );
  28786. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  28787. this.add( cameraNZ );
  28788. options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  28789. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  28790. this.renderTarget.texture.name = "CubeCamera";
  28791. this.update = function ( renderer, scene ) {
  28792. if ( this.parent === null ) this.updateMatrixWorld();
  28793. var currentRenderTarget = renderer.getRenderTarget();
  28794. var renderTarget = this.renderTarget;
  28795. var generateMipmaps = renderTarget.texture.generateMipmaps;
  28796. renderTarget.texture.generateMipmaps = false;
  28797. renderer.setRenderTarget( renderTarget, 0 );
  28798. renderer.render( scene, cameraPX );
  28799. renderer.setRenderTarget( renderTarget, 1 );
  28800. renderer.render( scene, cameraNX );
  28801. renderer.setRenderTarget( renderTarget, 2 );
  28802. renderer.render( scene, cameraPY );
  28803. renderer.setRenderTarget( renderTarget, 3 );
  28804. renderer.render( scene, cameraNY );
  28805. renderer.setRenderTarget( renderTarget, 4 );
  28806. renderer.render( scene, cameraPZ );
  28807. renderTarget.texture.generateMipmaps = generateMipmaps;
  28808. renderer.setRenderTarget( renderTarget, 5 );
  28809. renderer.render( scene, cameraNZ );
  28810. renderer.setRenderTarget( currentRenderTarget );
  28811. };
  28812. this.clear = function ( renderer, color, depth, stencil ) {
  28813. var currentRenderTarget = renderer.getRenderTarget();
  28814. var renderTarget = this.renderTarget;
  28815. for ( var i = 0; i < 6; i ++ ) {
  28816. renderer.setRenderTarget( renderTarget, i );
  28817. renderer.clear( color, depth, stencil );
  28818. }
  28819. renderer.setRenderTarget( currentRenderTarget );
  28820. };
  28821. }
  28822. CubeCamera.prototype = Object.create( Object3D.prototype );
  28823. CubeCamera.prototype.constructor = CubeCamera;
  28824. /**
  28825. * @author alteredq / http://alteredqualia.com/
  28826. */
  28827. function Clock( autoStart ) {
  28828. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  28829. this.startTime = 0;
  28830. this.oldTime = 0;
  28831. this.elapsedTime = 0;
  28832. this.running = false;
  28833. }
  28834. Object.assign( Clock.prototype, {
  28835. start: function () {
  28836. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  28837. this.oldTime = this.startTime;
  28838. this.elapsedTime = 0;
  28839. this.running = true;
  28840. },
  28841. stop: function () {
  28842. this.getElapsedTime();
  28843. this.running = false;
  28844. this.autoStart = false;
  28845. },
  28846. getElapsedTime: function () {
  28847. this.getDelta();
  28848. return this.elapsedTime;
  28849. },
  28850. getDelta: function () {
  28851. var diff = 0;
  28852. if ( this.autoStart && ! this.running ) {
  28853. this.start();
  28854. return 0;
  28855. }
  28856. if ( this.running ) {
  28857. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  28858. diff = ( newTime - this.oldTime ) / 1000;
  28859. this.oldTime = newTime;
  28860. this.elapsedTime += diff;
  28861. }
  28862. return diff;
  28863. }
  28864. } );
  28865. /**
  28866. * @author mrdoob / http://mrdoob.com/
  28867. */
  28868. function AudioListener() {
  28869. Object3D.call( this );
  28870. this.type = 'AudioListener';
  28871. this.context = AudioContext.getContext();
  28872. this.gain = this.context.createGain();
  28873. this.gain.connect( this.context.destination );
  28874. this.filter = null;
  28875. this.timeDelta = 0;
  28876. }
  28877. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28878. constructor: AudioListener,
  28879. getInput: function () {
  28880. return this.gain;
  28881. },
  28882. removeFilter: function ( ) {
  28883. if ( this.filter !== null ) {
  28884. this.gain.disconnect( this.filter );
  28885. this.filter.disconnect( this.context.destination );
  28886. this.gain.connect( this.context.destination );
  28887. this.filter = null;
  28888. }
  28889. return this;
  28890. },
  28891. getFilter: function () {
  28892. return this.filter;
  28893. },
  28894. setFilter: function ( value ) {
  28895. if ( this.filter !== null ) {
  28896. this.gain.disconnect( this.filter );
  28897. this.filter.disconnect( this.context.destination );
  28898. } else {
  28899. this.gain.disconnect( this.context.destination );
  28900. }
  28901. this.filter = value;
  28902. this.gain.connect( this.filter );
  28903. this.filter.connect( this.context.destination );
  28904. return this;
  28905. },
  28906. getMasterVolume: function () {
  28907. return this.gain.gain.value;
  28908. },
  28909. setMasterVolume: function ( value ) {
  28910. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28911. return this;
  28912. },
  28913. updateMatrixWorld: ( function () {
  28914. var position = new Vector3();
  28915. var quaternion = new Quaternion();
  28916. var scale = new Vector3();
  28917. var orientation = new Vector3();
  28918. var clock = new Clock();
  28919. return function updateMatrixWorld( force ) {
  28920. Object3D.prototype.updateMatrixWorld.call( this, force );
  28921. var listener = this.context.listener;
  28922. var up = this.up;
  28923. this.timeDelta = clock.getDelta();
  28924. this.matrixWorld.decompose( position, quaternion, scale );
  28925. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  28926. if ( listener.positionX ) {
  28927. // code path for Chrome (see #14393)
  28928. var endTime = this.context.currentTime + this.timeDelta;
  28929. listener.positionX.linearRampToValueAtTime( position.x, endTime );
  28930. listener.positionY.linearRampToValueAtTime( position.y, endTime );
  28931. listener.positionZ.linearRampToValueAtTime( position.z, endTime );
  28932. listener.forwardX.linearRampToValueAtTime( orientation.x, endTime );
  28933. listener.forwardY.linearRampToValueAtTime( orientation.y, endTime );
  28934. listener.forwardZ.linearRampToValueAtTime( orientation.z, endTime );
  28935. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28936. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28937. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28938. } else {
  28939. listener.setPosition( position.x, position.y, position.z );
  28940. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  28941. }
  28942. };
  28943. } )()
  28944. } );
  28945. /**
  28946. * @author mrdoob / http://mrdoob.com/
  28947. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  28948. */
  28949. function Audio( listener ) {
  28950. Object3D.call( this );
  28951. this.type = 'Audio';
  28952. this.listener = listener;
  28953. this.context = listener.context;
  28954. this.gain = this.context.createGain();
  28955. this.gain.connect( listener.getInput() );
  28956. this.autoplay = false;
  28957. this.buffer = null;
  28958. this.detune = 0;
  28959. this.loop = false;
  28960. this.startTime = 0;
  28961. this.offset = 0;
  28962. this.playbackRate = 1;
  28963. this.isPlaying = false;
  28964. this.hasPlaybackControl = true;
  28965. this.sourceType = 'empty';
  28966. this.filters = [];
  28967. }
  28968. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  28969. constructor: Audio,
  28970. getOutput: function () {
  28971. return this.gain;
  28972. },
  28973. setNodeSource: function ( audioNode ) {
  28974. this.hasPlaybackControl = false;
  28975. this.sourceType = 'audioNode';
  28976. this.source = audioNode;
  28977. this.connect();
  28978. return this;
  28979. },
  28980. setMediaElementSource: function ( mediaElement ) {
  28981. this.hasPlaybackControl = false;
  28982. this.sourceType = 'mediaNode';
  28983. this.source = this.context.createMediaElementSource( mediaElement );
  28984. this.connect();
  28985. return this;
  28986. },
  28987. setBuffer: function ( audioBuffer ) {
  28988. this.buffer = audioBuffer;
  28989. this.sourceType = 'buffer';
  28990. if ( this.autoplay ) this.play();
  28991. return this;
  28992. },
  28993. play: function () {
  28994. if ( this.isPlaying === true ) {
  28995. console.warn( 'THREE.Audio: Audio is already playing.' );
  28996. return;
  28997. }
  28998. if ( this.hasPlaybackControl === false ) {
  28999. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29000. return;
  29001. }
  29002. var source = this.context.createBufferSource();
  29003. source.buffer = this.buffer;
  29004. source.loop = this.loop;
  29005. source.onended = this.onEnded.bind( this );
  29006. this.startTime = this.context.currentTime;
  29007. source.start( this.startTime, this.offset );
  29008. this.isPlaying = true;
  29009. this.source = source;
  29010. this.setDetune( this.detune );
  29011. this.setPlaybackRate( this.playbackRate );
  29012. return this.connect();
  29013. },
  29014. pause: function () {
  29015. if ( this.hasPlaybackControl === false ) {
  29016. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29017. return;
  29018. }
  29019. if ( this.isPlaying === true ) {
  29020. this.source.stop();
  29021. this.source.onended = null;
  29022. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  29023. this.isPlaying = false;
  29024. }
  29025. return this;
  29026. },
  29027. stop: function () {
  29028. if ( this.hasPlaybackControl === false ) {
  29029. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29030. return;
  29031. }
  29032. this.source.stop();
  29033. this.source.onended = null;
  29034. this.offset = 0;
  29035. this.isPlaying = false;
  29036. return this;
  29037. },
  29038. connect: function () {
  29039. if ( this.filters.length > 0 ) {
  29040. this.source.connect( this.filters[ 0 ] );
  29041. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  29042. this.filters[ i - 1 ].connect( this.filters[ i ] );
  29043. }
  29044. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  29045. } else {
  29046. this.source.connect( this.getOutput() );
  29047. }
  29048. return this;
  29049. },
  29050. disconnect: function () {
  29051. if ( this.filters.length > 0 ) {
  29052. this.source.disconnect( this.filters[ 0 ] );
  29053. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  29054. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  29055. }
  29056. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  29057. } else {
  29058. this.source.disconnect( this.getOutput() );
  29059. }
  29060. return this;
  29061. },
  29062. getFilters: function () {
  29063. return this.filters;
  29064. },
  29065. setFilters: function ( value ) {
  29066. if ( ! value ) value = [];
  29067. if ( this.isPlaying === true ) {
  29068. this.disconnect();
  29069. this.filters = value;
  29070. this.connect();
  29071. } else {
  29072. this.filters = value;
  29073. }
  29074. return this;
  29075. },
  29076. setDetune: function ( value ) {
  29077. this.detune = value;
  29078. if ( this.source.detune === undefined ) return; // only set detune when available
  29079. if ( this.isPlaying === true ) {
  29080. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  29081. }
  29082. return this;
  29083. },
  29084. getDetune: function () {
  29085. return this.detune;
  29086. },
  29087. getFilter: function () {
  29088. return this.getFilters()[ 0 ];
  29089. },
  29090. setFilter: function ( filter ) {
  29091. return this.setFilters( filter ? [ filter ] : [] );
  29092. },
  29093. setPlaybackRate: function ( value ) {
  29094. if ( this.hasPlaybackControl === false ) {
  29095. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29096. return;
  29097. }
  29098. this.playbackRate = value;
  29099. if ( this.isPlaying === true ) {
  29100. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  29101. }
  29102. return this;
  29103. },
  29104. getPlaybackRate: function () {
  29105. return this.playbackRate;
  29106. },
  29107. onEnded: function () {
  29108. this.isPlaying = false;
  29109. },
  29110. getLoop: function () {
  29111. if ( this.hasPlaybackControl === false ) {
  29112. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29113. return false;
  29114. }
  29115. return this.loop;
  29116. },
  29117. setLoop: function ( value ) {
  29118. if ( this.hasPlaybackControl === false ) {
  29119. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  29120. return;
  29121. }
  29122. this.loop = value;
  29123. if ( this.isPlaying === true ) {
  29124. this.source.loop = this.loop;
  29125. }
  29126. return this;
  29127. },
  29128. getVolume: function () {
  29129. return this.gain.gain.value;
  29130. },
  29131. setVolume: function ( value ) {
  29132. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  29133. return this;
  29134. }
  29135. } );
  29136. /**
  29137. * @author mrdoob / http://mrdoob.com/
  29138. */
  29139. function PositionalAudio( listener ) {
  29140. Audio.call( this, listener );
  29141. this.panner = this.context.createPanner();
  29142. this.panner.connect( this.gain );
  29143. }
  29144. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  29145. constructor: PositionalAudio,
  29146. getOutput: function () {
  29147. return this.panner;
  29148. },
  29149. getRefDistance: function () {
  29150. return this.panner.refDistance;
  29151. },
  29152. setRefDistance: function ( value ) {
  29153. this.panner.refDistance = value;
  29154. return this;
  29155. },
  29156. getRolloffFactor: function () {
  29157. return this.panner.rolloffFactor;
  29158. },
  29159. setRolloffFactor: function ( value ) {
  29160. this.panner.rolloffFactor = value;
  29161. return this;
  29162. },
  29163. getDistanceModel: function () {
  29164. return this.panner.distanceModel;
  29165. },
  29166. setDistanceModel: function ( value ) {
  29167. this.panner.distanceModel = value;
  29168. return this;
  29169. },
  29170. getMaxDistance: function () {
  29171. return this.panner.maxDistance;
  29172. },
  29173. setMaxDistance: function ( value ) {
  29174. this.panner.maxDistance = value;
  29175. return this;
  29176. },
  29177. setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  29178. this.panner.coneInnerAngle = coneInnerAngle;
  29179. this.panner.coneOuterAngle = coneOuterAngle;
  29180. this.panner.coneOuterGain = coneOuterGain;
  29181. return this;
  29182. },
  29183. updateMatrixWorld: ( function () {
  29184. var position = new Vector3();
  29185. var quaternion = new Quaternion();
  29186. var scale = new Vector3();
  29187. var orientation = new Vector3();
  29188. return function updateMatrixWorld( force ) {
  29189. Object3D.prototype.updateMatrixWorld.call( this, force );
  29190. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  29191. this.matrixWorld.decompose( position, quaternion, scale );
  29192. orientation.set( 0, 0, 1 ).applyQuaternion( quaternion );
  29193. var panner = this.panner;
  29194. if ( panner.positionX ) {
  29195. // code path for Chrome and Firefox (see #14393)
  29196. var endTime = this.context.currentTime + this.listener.timeDelta;
  29197. panner.positionX.linearRampToValueAtTime( position.x, endTime );
  29198. panner.positionY.linearRampToValueAtTime( position.y, endTime );
  29199. panner.positionZ.linearRampToValueAtTime( position.z, endTime );
  29200. panner.orientationX.linearRampToValueAtTime( orientation.x, endTime );
  29201. panner.orientationY.linearRampToValueAtTime( orientation.y, endTime );
  29202. panner.orientationZ.linearRampToValueAtTime( orientation.z, endTime );
  29203. } else {
  29204. panner.setPosition( position.x, position.y, position.z );
  29205. panner.setOrientation( orientation.x, orientation.y, orientation.z );
  29206. }
  29207. };
  29208. } )()
  29209. } );
  29210. /**
  29211. * @author mrdoob / http://mrdoob.com/
  29212. */
  29213. function AudioAnalyser( audio, fftSize ) {
  29214. this.analyser = audio.context.createAnalyser();
  29215. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  29216. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  29217. audio.getOutput().connect( this.analyser );
  29218. }
  29219. Object.assign( AudioAnalyser.prototype, {
  29220. getFrequencyData: function () {
  29221. this.analyser.getByteFrequencyData( this.data );
  29222. return this.data;
  29223. },
  29224. getAverageFrequency: function () {
  29225. var value = 0, data = this.getFrequencyData();
  29226. for ( var i = 0; i < data.length; i ++ ) {
  29227. value += data[ i ];
  29228. }
  29229. return value / data.length;
  29230. }
  29231. } );
  29232. /**
  29233. *
  29234. * Buffered scene graph property that allows weighted accumulation.
  29235. *
  29236. *
  29237. * @author Ben Houston / http://clara.io/
  29238. * @author David Sarno / http://lighthaus.us/
  29239. * @author tschw
  29240. */
  29241. function PropertyMixer( binding, typeName, valueSize ) {
  29242. this.binding = binding;
  29243. this.valueSize = valueSize;
  29244. var bufferType = Float64Array,
  29245. mixFunction;
  29246. switch ( typeName ) {
  29247. case 'quaternion':
  29248. mixFunction = this._slerp;
  29249. break;
  29250. case 'string':
  29251. case 'bool':
  29252. bufferType = Array;
  29253. mixFunction = this._select;
  29254. break;
  29255. default:
  29256. mixFunction = this._lerp;
  29257. }
  29258. this.buffer = new bufferType( valueSize * 4 );
  29259. // layout: [ incoming | accu0 | accu1 | orig ]
  29260. //
  29261. // interpolators can use .buffer as their .result
  29262. // the data then goes to 'incoming'
  29263. //
  29264. // 'accu0' and 'accu1' are used frame-interleaved for
  29265. // the cumulative result and are compared to detect
  29266. // changes
  29267. //
  29268. // 'orig' stores the original state of the property
  29269. this._mixBufferRegion = mixFunction;
  29270. this.cumulativeWeight = 0;
  29271. this.useCount = 0;
  29272. this.referenceCount = 0;
  29273. }
  29274. Object.assign( PropertyMixer.prototype, {
  29275. // accumulate data in the 'incoming' region into 'accu<i>'
  29276. accumulate: function ( accuIndex, weight ) {
  29277. // note: happily accumulating nothing when weight = 0, the caller knows
  29278. // the weight and shouldn't have made the call in the first place
  29279. var buffer = this.buffer,
  29280. stride = this.valueSize,
  29281. offset = accuIndex * stride + stride,
  29282. currentWeight = this.cumulativeWeight;
  29283. if ( currentWeight === 0 ) {
  29284. // accuN := incoming * weight
  29285. for ( var i = 0; i !== stride; ++ i ) {
  29286. buffer[ offset + i ] = buffer[ i ];
  29287. }
  29288. currentWeight = weight;
  29289. } else {
  29290. // accuN := accuN + incoming * weight
  29291. currentWeight += weight;
  29292. var mix = weight / currentWeight;
  29293. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  29294. }
  29295. this.cumulativeWeight = currentWeight;
  29296. },
  29297. // apply the state of 'accu<i>' to the binding when accus differ
  29298. apply: function ( accuIndex ) {
  29299. var stride = this.valueSize,
  29300. buffer = this.buffer,
  29301. offset = accuIndex * stride + stride,
  29302. weight = this.cumulativeWeight,
  29303. binding = this.binding;
  29304. this.cumulativeWeight = 0;
  29305. if ( weight < 1 ) {
  29306. // accuN := accuN + original * ( 1 - cumulativeWeight )
  29307. var originalValueOffset = stride * 3;
  29308. this._mixBufferRegion(
  29309. buffer, offset, originalValueOffset, 1 - weight, stride );
  29310. }
  29311. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  29312. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  29313. // value has changed -> update scene graph
  29314. binding.setValue( buffer, offset );
  29315. break;
  29316. }
  29317. }
  29318. },
  29319. // remember the state of the bound property and copy it to both accus
  29320. saveOriginalState: function () {
  29321. var binding = this.binding;
  29322. var buffer = this.buffer,
  29323. stride = this.valueSize,
  29324. originalValueOffset = stride * 3;
  29325. binding.getValue( buffer, originalValueOffset );
  29326. // accu[0..1] := orig -- initially detect changes against the original
  29327. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  29328. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  29329. }
  29330. this.cumulativeWeight = 0;
  29331. },
  29332. // apply the state previously taken via 'saveOriginalState' to the binding
  29333. restoreOriginalState: function () {
  29334. var originalValueOffset = this.valueSize * 3;
  29335. this.binding.setValue( this.buffer, originalValueOffset );
  29336. },
  29337. // mix functions
  29338. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  29339. if ( t >= 0.5 ) {
  29340. for ( var i = 0; i !== stride; ++ i ) {
  29341. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  29342. }
  29343. }
  29344. },
  29345. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  29346. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  29347. },
  29348. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  29349. var s = 1 - t;
  29350. for ( var i = 0; i !== stride; ++ i ) {
  29351. var j = dstOffset + i;
  29352. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  29353. }
  29354. }
  29355. } );
  29356. /**
  29357. *
  29358. * A reference to a real property in the scene graph.
  29359. *
  29360. *
  29361. * @author Ben Houston / http://clara.io/
  29362. * @author David Sarno / http://lighthaus.us/
  29363. * @author tschw
  29364. */
  29365. // Characters [].:/ are reserved for track binding syntax.
  29366. var RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  29367. function Composite( targetGroup, path, optionalParsedPath ) {
  29368. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  29369. this._targetGroup = targetGroup;
  29370. this._bindings = targetGroup.subscribe_( path, parsedPath );
  29371. }
  29372. Object.assign( Composite.prototype, {
  29373. getValue: function ( array, offset ) {
  29374. this.bind(); // bind all binding
  29375. var firstValidIndex = this._targetGroup.nCachedObjects_,
  29376. binding = this._bindings[ firstValidIndex ];
  29377. // and only call .getValue on the first
  29378. if ( binding !== undefined ) binding.getValue( array, offset );
  29379. },
  29380. setValue: function ( array, offset ) {
  29381. var bindings = this._bindings;
  29382. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29383. bindings[ i ].setValue( array, offset );
  29384. }
  29385. },
  29386. bind: function () {
  29387. var bindings = this._bindings;
  29388. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29389. bindings[ i ].bind();
  29390. }
  29391. },
  29392. unbind: function () {
  29393. var bindings = this._bindings;
  29394. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29395. bindings[ i ].unbind();
  29396. }
  29397. }
  29398. } );
  29399. function PropertyBinding( rootNode, path, parsedPath ) {
  29400. this.path = path;
  29401. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  29402. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  29403. this.rootNode = rootNode;
  29404. }
  29405. Object.assign( PropertyBinding, {
  29406. Composite: Composite,
  29407. create: function ( root, path, parsedPath ) {
  29408. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  29409. return new PropertyBinding( root, path, parsedPath );
  29410. } else {
  29411. return new PropertyBinding.Composite( root, path, parsedPath );
  29412. }
  29413. },
  29414. /**
  29415. * Replaces spaces with underscores and removes unsupported characters from
  29416. * node names, to ensure compatibility with parseTrackName().
  29417. *
  29418. * @param {string} name Node name to be sanitized.
  29419. * @return {string}
  29420. */
  29421. sanitizeNodeName: ( function () {
  29422. var reservedRe = new RegExp( '[' + RESERVED_CHARS_RE + ']', 'g' );
  29423. return function sanitizeNodeName( name ) {
  29424. return name.replace( /\s/g, '_' ).replace( reservedRe, '' );
  29425. };
  29426. }() ),
  29427. parseTrackName: function () {
  29428. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  29429. // only latin characters, and the unicode \p{L} is not yet supported. So
  29430. // instead, we exclude reserved characters and match everything else.
  29431. var wordChar = '[^' + RESERVED_CHARS_RE + ']';
  29432. var wordCharOrDot = '[^' + RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  29433. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  29434. // be matched to parse the rest of the track name.
  29435. var directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', wordChar );
  29436. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  29437. var nodeRe = /(WCOD+)?/.source.replace( 'WCOD', wordCharOrDot );
  29438. // Object on target node, and accessor. May not contain reserved
  29439. // characters. Accessor may contain any character except closing bracket.
  29440. var objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', wordChar );
  29441. // Property and accessor. May not contain reserved characters. Accessor may
  29442. // contain any non-bracket characters.
  29443. var propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', wordChar );
  29444. var trackRe = new RegExp( ''
  29445. + '^'
  29446. + directoryRe
  29447. + nodeRe
  29448. + objectRe
  29449. + propertyRe
  29450. + '$'
  29451. );
  29452. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  29453. return function parseTrackName( trackName ) {
  29454. var matches = trackRe.exec( trackName );
  29455. if ( ! matches ) {
  29456. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  29457. }
  29458. var results = {
  29459. // directoryName: matches[ 1 ], // (tschw) currently unused
  29460. nodeName: matches[ 2 ],
  29461. objectName: matches[ 3 ],
  29462. objectIndex: matches[ 4 ],
  29463. propertyName: matches[ 5 ], // required
  29464. propertyIndex: matches[ 6 ]
  29465. };
  29466. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  29467. if ( lastDot !== undefined && lastDot !== - 1 ) {
  29468. var objectName = results.nodeName.substring( lastDot + 1 );
  29469. // Object names must be checked against a whitelist. Otherwise, there
  29470. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  29471. // 'bar' could be the objectName, or part of a nodeName (which can
  29472. // include '.' characters).
  29473. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  29474. results.nodeName = results.nodeName.substring( 0, lastDot );
  29475. results.objectName = objectName;
  29476. }
  29477. }
  29478. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  29479. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  29480. }
  29481. return results;
  29482. };
  29483. }(),
  29484. findNode: function ( root, nodeName ) {
  29485. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  29486. return root;
  29487. }
  29488. // search into skeleton bones.
  29489. if ( root.skeleton ) {
  29490. var bone = root.skeleton.getBoneByName( nodeName );
  29491. if ( bone !== undefined ) {
  29492. return bone;
  29493. }
  29494. }
  29495. // search into node subtree.
  29496. if ( root.children ) {
  29497. var searchNodeSubtree = function ( children ) {
  29498. for ( var i = 0; i < children.length; i ++ ) {
  29499. var childNode = children[ i ];
  29500. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  29501. return childNode;
  29502. }
  29503. var result = searchNodeSubtree( childNode.children );
  29504. if ( result ) return result;
  29505. }
  29506. return null;
  29507. };
  29508. var subTreeNode = searchNodeSubtree( root.children );
  29509. if ( subTreeNode ) {
  29510. return subTreeNode;
  29511. }
  29512. }
  29513. return null;
  29514. }
  29515. } );
  29516. Object.assign( PropertyBinding.prototype, { // prototype, continued
  29517. // these are used to "bind" a nonexistent property
  29518. _getValue_unavailable: function () {},
  29519. _setValue_unavailable: function () {},
  29520. BindingType: {
  29521. Direct: 0,
  29522. EntireArray: 1,
  29523. ArrayElement: 2,
  29524. HasFromToArray: 3
  29525. },
  29526. Versioning: {
  29527. None: 0,
  29528. NeedsUpdate: 1,
  29529. MatrixWorldNeedsUpdate: 2
  29530. },
  29531. GetterByBindingType: [
  29532. function getValue_direct( buffer, offset ) {
  29533. buffer[ offset ] = this.node[ this.propertyName ];
  29534. },
  29535. function getValue_array( buffer, offset ) {
  29536. var source = this.resolvedProperty;
  29537. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  29538. buffer[ offset ++ ] = source[ i ];
  29539. }
  29540. },
  29541. function getValue_arrayElement( buffer, offset ) {
  29542. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  29543. },
  29544. function getValue_toArray( buffer, offset ) {
  29545. this.resolvedProperty.toArray( buffer, offset );
  29546. }
  29547. ],
  29548. SetterByBindingTypeAndVersioning: [
  29549. [
  29550. // Direct
  29551. function setValue_direct( buffer, offset ) {
  29552. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29553. },
  29554. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  29555. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29556. this.targetObject.needsUpdate = true;
  29557. },
  29558. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29559. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29560. this.targetObject.matrixWorldNeedsUpdate = true;
  29561. }
  29562. ], [
  29563. // EntireArray
  29564. function setValue_array( buffer, offset ) {
  29565. var dest = this.resolvedProperty;
  29566. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  29567. dest[ i ] = buffer[ offset ++ ];
  29568. }
  29569. },
  29570. function setValue_array_setNeedsUpdate( buffer, offset ) {
  29571. var dest = this.resolvedProperty;
  29572. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  29573. dest[ i ] = buffer[ offset ++ ];
  29574. }
  29575. this.targetObject.needsUpdate = true;
  29576. },
  29577. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29578. var dest = this.resolvedProperty;
  29579. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  29580. dest[ i ] = buffer[ offset ++ ];
  29581. }
  29582. this.targetObject.matrixWorldNeedsUpdate = true;
  29583. }
  29584. ], [
  29585. // ArrayElement
  29586. function setValue_arrayElement( buffer, offset ) {
  29587. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29588. },
  29589. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  29590. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29591. this.targetObject.needsUpdate = true;
  29592. },
  29593. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29594. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29595. this.targetObject.matrixWorldNeedsUpdate = true;
  29596. }
  29597. ], [
  29598. // HasToFromArray
  29599. function setValue_fromArray( buffer, offset ) {
  29600. this.resolvedProperty.fromArray( buffer, offset );
  29601. },
  29602. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  29603. this.resolvedProperty.fromArray( buffer, offset );
  29604. this.targetObject.needsUpdate = true;
  29605. },
  29606. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29607. this.resolvedProperty.fromArray( buffer, offset );
  29608. this.targetObject.matrixWorldNeedsUpdate = true;
  29609. }
  29610. ]
  29611. ],
  29612. getValue: function getValue_unbound( targetArray, offset ) {
  29613. this.bind();
  29614. this.getValue( targetArray, offset );
  29615. // Note: This class uses a State pattern on a per-method basis:
  29616. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  29617. // prototype version of these methods with one that represents
  29618. // the bound state. When the property is not found, the methods
  29619. // become no-ops.
  29620. },
  29621. setValue: function getValue_unbound( sourceArray, offset ) {
  29622. this.bind();
  29623. this.setValue( sourceArray, offset );
  29624. },
  29625. // create getter / setter pair for a property in the scene graph
  29626. bind: function () {
  29627. var targetObject = this.node,
  29628. parsedPath = this.parsedPath,
  29629. objectName = parsedPath.objectName,
  29630. propertyName = parsedPath.propertyName,
  29631. propertyIndex = parsedPath.propertyIndex;
  29632. if ( ! targetObject ) {
  29633. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  29634. this.node = targetObject;
  29635. }
  29636. // set fail state so we can just 'return' on error
  29637. this.getValue = this._getValue_unavailable;
  29638. this.setValue = this._setValue_unavailable;
  29639. // ensure there is a value node
  29640. if ( ! targetObject ) {
  29641. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  29642. return;
  29643. }
  29644. if ( objectName ) {
  29645. var objectIndex = parsedPath.objectIndex;
  29646. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29647. switch ( objectName ) {
  29648. case 'materials':
  29649. if ( ! targetObject.material ) {
  29650. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29651. return;
  29652. }
  29653. if ( ! targetObject.material.materials ) {
  29654. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29655. return;
  29656. }
  29657. targetObject = targetObject.material.materials;
  29658. break;
  29659. case 'bones':
  29660. if ( ! targetObject.skeleton ) {
  29661. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29662. return;
  29663. }
  29664. // potential future optimization: skip this if propertyIndex is already an integer
  29665. // and convert the integer string to a true integer.
  29666. targetObject = targetObject.skeleton.bones;
  29667. // support resolving morphTarget names into indices.
  29668. for ( var i = 0; i < targetObject.length; i ++ ) {
  29669. if ( targetObject[ i ].name === objectIndex ) {
  29670. objectIndex = i;
  29671. break;
  29672. }
  29673. }
  29674. break;
  29675. default:
  29676. if ( targetObject[ objectName ] === undefined ) {
  29677. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29678. return;
  29679. }
  29680. targetObject = targetObject[ objectName ];
  29681. }
  29682. if ( objectIndex !== undefined ) {
  29683. if ( targetObject[ objectIndex ] === undefined ) {
  29684. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29685. return;
  29686. }
  29687. targetObject = targetObject[ objectIndex ];
  29688. }
  29689. }
  29690. // resolve property
  29691. var nodeProperty = targetObject[ propertyName ];
  29692. if ( nodeProperty === undefined ) {
  29693. var nodeName = parsedPath.nodeName;
  29694. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29695. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29696. return;
  29697. }
  29698. // determine versioning scheme
  29699. var versioning = this.Versioning.None;
  29700. this.targetObject = targetObject;
  29701. if ( targetObject.needsUpdate !== undefined ) { // material
  29702. versioning = this.Versioning.NeedsUpdate;
  29703. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  29704. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29705. }
  29706. // determine how the property gets bound
  29707. var bindingType = this.BindingType.Direct;
  29708. if ( propertyIndex !== undefined ) {
  29709. // access a sub element of the property array (only primitives are supported right now)
  29710. if ( propertyName === "morphTargetInfluences" ) {
  29711. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29712. // support resolving morphTarget names into indices.
  29713. if ( ! targetObject.geometry ) {
  29714. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29715. return;
  29716. }
  29717. if ( targetObject.geometry.isBufferGeometry ) {
  29718. if ( ! targetObject.geometry.morphAttributes ) {
  29719. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29720. return;
  29721. }
  29722. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  29723. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  29724. propertyIndex = i;
  29725. break;
  29726. }
  29727. }
  29728. } else {
  29729. if ( ! targetObject.geometry.morphTargets ) {
  29730. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  29731. return;
  29732. }
  29733. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  29734. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  29735. propertyIndex = i;
  29736. break;
  29737. }
  29738. }
  29739. }
  29740. }
  29741. bindingType = this.BindingType.ArrayElement;
  29742. this.resolvedProperty = nodeProperty;
  29743. this.propertyIndex = propertyIndex;
  29744. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29745. // must use copy for Object3D.Euler/Quaternion
  29746. bindingType = this.BindingType.HasFromToArray;
  29747. this.resolvedProperty = nodeProperty;
  29748. } else if ( Array.isArray( nodeProperty ) ) {
  29749. bindingType = this.BindingType.EntireArray;
  29750. this.resolvedProperty = nodeProperty;
  29751. } else {
  29752. this.propertyName = propertyName;
  29753. }
  29754. // select getter / setter
  29755. this.getValue = this.GetterByBindingType[ bindingType ];
  29756. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29757. },
  29758. unbind: function () {
  29759. this.node = null;
  29760. // back to the prototype version of getValue / setValue
  29761. // note: avoiding to mutate the shape of 'this' via 'delete'
  29762. this.getValue = this._getValue_unbound;
  29763. this.setValue = this._setValue_unbound;
  29764. }
  29765. } );
  29766. //!\ DECLARE ALIAS AFTER assign prototype !
  29767. Object.assign( PropertyBinding.prototype, {
  29768. // initial state of these methods that calls 'bind'
  29769. _getValue_unbound: PropertyBinding.prototype.getValue,
  29770. _setValue_unbound: PropertyBinding.prototype.setValue,
  29771. } );
  29772. /**
  29773. *
  29774. * A group of objects that receives a shared animation state.
  29775. *
  29776. * Usage:
  29777. *
  29778. * - Add objects you would otherwise pass as 'root' to the
  29779. * constructor or the .clipAction method of AnimationMixer.
  29780. *
  29781. * - Instead pass this object as 'root'.
  29782. *
  29783. * - You can also add and remove objects later when the mixer
  29784. * is running.
  29785. *
  29786. * Note:
  29787. *
  29788. * Objects of this class appear as one object to the mixer,
  29789. * so cache control of the individual objects must be done
  29790. * on the group.
  29791. *
  29792. * Limitation:
  29793. *
  29794. * - The animated properties must be compatible among the
  29795. * all objects in the group.
  29796. *
  29797. * - A single property can either be controlled through a
  29798. * target group or directly, but not both.
  29799. *
  29800. * @author tschw
  29801. */
  29802. function AnimationObjectGroup() {
  29803. this.uuid = _Math.generateUUID();
  29804. // cached objects followed by the active ones
  29805. this._objects = Array.prototype.slice.call( arguments );
  29806. this.nCachedObjects_ = 0; // threshold
  29807. // note: read by PropertyBinding.Composite
  29808. var indices = {};
  29809. this._indicesByUUID = indices; // for bookkeeping
  29810. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29811. indices[ arguments[ i ].uuid ] = i;
  29812. }
  29813. this._paths = []; // inside: string
  29814. this._parsedPaths = []; // inside: { we don't care, here }
  29815. this._bindings = []; // inside: Array< PropertyBinding >
  29816. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29817. var scope = this;
  29818. this.stats = {
  29819. objects: {
  29820. get total() {
  29821. return scope._objects.length;
  29822. },
  29823. get inUse() {
  29824. return this.total - scope.nCachedObjects_;
  29825. }
  29826. },
  29827. get bindingsPerObject() {
  29828. return scope._bindings.length;
  29829. }
  29830. };
  29831. }
  29832. Object.assign( AnimationObjectGroup.prototype, {
  29833. isAnimationObjectGroup: true,
  29834. add: function () {
  29835. var objects = this._objects,
  29836. nObjects = objects.length,
  29837. nCachedObjects = this.nCachedObjects_,
  29838. indicesByUUID = this._indicesByUUID,
  29839. paths = this._paths,
  29840. parsedPaths = this._parsedPaths,
  29841. bindings = this._bindings,
  29842. nBindings = bindings.length,
  29843. knownObject = undefined;
  29844. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29845. var object = arguments[ i ],
  29846. uuid = object.uuid,
  29847. index = indicesByUUID[ uuid ];
  29848. if ( index === undefined ) {
  29849. // unknown object -> add it to the ACTIVE region
  29850. index = nObjects ++;
  29851. indicesByUUID[ uuid ] = index;
  29852. objects.push( object );
  29853. // accounting is done, now do the same for all bindings
  29854. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29855. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29856. }
  29857. } else if ( index < nCachedObjects ) {
  29858. knownObject = objects[ index ];
  29859. // move existing object to the ACTIVE region
  29860. var firstActiveIndex = -- nCachedObjects,
  29861. lastCachedObject = objects[ firstActiveIndex ];
  29862. indicesByUUID[ lastCachedObject.uuid ] = index;
  29863. objects[ index ] = lastCachedObject;
  29864. indicesByUUID[ uuid ] = firstActiveIndex;
  29865. objects[ firstActiveIndex ] = object;
  29866. // accounting is done, now do the same for all bindings
  29867. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29868. var bindingsForPath = bindings[ j ],
  29869. lastCached = bindingsForPath[ firstActiveIndex ],
  29870. binding = bindingsForPath[ index ];
  29871. bindingsForPath[ index ] = lastCached;
  29872. if ( binding === undefined ) {
  29873. // since we do not bother to create new bindings
  29874. // for objects that are cached, the binding may
  29875. // or may not exist
  29876. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29877. }
  29878. bindingsForPath[ firstActiveIndex ] = binding;
  29879. }
  29880. } else if ( objects[ index ] !== knownObject ) {
  29881. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29882. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29883. } // else the object is already where we want it to be
  29884. } // for arguments
  29885. this.nCachedObjects_ = nCachedObjects;
  29886. },
  29887. remove: function () {
  29888. var objects = this._objects,
  29889. nCachedObjects = this.nCachedObjects_,
  29890. indicesByUUID = this._indicesByUUID,
  29891. bindings = this._bindings,
  29892. nBindings = bindings.length;
  29893. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29894. var object = arguments[ i ],
  29895. uuid = object.uuid,
  29896. index = indicesByUUID[ uuid ];
  29897. if ( index !== undefined && index >= nCachedObjects ) {
  29898. // move existing object into the CACHED region
  29899. var lastCachedIndex = nCachedObjects ++,
  29900. firstActiveObject = objects[ lastCachedIndex ];
  29901. indicesByUUID[ firstActiveObject.uuid ] = index;
  29902. objects[ index ] = firstActiveObject;
  29903. indicesByUUID[ uuid ] = lastCachedIndex;
  29904. objects[ lastCachedIndex ] = object;
  29905. // accounting is done, now do the same for all bindings
  29906. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29907. var bindingsForPath = bindings[ j ],
  29908. firstActive = bindingsForPath[ lastCachedIndex ],
  29909. binding = bindingsForPath[ index ];
  29910. bindingsForPath[ index ] = firstActive;
  29911. bindingsForPath[ lastCachedIndex ] = binding;
  29912. }
  29913. }
  29914. } // for arguments
  29915. this.nCachedObjects_ = nCachedObjects;
  29916. },
  29917. // remove & forget
  29918. uncache: function () {
  29919. var objects = this._objects,
  29920. nObjects = objects.length,
  29921. nCachedObjects = this.nCachedObjects_,
  29922. indicesByUUID = this._indicesByUUID,
  29923. bindings = this._bindings,
  29924. nBindings = bindings.length;
  29925. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  29926. var object = arguments[ i ],
  29927. uuid = object.uuid,
  29928. index = indicesByUUID[ uuid ];
  29929. if ( index !== undefined ) {
  29930. delete indicesByUUID[ uuid ];
  29931. if ( index < nCachedObjects ) {
  29932. // object is cached, shrink the CACHED region
  29933. var firstActiveIndex = -- nCachedObjects,
  29934. lastCachedObject = objects[ firstActiveIndex ],
  29935. lastIndex = -- nObjects,
  29936. lastObject = objects[ lastIndex ];
  29937. // last cached object takes this object's place
  29938. indicesByUUID[ lastCachedObject.uuid ] = index;
  29939. objects[ index ] = lastCachedObject;
  29940. // last object goes to the activated slot and pop
  29941. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29942. objects[ firstActiveIndex ] = lastObject;
  29943. objects.pop();
  29944. // accounting is done, now do the same for all bindings
  29945. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29946. var bindingsForPath = bindings[ j ],
  29947. lastCached = bindingsForPath[ firstActiveIndex ],
  29948. last = bindingsForPath[ lastIndex ];
  29949. bindingsForPath[ index ] = lastCached;
  29950. bindingsForPath[ firstActiveIndex ] = last;
  29951. bindingsForPath.pop();
  29952. }
  29953. } else {
  29954. // object is active, just swap with the last and pop
  29955. var lastIndex = -- nObjects,
  29956. lastObject = objects[ lastIndex ];
  29957. indicesByUUID[ lastObject.uuid ] = index;
  29958. objects[ index ] = lastObject;
  29959. objects.pop();
  29960. // accounting is done, now do the same for all bindings
  29961. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  29962. var bindingsForPath = bindings[ j ];
  29963. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29964. bindingsForPath.pop();
  29965. }
  29966. } // cached or active
  29967. } // if object is known
  29968. } // for arguments
  29969. this.nCachedObjects_ = nCachedObjects;
  29970. },
  29971. // Internal interface used by befriended PropertyBinding.Composite:
  29972. subscribe_: function ( path, parsedPath ) {
  29973. // returns an array of bindings for the given path that is changed
  29974. // according to the contained objects in the group
  29975. var indicesByPath = this._bindingsIndicesByPath,
  29976. index = indicesByPath[ path ],
  29977. bindings = this._bindings;
  29978. if ( index !== undefined ) return bindings[ index ];
  29979. var paths = this._paths,
  29980. parsedPaths = this._parsedPaths,
  29981. objects = this._objects,
  29982. nObjects = objects.length,
  29983. nCachedObjects = this.nCachedObjects_,
  29984. bindingsForPath = new Array( nObjects );
  29985. index = bindings.length;
  29986. indicesByPath[ path ] = index;
  29987. paths.push( path );
  29988. parsedPaths.push( parsedPath );
  29989. bindings.push( bindingsForPath );
  29990. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29991. var object = objects[ i ];
  29992. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29993. }
  29994. return bindingsForPath;
  29995. },
  29996. unsubscribe_: function ( path ) {
  29997. // tells the group to forget about a property path and no longer
  29998. // update the array previously obtained with 'subscribe_'
  29999. var indicesByPath = this._bindingsIndicesByPath,
  30000. index = indicesByPath[ path ];
  30001. if ( index !== undefined ) {
  30002. var paths = this._paths,
  30003. parsedPaths = this._parsedPaths,
  30004. bindings = this._bindings,
  30005. lastBindingsIndex = bindings.length - 1,
  30006. lastBindings = bindings[ lastBindingsIndex ],
  30007. lastBindingsPath = path[ lastBindingsIndex ];
  30008. indicesByPath[ lastBindingsPath ] = index;
  30009. bindings[ index ] = lastBindings;
  30010. bindings.pop();
  30011. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  30012. parsedPaths.pop();
  30013. paths[ index ] = paths[ lastBindingsIndex ];
  30014. paths.pop();
  30015. }
  30016. }
  30017. } );
  30018. /**
  30019. *
  30020. * Action provided by AnimationMixer for scheduling clip playback on specific
  30021. * objects.
  30022. *
  30023. * @author Ben Houston / http://clara.io/
  30024. * @author David Sarno / http://lighthaus.us/
  30025. * @author tschw
  30026. *
  30027. */
  30028. function AnimationAction( mixer, clip, localRoot ) {
  30029. this._mixer = mixer;
  30030. this._clip = clip;
  30031. this._localRoot = localRoot || null;
  30032. var tracks = clip.tracks,
  30033. nTracks = tracks.length,
  30034. interpolants = new Array( nTracks );
  30035. var interpolantSettings = {
  30036. endingStart: ZeroCurvatureEnding,
  30037. endingEnd: ZeroCurvatureEnding
  30038. };
  30039. for ( var i = 0; i !== nTracks; ++ i ) {
  30040. var interpolant = tracks[ i ].createInterpolant( null );
  30041. interpolants[ i ] = interpolant;
  30042. interpolant.settings = interpolantSettings;
  30043. }
  30044. this._interpolantSettings = interpolantSettings;
  30045. this._interpolants = interpolants; // bound by the mixer
  30046. // inside: PropertyMixer (managed by the mixer)
  30047. this._propertyBindings = new Array( nTracks );
  30048. this._cacheIndex = null; // for the memory manager
  30049. this._byClipCacheIndex = null; // for the memory manager
  30050. this._timeScaleInterpolant = null;
  30051. this._weightInterpolant = null;
  30052. this.loop = LoopRepeat;
  30053. this._loopCount = - 1;
  30054. // global mixer time when the action is to be started
  30055. // it's set back to 'null' upon start of the action
  30056. this._startTime = null;
  30057. // scaled local time of the action
  30058. // gets clamped or wrapped to 0..clip.duration according to loop
  30059. this.time = 0;
  30060. this.timeScale = 1;
  30061. this._effectiveTimeScale = 1;
  30062. this.weight = 1;
  30063. this._effectiveWeight = 1;
  30064. this.repetitions = Infinity; // no. of repetitions when looping
  30065. this.paused = false; // true -> zero effective time scale
  30066. this.enabled = true; // false -> zero effective weight
  30067. this.clampWhenFinished = false;// keep feeding the last frame?
  30068. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  30069. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  30070. }
  30071. Object.assign( AnimationAction.prototype, {
  30072. // State & Scheduling
  30073. play: function () {
  30074. this._mixer._activateAction( this );
  30075. return this;
  30076. },
  30077. stop: function () {
  30078. this._mixer._deactivateAction( this );
  30079. return this.reset();
  30080. },
  30081. reset: function () {
  30082. this.paused = false;
  30083. this.enabled = true;
  30084. this.time = 0; // restart clip
  30085. this._loopCount = - 1;// forget previous loops
  30086. this._startTime = null;// forget scheduling
  30087. return this.stopFading().stopWarping();
  30088. },
  30089. isRunning: function () {
  30090. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  30091. this._startTime === null && this._mixer._isActiveAction( this );
  30092. },
  30093. // return true when play has been called
  30094. isScheduled: function () {
  30095. return this._mixer._isActiveAction( this );
  30096. },
  30097. startAt: function ( time ) {
  30098. this._startTime = time;
  30099. return this;
  30100. },
  30101. setLoop: function ( mode, repetitions ) {
  30102. this.loop = mode;
  30103. this.repetitions = repetitions;
  30104. return this;
  30105. },
  30106. // Weight
  30107. // set the weight stopping any scheduled fading
  30108. // although .enabled = false yields an effective weight of zero, this
  30109. // method does *not* change .enabled, because it would be confusing
  30110. setEffectiveWeight: function ( weight ) {
  30111. this.weight = weight;
  30112. // note: same logic as when updated at runtime
  30113. this._effectiveWeight = this.enabled ? weight : 0;
  30114. return this.stopFading();
  30115. },
  30116. // return the weight considering fading and .enabled
  30117. getEffectiveWeight: function () {
  30118. return this._effectiveWeight;
  30119. },
  30120. fadeIn: function ( duration ) {
  30121. return this._scheduleFading( duration, 0, 1 );
  30122. },
  30123. fadeOut: function ( duration ) {
  30124. return this._scheduleFading( duration, 1, 0 );
  30125. },
  30126. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  30127. fadeOutAction.fadeOut( duration );
  30128. this.fadeIn( duration );
  30129. if ( warp ) {
  30130. var fadeInDuration = this._clip.duration,
  30131. fadeOutDuration = fadeOutAction._clip.duration,
  30132. startEndRatio = fadeOutDuration / fadeInDuration,
  30133. endStartRatio = fadeInDuration / fadeOutDuration;
  30134. fadeOutAction.warp( 1.0, startEndRatio, duration );
  30135. this.warp( endStartRatio, 1.0, duration );
  30136. }
  30137. return this;
  30138. },
  30139. crossFadeTo: function ( fadeInAction, duration, warp ) {
  30140. return fadeInAction.crossFadeFrom( this, duration, warp );
  30141. },
  30142. stopFading: function () {
  30143. var weightInterpolant = this._weightInterpolant;
  30144. if ( weightInterpolant !== null ) {
  30145. this._weightInterpolant = null;
  30146. this._mixer._takeBackControlInterpolant( weightInterpolant );
  30147. }
  30148. return this;
  30149. },
  30150. // Time Scale Control
  30151. // set the time scale stopping any scheduled warping
  30152. // although .paused = true yields an effective time scale of zero, this
  30153. // method does *not* change .paused, because it would be confusing
  30154. setEffectiveTimeScale: function ( timeScale ) {
  30155. this.timeScale = timeScale;
  30156. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  30157. return this.stopWarping();
  30158. },
  30159. // return the time scale considering warping and .paused
  30160. getEffectiveTimeScale: function () {
  30161. return this._effectiveTimeScale;
  30162. },
  30163. setDuration: function ( duration ) {
  30164. this.timeScale = this._clip.duration / duration;
  30165. return this.stopWarping();
  30166. },
  30167. syncWith: function ( action ) {
  30168. this.time = action.time;
  30169. this.timeScale = action.timeScale;
  30170. return this.stopWarping();
  30171. },
  30172. halt: function ( duration ) {
  30173. return this.warp( this._effectiveTimeScale, 0, duration );
  30174. },
  30175. warp: function ( startTimeScale, endTimeScale, duration ) {
  30176. var mixer = this._mixer, now = mixer.time,
  30177. interpolant = this._timeScaleInterpolant,
  30178. timeScale = this.timeScale;
  30179. if ( interpolant === null ) {
  30180. interpolant = mixer._lendControlInterpolant();
  30181. this._timeScaleInterpolant = interpolant;
  30182. }
  30183. var times = interpolant.parameterPositions,
  30184. values = interpolant.sampleValues;
  30185. times[ 0 ] = now;
  30186. times[ 1 ] = now + duration;
  30187. values[ 0 ] = startTimeScale / timeScale;
  30188. values[ 1 ] = endTimeScale / timeScale;
  30189. return this;
  30190. },
  30191. stopWarping: function () {
  30192. var timeScaleInterpolant = this._timeScaleInterpolant;
  30193. if ( timeScaleInterpolant !== null ) {
  30194. this._timeScaleInterpolant = null;
  30195. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  30196. }
  30197. return this;
  30198. },
  30199. // Object Accessors
  30200. getMixer: function () {
  30201. return this._mixer;
  30202. },
  30203. getClip: function () {
  30204. return this._clip;
  30205. },
  30206. getRoot: function () {
  30207. return this._localRoot || this._mixer._root;
  30208. },
  30209. // Interna
  30210. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  30211. // called by the mixer
  30212. if ( ! this.enabled ) {
  30213. // call ._updateWeight() to update ._effectiveWeight
  30214. this._updateWeight( time );
  30215. return;
  30216. }
  30217. var startTime = this._startTime;
  30218. if ( startTime !== null ) {
  30219. // check for scheduled start of action
  30220. var timeRunning = ( time - startTime ) * timeDirection;
  30221. if ( timeRunning < 0 || timeDirection === 0 ) {
  30222. return; // yet to come / don't decide when delta = 0
  30223. }
  30224. // start
  30225. this._startTime = null; // unschedule
  30226. deltaTime = timeDirection * timeRunning;
  30227. }
  30228. // apply time scale and advance time
  30229. deltaTime *= this._updateTimeScale( time );
  30230. var clipTime = this._updateTime( deltaTime );
  30231. // note: _updateTime may disable the action resulting in
  30232. // an effective weight of 0
  30233. var weight = this._updateWeight( time );
  30234. if ( weight > 0 ) {
  30235. var interpolants = this._interpolants;
  30236. var propertyMixers = this._propertyBindings;
  30237. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  30238. interpolants[ j ].evaluate( clipTime );
  30239. propertyMixers[ j ].accumulate( accuIndex, weight );
  30240. }
  30241. }
  30242. },
  30243. _updateWeight: function ( time ) {
  30244. var weight = 0;
  30245. if ( this.enabled ) {
  30246. weight = this.weight;
  30247. var interpolant = this._weightInterpolant;
  30248. if ( interpolant !== null ) {
  30249. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  30250. weight *= interpolantValue;
  30251. if ( time > interpolant.parameterPositions[ 1 ] ) {
  30252. this.stopFading();
  30253. if ( interpolantValue === 0 ) {
  30254. // faded out, disable
  30255. this.enabled = false;
  30256. }
  30257. }
  30258. }
  30259. }
  30260. this._effectiveWeight = weight;
  30261. return weight;
  30262. },
  30263. _updateTimeScale: function ( time ) {
  30264. var timeScale = 0;
  30265. if ( ! this.paused ) {
  30266. timeScale = this.timeScale;
  30267. var interpolant = this._timeScaleInterpolant;
  30268. if ( interpolant !== null ) {
  30269. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  30270. timeScale *= interpolantValue;
  30271. if ( time > interpolant.parameterPositions[ 1 ] ) {
  30272. this.stopWarping();
  30273. if ( timeScale === 0 ) {
  30274. // motion has halted, pause
  30275. this.paused = true;
  30276. } else {
  30277. // warp done - apply final time scale
  30278. this.timeScale = timeScale;
  30279. }
  30280. }
  30281. }
  30282. }
  30283. this._effectiveTimeScale = timeScale;
  30284. return timeScale;
  30285. },
  30286. _updateTime: function ( deltaTime ) {
  30287. var time = this.time + deltaTime;
  30288. var duration = this._clip.duration;
  30289. var loop = this.loop;
  30290. var loopCount = this._loopCount;
  30291. var pingPong = ( loop === LoopPingPong );
  30292. if ( deltaTime === 0 ) {
  30293. if ( loopCount === - 1 ) return time;
  30294. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  30295. }
  30296. if ( loop === LoopOnce ) {
  30297. if ( loopCount === - 1 ) {
  30298. // just started
  30299. this._loopCount = 0;
  30300. this._setEndings( true, true, false );
  30301. }
  30302. handle_stop: {
  30303. if ( time >= duration ) {
  30304. time = duration;
  30305. } else if ( time < 0 ) {
  30306. time = 0;
  30307. } else break handle_stop;
  30308. if ( this.clampWhenFinished ) this.paused = true;
  30309. else this.enabled = false;
  30310. this._mixer.dispatchEvent( {
  30311. type: 'finished', action: this,
  30312. direction: deltaTime < 0 ? - 1 : 1
  30313. } );
  30314. }
  30315. } else { // repetitive Repeat or PingPong
  30316. if ( loopCount === - 1 ) {
  30317. // just started
  30318. if ( deltaTime >= 0 ) {
  30319. loopCount = 0;
  30320. this._setEndings( true, this.repetitions === 0, pingPong );
  30321. } else {
  30322. // when looping in reverse direction, the initial
  30323. // transition through zero counts as a repetition,
  30324. // so leave loopCount at -1
  30325. this._setEndings( this.repetitions === 0, true, pingPong );
  30326. }
  30327. }
  30328. if ( time >= duration || time < 0 ) {
  30329. // wrap around
  30330. var loopDelta = Math.floor( time / duration ); // signed
  30331. time -= duration * loopDelta;
  30332. loopCount += Math.abs( loopDelta );
  30333. var pending = this.repetitions - loopCount;
  30334. if ( pending <= 0 ) {
  30335. // have to stop (switch state, clamp time, fire event)
  30336. if ( this.clampWhenFinished ) this.paused = true;
  30337. else this.enabled = false;
  30338. time = deltaTime > 0 ? duration : 0;
  30339. this._mixer.dispatchEvent( {
  30340. type: 'finished', action: this,
  30341. direction: deltaTime > 0 ? 1 : - 1
  30342. } );
  30343. } else {
  30344. // keep running
  30345. if ( pending === 1 ) {
  30346. // entering the last round
  30347. var atStart = deltaTime < 0;
  30348. this._setEndings( atStart, ! atStart, pingPong );
  30349. } else {
  30350. this._setEndings( false, false, pingPong );
  30351. }
  30352. this._loopCount = loopCount;
  30353. this._mixer.dispatchEvent( {
  30354. type: 'loop', action: this, loopDelta: loopDelta
  30355. } );
  30356. }
  30357. }
  30358. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  30359. // invert time for the "pong round"
  30360. this.time = time;
  30361. return duration - time;
  30362. }
  30363. }
  30364. this.time = time;
  30365. return time;
  30366. },
  30367. _setEndings: function ( atStart, atEnd, pingPong ) {
  30368. var settings = this._interpolantSettings;
  30369. if ( pingPong ) {
  30370. settings.endingStart = ZeroSlopeEnding;
  30371. settings.endingEnd = ZeroSlopeEnding;
  30372. } else {
  30373. // assuming for LoopOnce atStart == atEnd == true
  30374. if ( atStart ) {
  30375. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30376. } else {
  30377. settings.endingStart = WrapAroundEnding;
  30378. }
  30379. if ( atEnd ) {
  30380. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30381. } else {
  30382. settings.endingEnd = WrapAroundEnding;
  30383. }
  30384. }
  30385. },
  30386. _scheduleFading: function ( duration, weightNow, weightThen ) {
  30387. var mixer = this._mixer, now = mixer.time,
  30388. interpolant = this._weightInterpolant;
  30389. if ( interpolant === null ) {
  30390. interpolant = mixer._lendControlInterpolant();
  30391. this._weightInterpolant = interpolant;
  30392. }
  30393. var times = interpolant.parameterPositions,
  30394. values = interpolant.sampleValues;
  30395. times[ 0 ] = now;
  30396. values[ 0 ] = weightNow;
  30397. times[ 1 ] = now + duration;
  30398. values[ 1 ] = weightThen;
  30399. return this;
  30400. }
  30401. } );
  30402. /**
  30403. *
  30404. * Player for AnimationClips.
  30405. *
  30406. *
  30407. * @author Ben Houston / http://clara.io/
  30408. * @author David Sarno / http://lighthaus.us/
  30409. * @author tschw
  30410. */
  30411. function AnimationMixer( root ) {
  30412. this._root = root;
  30413. this._initMemoryManager();
  30414. this._accuIndex = 0;
  30415. this.time = 0;
  30416. this.timeScale = 1.0;
  30417. }
  30418. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  30419. constructor: AnimationMixer,
  30420. _bindAction: function ( action, prototypeAction ) {
  30421. var root = action._localRoot || this._root,
  30422. tracks = action._clip.tracks,
  30423. nTracks = tracks.length,
  30424. bindings = action._propertyBindings,
  30425. interpolants = action._interpolants,
  30426. rootUuid = root.uuid,
  30427. bindingsByRoot = this._bindingsByRootAndName,
  30428. bindingsByName = bindingsByRoot[ rootUuid ];
  30429. if ( bindingsByName === undefined ) {
  30430. bindingsByName = {};
  30431. bindingsByRoot[ rootUuid ] = bindingsByName;
  30432. }
  30433. for ( var i = 0; i !== nTracks; ++ i ) {
  30434. var track = tracks[ i ],
  30435. trackName = track.name,
  30436. binding = bindingsByName[ trackName ];
  30437. if ( binding !== undefined ) {
  30438. bindings[ i ] = binding;
  30439. } else {
  30440. binding = bindings[ i ];
  30441. if ( binding !== undefined ) {
  30442. // existing binding, make sure the cache knows
  30443. if ( binding._cacheIndex === null ) {
  30444. ++ binding.referenceCount;
  30445. this._addInactiveBinding( binding, rootUuid, trackName );
  30446. }
  30447. continue;
  30448. }
  30449. var path = prototypeAction && prototypeAction.
  30450. _propertyBindings[ i ].binding.parsedPath;
  30451. binding = new PropertyMixer(
  30452. PropertyBinding.create( root, trackName, path ),
  30453. track.ValueTypeName, track.getValueSize() );
  30454. ++ binding.referenceCount;
  30455. this._addInactiveBinding( binding, rootUuid, trackName );
  30456. bindings[ i ] = binding;
  30457. }
  30458. interpolants[ i ].resultBuffer = binding.buffer;
  30459. }
  30460. },
  30461. _activateAction: function ( action ) {
  30462. if ( ! this._isActiveAction( action ) ) {
  30463. if ( action._cacheIndex === null ) {
  30464. // this action has been forgotten by the cache, but the user
  30465. // appears to be still using it -> rebind
  30466. var rootUuid = ( action._localRoot || this._root ).uuid,
  30467. clipUuid = action._clip.uuid,
  30468. actionsForClip = this._actionsByClip[ clipUuid ];
  30469. this._bindAction( action,
  30470. actionsForClip && actionsForClip.knownActions[ 0 ] );
  30471. this._addInactiveAction( action, clipUuid, rootUuid );
  30472. }
  30473. var bindings = action._propertyBindings;
  30474. // increment reference counts / sort out state
  30475. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  30476. var binding = bindings[ i ];
  30477. if ( binding.useCount ++ === 0 ) {
  30478. this._lendBinding( binding );
  30479. binding.saveOriginalState();
  30480. }
  30481. }
  30482. this._lendAction( action );
  30483. }
  30484. },
  30485. _deactivateAction: function ( action ) {
  30486. if ( this._isActiveAction( action ) ) {
  30487. var bindings = action._propertyBindings;
  30488. // decrement reference counts / sort out state
  30489. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  30490. var binding = bindings[ i ];
  30491. if ( -- binding.useCount === 0 ) {
  30492. binding.restoreOriginalState();
  30493. this._takeBackBinding( binding );
  30494. }
  30495. }
  30496. this._takeBackAction( action );
  30497. }
  30498. },
  30499. // Memory manager
  30500. _initMemoryManager: function () {
  30501. this._actions = []; // 'nActiveActions' followed by inactive ones
  30502. this._nActiveActions = 0;
  30503. this._actionsByClip = {};
  30504. // inside:
  30505. // {
  30506. // knownActions: Array< AnimationAction > - used as prototypes
  30507. // actionByRoot: AnimationAction - lookup
  30508. // }
  30509. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  30510. this._nActiveBindings = 0;
  30511. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  30512. this._controlInterpolants = []; // same game as above
  30513. this._nActiveControlInterpolants = 0;
  30514. var scope = this;
  30515. this.stats = {
  30516. actions: {
  30517. get total() {
  30518. return scope._actions.length;
  30519. },
  30520. get inUse() {
  30521. return scope._nActiveActions;
  30522. }
  30523. },
  30524. bindings: {
  30525. get total() {
  30526. return scope._bindings.length;
  30527. },
  30528. get inUse() {
  30529. return scope._nActiveBindings;
  30530. }
  30531. },
  30532. controlInterpolants: {
  30533. get total() {
  30534. return scope._controlInterpolants.length;
  30535. },
  30536. get inUse() {
  30537. return scope._nActiveControlInterpolants;
  30538. }
  30539. }
  30540. };
  30541. },
  30542. // Memory management for AnimationAction objects
  30543. _isActiveAction: function ( action ) {
  30544. var index = action._cacheIndex;
  30545. return index !== null && index < this._nActiveActions;
  30546. },
  30547. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  30548. var actions = this._actions,
  30549. actionsByClip = this._actionsByClip,
  30550. actionsForClip = actionsByClip[ clipUuid ];
  30551. if ( actionsForClip === undefined ) {
  30552. actionsForClip = {
  30553. knownActions: [ action ],
  30554. actionByRoot: {}
  30555. };
  30556. action._byClipCacheIndex = 0;
  30557. actionsByClip[ clipUuid ] = actionsForClip;
  30558. } else {
  30559. var knownActions = actionsForClip.knownActions;
  30560. action._byClipCacheIndex = knownActions.length;
  30561. knownActions.push( action );
  30562. }
  30563. action._cacheIndex = actions.length;
  30564. actions.push( action );
  30565. actionsForClip.actionByRoot[ rootUuid ] = action;
  30566. },
  30567. _removeInactiveAction: function ( action ) {
  30568. var actions = this._actions,
  30569. lastInactiveAction = actions[ actions.length - 1 ],
  30570. cacheIndex = action._cacheIndex;
  30571. lastInactiveAction._cacheIndex = cacheIndex;
  30572. actions[ cacheIndex ] = lastInactiveAction;
  30573. actions.pop();
  30574. action._cacheIndex = null;
  30575. var clipUuid = action._clip.uuid,
  30576. actionsByClip = this._actionsByClip,
  30577. actionsForClip = actionsByClip[ clipUuid ],
  30578. knownActionsForClip = actionsForClip.knownActions,
  30579. lastKnownAction =
  30580. knownActionsForClip[ knownActionsForClip.length - 1 ],
  30581. byClipCacheIndex = action._byClipCacheIndex;
  30582. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  30583. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  30584. knownActionsForClip.pop();
  30585. action._byClipCacheIndex = null;
  30586. var actionByRoot = actionsForClip.actionByRoot,
  30587. rootUuid = ( action._localRoot || this._root ).uuid;
  30588. delete actionByRoot[ rootUuid ];
  30589. if ( knownActionsForClip.length === 0 ) {
  30590. delete actionsByClip[ clipUuid ];
  30591. }
  30592. this._removeInactiveBindingsForAction( action );
  30593. },
  30594. _removeInactiveBindingsForAction: function ( action ) {
  30595. var bindings = action._propertyBindings;
  30596. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  30597. var binding = bindings[ i ];
  30598. if ( -- binding.referenceCount === 0 ) {
  30599. this._removeInactiveBinding( binding );
  30600. }
  30601. }
  30602. },
  30603. _lendAction: function ( action ) {
  30604. // [ active actions | inactive actions ]
  30605. // [ active actions >| inactive actions ]
  30606. // s a
  30607. // <-swap->
  30608. // a s
  30609. var actions = this._actions,
  30610. prevIndex = action._cacheIndex,
  30611. lastActiveIndex = this._nActiveActions ++,
  30612. firstInactiveAction = actions[ lastActiveIndex ];
  30613. action._cacheIndex = lastActiveIndex;
  30614. actions[ lastActiveIndex ] = action;
  30615. firstInactiveAction._cacheIndex = prevIndex;
  30616. actions[ prevIndex ] = firstInactiveAction;
  30617. },
  30618. _takeBackAction: function ( action ) {
  30619. // [ active actions | inactive actions ]
  30620. // [ active actions |< inactive actions ]
  30621. // a s
  30622. // <-swap->
  30623. // s a
  30624. var actions = this._actions,
  30625. prevIndex = action._cacheIndex,
  30626. firstInactiveIndex = -- this._nActiveActions,
  30627. lastActiveAction = actions[ firstInactiveIndex ];
  30628. action._cacheIndex = firstInactiveIndex;
  30629. actions[ firstInactiveIndex ] = action;
  30630. lastActiveAction._cacheIndex = prevIndex;
  30631. actions[ prevIndex ] = lastActiveAction;
  30632. },
  30633. // Memory management for PropertyMixer objects
  30634. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  30635. var bindingsByRoot = this._bindingsByRootAndName,
  30636. bindingByName = bindingsByRoot[ rootUuid ],
  30637. bindings = this._bindings;
  30638. if ( bindingByName === undefined ) {
  30639. bindingByName = {};
  30640. bindingsByRoot[ rootUuid ] = bindingByName;
  30641. }
  30642. bindingByName[ trackName ] = binding;
  30643. binding._cacheIndex = bindings.length;
  30644. bindings.push( binding );
  30645. },
  30646. _removeInactiveBinding: function ( binding ) {
  30647. var bindings = this._bindings,
  30648. propBinding = binding.binding,
  30649. rootUuid = propBinding.rootNode.uuid,
  30650. trackName = propBinding.path,
  30651. bindingsByRoot = this._bindingsByRootAndName,
  30652. bindingByName = bindingsByRoot[ rootUuid ],
  30653. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30654. cacheIndex = binding._cacheIndex;
  30655. lastInactiveBinding._cacheIndex = cacheIndex;
  30656. bindings[ cacheIndex ] = lastInactiveBinding;
  30657. bindings.pop();
  30658. delete bindingByName[ trackName ];
  30659. remove_empty_map: {
  30660. for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars
  30661. delete bindingsByRoot[ rootUuid ];
  30662. }
  30663. },
  30664. _lendBinding: function ( binding ) {
  30665. var bindings = this._bindings,
  30666. prevIndex = binding._cacheIndex,
  30667. lastActiveIndex = this._nActiveBindings ++,
  30668. firstInactiveBinding = bindings[ lastActiveIndex ];
  30669. binding._cacheIndex = lastActiveIndex;
  30670. bindings[ lastActiveIndex ] = binding;
  30671. firstInactiveBinding._cacheIndex = prevIndex;
  30672. bindings[ prevIndex ] = firstInactiveBinding;
  30673. },
  30674. _takeBackBinding: function ( binding ) {
  30675. var bindings = this._bindings,
  30676. prevIndex = binding._cacheIndex,
  30677. firstInactiveIndex = -- this._nActiveBindings,
  30678. lastActiveBinding = bindings[ firstInactiveIndex ];
  30679. binding._cacheIndex = firstInactiveIndex;
  30680. bindings[ firstInactiveIndex ] = binding;
  30681. lastActiveBinding._cacheIndex = prevIndex;
  30682. bindings[ prevIndex ] = lastActiveBinding;
  30683. },
  30684. // Memory management of Interpolants for weight and time scale
  30685. _lendControlInterpolant: function () {
  30686. var interpolants = this._controlInterpolants,
  30687. lastActiveIndex = this._nActiveControlInterpolants ++,
  30688. interpolant = interpolants[ lastActiveIndex ];
  30689. if ( interpolant === undefined ) {
  30690. interpolant = new LinearInterpolant(
  30691. new Float32Array( 2 ), new Float32Array( 2 ),
  30692. 1, this._controlInterpolantsResultBuffer );
  30693. interpolant.__cacheIndex = lastActiveIndex;
  30694. interpolants[ lastActiveIndex ] = interpolant;
  30695. }
  30696. return interpolant;
  30697. },
  30698. _takeBackControlInterpolant: function ( interpolant ) {
  30699. var interpolants = this._controlInterpolants,
  30700. prevIndex = interpolant.__cacheIndex,
  30701. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30702. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30703. interpolant.__cacheIndex = firstInactiveIndex;
  30704. interpolants[ firstInactiveIndex ] = interpolant;
  30705. lastActiveInterpolant.__cacheIndex = prevIndex;
  30706. interpolants[ prevIndex ] = lastActiveInterpolant;
  30707. },
  30708. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  30709. // return an action for a clip optionally using a custom root target
  30710. // object (this method allocates a lot of dynamic memory in case a
  30711. // previously unknown clip/root combination is specified)
  30712. clipAction: function ( clip, optionalRoot ) {
  30713. var root = optionalRoot || this._root,
  30714. rootUuid = root.uuid,
  30715. clipObject = typeof clip === 'string' ?
  30716. AnimationClip.findByName( root, clip ) : clip,
  30717. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  30718. actionsForClip = this._actionsByClip[ clipUuid ],
  30719. prototypeAction = null;
  30720. if ( actionsForClip !== undefined ) {
  30721. var existingAction =
  30722. actionsForClip.actionByRoot[ rootUuid ];
  30723. if ( existingAction !== undefined ) {
  30724. return existingAction;
  30725. }
  30726. // we know the clip, so we don't have to parse all
  30727. // the bindings again but can just copy
  30728. prototypeAction = actionsForClip.knownActions[ 0 ];
  30729. // also, take the clip from the prototype action
  30730. if ( clipObject === null )
  30731. clipObject = prototypeAction._clip;
  30732. }
  30733. // clip must be known when specified via string
  30734. if ( clipObject === null ) return null;
  30735. // allocate all resources required to run it
  30736. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  30737. this._bindAction( newAction, prototypeAction );
  30738. // and make the action known to the memory manager
  30739. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30740. return newAction;
  30741. },
  30742. // get an existing action
  30743. existingAction: function ( clip, optionalRoot ) {
  30744. var root = optionalRoot || this._root,
  30745. rootUuid = root.uuid,
  30746. clipObject = typeof clip === 'string' ?
  30747. AnimationClip.findByName( root, clip ) : clip,
  30748. clipUuid = clipObject ? clipObject.uuid : clip,
  30749. actionsForClip = this._actionsByClip[ clipUuid ];
  30750. if ( actionsForClip !== undefined ) {
  30751. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30752. }
  30753. return null;
  30754. },
  30755. // deactivates all previously scheduled actions
  30756. stopAllAction: function () {
  30757. var actions = this._actions,
  30758. nActions = this._nActiveActions,
  30759. bindings = this._bindings,
  30760. nBindings = this._nActiveBindings;
  30761. this._nActiveActions = 0;
  30762. this._nActiveBindings = 0;
  30763. for ( var i = 0; i !== nActions; ++ i ) {
  30764. actions[ i ].reset();
  30765. }
  30766. for ( var i = 0; i !== nBindings; ++ i ) {
  30767. bindings[ i ].useCount = 0;
  30768. }
  30769. return this;
  30770. },
  30771. // advance the time and update apply the animation
  30772. update: function ( deltaTime ) {
  30773. deltaTime *= this.timeScale;
  30774. var actions = this._actions,
  30775. nActions = this._nActiveActions,
  30776. time = this.time += deltaTime,
  30777. timeDirection = Math.sign( deltaTime ),
  30778. accuIndex = this._accuIndex ^= 1;
  30779. // run active actions
  30780. for ( var i = 0; i !== nActions; ++ i ) {
  30781. var action = actions[ i ];
  30782. action._update( time, deltaTime, timeDirection, accuIndex );
  30783. }
  30784. // update scene graph
  30785. var bindings = this._bindings,
  30786. nBindings = this._nActiveBindings;
  30787. for ( var i = 0; i !== nBindings; ++ i ) {
  30788. bindings[ i ].apply( accuIndex );
  30789. }
  30790. return this;
  30791. },
  30792. // return this mixer's root target object
  30793. getRoot: function () {
  30794. return this._root;
  30795. },
  30796. // free all resources specific to a particular clip
  30797. uncacheClip: function ( clip ) {
  30798. var actions = this._actions,
  30799. clipUuid = clip.uuid,
  30800. actionsByClip = this._actionsByClip,
  30801. actionsForClip = actionsByClip[ clipUuid ];
  30802. if ( actionsForClip !== undefined ) {
  30803. // note: just calling _removeInactiveAction would mess up the
  30804. // iteration state and also require updating the state we can
  30805. // just throw away
  30806. var actionsToRemove = actionsForClip.knownActions;
  30807. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30808. var action = actionsToRemove[ i ];
  30809. this._deactivateAction( action );
  30810. var cacheIndex = action._cacheIndex,
  30811. lastInactiveAction = actions[ actions.length - 1 ];
  30812. action._cacheIndex = null;
  30813. action._byClipCacheIndex = null;
  30814. lastInactiveAction._cacheIndex = cacheIndex;
  30815. actions[ cacheIndex ] = lastInactiveAction;
  30816. actions.pop();
  30817. this._removeInactiveBindingsForAction( action );
  30818. }
  30819. delete actionsByClip[ clipUuid ];
  30820. }
  30821. },
  30822. // free all resources specific to a particular root target object
  30823. uncacheRoot: function ( root ) {
  30824. var rootUuid = root.uuid,
  30825. actionsByClip = this._actionsByClip;
  30826. for ( var clipUuid in actionsByClip ) {
  30827. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30828. action = actionByRoot[ rootUuid ];
  30829. if ( action !== undefined ) {
  30830. this._deactivateAction( action );
  30831. this._removeInactiveAction( action );
  30832. }
  30833. }
  30834. var bindingsByRoot = this._bindingsByRootAndName,
  30835. bindingByName = bindingsByRoot[ rootUuid ];
  30836. if ( bindingByName !== undefined ) {
  30837. for ( var trackName in bindingByName ) {
  30838. var binding = bindingByName[ trackName ];
  30839. binding.restoreOriginalState();
  30840. this._removeInactiveBinding( binding );
  30841. }
  30842. }
  30843. },
  30844. // remove a targeted clip from the cache
  30845. uncacheAction: function ( clip, optionalRoot ) {
  30846. var action = this.existingAction( clip, optionalRoot );
  30847. if ( action !== null ) {
  30848. this._deactivateAction( action );
  30849. this._removeInactiveAction( action );
  30850. }
  30851. }
  30852. } );
  30853. /**
  30854. * @author mrdoob / http://mrdoob.com/
  30855. */
  30856. function Uniform( value ) {
  30857. if ( typeof value === 'string' ) {
  30858. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  30859. value = arguments[ 1 ];
  30860. }
  30861. this.value = value;
  30862. }
  30863. Uniform.prototype.clone = function () {
  30864. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30865. };
  30866. /**
  30867. * @author benaadams / https://twitter.com/ben_a_adams
  30868. */
  30869. function InstancedBufferGeometry() {
  30870. BufferGeometry.call( this );
  30871. this.type = 'InstancedBufferGeometry';
  30872. this.maxInstancedCount = undefined;
  30873. }
  30874. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  30875. constructor: InstancedBufferGeometry,
  30876. isInstancedBufferGeometry: true,
  30877. copy: function ( source ) {
  30878. BufferGeometry.prototype.copy.call( this, source );
  30879. this.maxInstancedCount = source.maxInstancedCount;
  30880. return this;
  30881. },
  30882. clone: function () {
  30883. return new this.constructor().copy( this );
  30884. }
  30885. } );
  30886. /**
  30887. * @author benaadams / https://twitter.com/ben_a_adams
  30888. */
  30889. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  30890. InterleavedBuffer.call( this, array, stride );
  30891. this.meshPerAttribute = meshPerAttribute || 1;
  30892. }
  30893. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  30894. constructor: InstancedInterleavedBuffer,
  30895. isInstancedInterleavedBuffer: true,
  30896. copy: function ( source ) {
  30897. InterleavedBuffer.prototype.copy.call( this, source );
  30898. this.meshPerAttribute = source.meshPerAttribute;
  30899. return this;
  30900. }
  30901. } );
  30902. /**
  30903. * @author benaadams / https://twitter.com/ben_a_adams
  30904. */
  30905. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  30906. if ( typeof ( normalized ) === 'number' ) {
  30907. meshPerAttribute = normalized;
  30908. normalized = false;
  30909. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  30910. }
  30911. BufferAttribute.call( this, array, itemSize, normalized );
  30912. this.meshPerAttribute = meshPerAttribute || 1;
  30913. }
  30914. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  30915. constructor: InstancedBufferAttribute,
  30916. isInstancedBufferAttribute: true,
  30917. copy: function ( source ) {
  30918. BufferAttribute.prototype.copy.call( this, source );
  30919. this.meshPerAttribute = source.meshPerAttribute;
  30920. return this;
  30921. }
  30922. } );
  30923. /**
  30924. * @author mrdoob / http://mrdoob.com/
  30925. * @author bhouston / http://clara.io/
  30926. * @author stephomi / http://stephaneginier.com/
  30927. */
  30928. function Raycaster( origin, direction, near, far ) {
  30929. this.ray = new Ray( origin, direction );
  30930. // direction is assumed to be normalized (for accurate distance calculations)
  30931. this.near = near || 0;
  30932. this.far = far || Infinity;
  30933. this.params = {
  30934. Mesh: {},
  30935. Line: {},
  30936. LOD: {},
  30937. Points: { threshold: 1 },
  30938. Sprite: {}
  30939. };
  30940. Object.defineProperties( this.params, {
  30941. PointCloud: {
  30942. get: function () {
  30943. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  30944. return this.Points;
  30945. }
  30946. }
  30947. } );
  30948. }
  30949. function ascSort( a, b ) {
  30950. return a.distance - b.distance;
  30951. }
  30952. function intersectObject( object, raycaster, intersects, recursive ) {
  30953. if ( object.visible === false ) return;
  30954. object.raycast( raycaster, intersects );
  30955. if ( recursive === true ) {
  30956. var children = object.children;
  30957. for ( var i = 0, l = children.length; i < l; i ++ ) {
  30958. intersectObject( children[ i ], raycaster, intersects, true );
  30959. }
  30960. }
  30961. }
  30962. Object.assign( Raycaster.prototype, {
  30963. linePrecision: 1,
  30964. set: function ( origin, direction ) {
  30965. // direction is assumed to be normalized (for accurate distance calculations)
  30966. this.ray.set( origin, direction );
  30967. },
  30968. setFromCamera: function ( coords, camera ) {
  30969. if ( ( camera && camera.isPerspectiveCamera ) ) {
  30970. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30971. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30972. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  30973. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30974. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30975. } else {
  30976. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  30977. }
  30978. },
  30979. intersectObject: function ( object, recursive, optionalTarget ) {
  30980. var intersects = optionalTarget || [];
  30981. intersectObject( object, this, intersects, recursive );
  30982. intersects.sort( ascSort );
  30983. return intersects;
  30984. },
  30985. intersectObjects: function ( objects, recursive, optionalTarget ) {
  30986. var intersects = optionalTarget || [];
  30987. if ( Array.isArray( objects ) === false ) {
  30988. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  30989. return intersects;
  30990. }
  30991. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  30992. intersectObject( objects[ i ], this, intersects, recursive );
  30993. }
  30994. intersects.sort( ascSort );
  30995. return intersects;
  30996. }
  30997. } );
  30998. /**
  30999. * @author bhouston / http://clara.io
  31000. * @author WestLangley / http://github.com/WestLangley
  31001. *
  31002. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  31003. *
  31004. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  31005. * The azimuthal angle (theta) is measured from the positive z-axiz.
  31006. */
  31007. function Spherical( radius, phi, theta ) {
  31008. this.radius = ( radius !== undefined ) ? radius : 1.0;
  31009. this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
  31010. this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle
  31011. return this;
  31012. }
  31013. Object.assign( Spherical.prototype, {
  31014. set: function ( radius, phi, theta ) {
  31015. this.radius = radius;
  31016. this.phi = phi;
  31017. this.theta = theta;
  31018. return this;
  31019. },
  31020. clone: function () {
  31021. return new this.constructor().copy( this );
  31022. },
  31023. copy: function ( other ) {
  31024. this.radius = other.radius;
  31025. this.phi = other.phi;
  31026. this.theta = other.theta;
  31027. return this;
  31028. },
  31029. // restrict phi to be betwee EPS and PI-EPS
  31030. makeSafe: function () {
  31031. var EPS = 0.000001;
  31032. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  31033. return this;
  31034. },
  31035. setFromVector3: function ( v ) {
  31036. return this.setFromCartesianCoords( v.x, v.y, v.z );
  31037. },
  31038. setFromCartesianCoords: function ( x, y, z ) {
  31039. this.radius = Math.sqrt( x * x + y * y + z * z );
  31040. if ( this.radius === 0 ) {
  31041. this.theta = 0;
  31042. this.phi = 0;
  31043. } else {
  31044. this.theta = Math.atan2( x, z );
  31045. this.phi = Math.acos( _Math.clamp( y / this.radius, - 1, 1 ) );
  31046. }
  31047. return this;
  31048. }
  31049. } );
  31050. /**
  31051. * @author Mugen87 / https://github.com/Mugen87
  31052. *
  31053. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  31054. *
  31055. */
  31056. function Cylindrical( radius, theta, y ) {
  31057. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  31058. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  31059. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  31060. return this;
  31061. }
  31062. Object.assign( Cylindrical.prototype, {
  31063. set: function ( radius, theta, y ) {
  31064. this.radius = radius;
  31065. this.theta = theta;
  31066. this.y = y;
  31067. return this;
  31068. },
  31069. clone: function () {
  31070. return new this.constructor().copy( this );
  31071. },
  31072. copy: function ( other ) {
  31073. this.radius = other.radius;
  31074. this.theta = other.theta;
  31075. this.y = other.y;
  31076. return this;
  31077. },
  31078. setFromVector3: function ( v ) {
  31079. return this.setFromCartesianCoords( v.x, v.y, v.z );
  31080. },
  31081. setFromCartesianCoords: function ( x, y, z ) {
  31082. this.radius = Math.sqrt( x * x + z * z );
  31083. this.theta = Math.atan2( x, z );
  31084. this.y = y;
  31085. return this;
  31086. }
  31087. } );
  31088. /**
  31089. * @author bhouston / http://clara.io
  31090. */
  31091. function Box2( min, max ) {
  31092. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  31093. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  31094. }
  31095. Object.assign( Box2.prototype, {
  31096. set: function ( min, max ) {
  31097. this.min.copy( min );
  31098. this.max.copy( max );
  31099. return this;
  31100. },
  31101. setFromPoints: function ( points ) {
  31102. this.makeEmpty();
  31103. for ( var i = 0, il = points.length; i < il; i ++ ) {
  31104. this.expandByPoint( points[ i ] );
  31105. }
  31106. return this;
  31107. },
  31108. setFromCenterAndSize: function () {
  31109. var v1 = new Vector2();
  31110. return function setFromCenterAndSize( center, size ) {
  31111. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  31112. this.min.copy( center ).sub( halfSize );
  31113. this.max.copy( center ).add( halfSize );
  31114. return this;
  31115. };
  31116. }(),
  31117. clone: function () {
  31118. return new this.constructor().copy( this );
  31119. },
  31120. copy: function ( box ) {
  31121. this.min.copy( box.min );
  31122. this.max.copy( box.max );
  31123. return this;
  31124. },
  31125. makeEmpty: function () {
  31126. this.min.x = this.min.y = + Infinity;
  31127. this.max.x = this.max.y = - Infinity;
  31128. return this;
  31129. },
  31130. isEmpty: function () {
  31131. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  31132. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  31133. },
  31134. getCenter: function ( target ) {
  31135. if ( target === undefined ) {
  31136. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  31137. target = new Vector2();
  31138. }
  31139. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  31140. },
  31141. getSize: function ( target ) {
  31142. if ( target === undefined ) {
  31143. console.warn( 'THREE.Box2: .getSize() target is now required' );
  31144. target = new Vector2();
  31145. }
  31146. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  31147. },
  31148. expandByPoint: function ( point ) {
  31149. this.min.min( point );
  31150. this.max.max( point );
  31151. return this;
  31152. },
  31153. expandByVector: function ( vector ) {
  31154. this.min.sub( vector );
  31155. this.max.add( vector );
  31156. return this;
  31157. },
  31158. expandByScalar: function ( scalar ) {
  31159. this.min.addScalar( - scalar );
  31160. this.max.addScalar( scalar );
  31161. return this;
  31162. },
  31163. containsPoint: function ( point ) {
  31164. return point.x < this.min.x || point.x > this.max.x ||
  31165. point.y < this.min.y || point.y > this.max.y ? false : true;
  31166. },
  31167. containsBox: function ( box ) {
  31168. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  31169. this.min.y <= box.min.y && box.max.y <= this.max.y;
  31170. },
  31171. getParameter: function ( point, target ) {
  31172. // This can potentially have a divide by zero if the box
  31173. // has a size dimension of 0.
  31174. if ( target === undefined ) {
  31175. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  31176. target = new Vector2();
  31177. }
  31178. return target.set(
  31179. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  31180. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  31181. );
  31182. },
  31183. intersectsBox: function ( box ) {
  31184. // using 4 splitting planes to rule out intersections
  31185. return box.max.x < this.min.x || box.min.x > this.max.x ||
  31186. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  31187. },
  31188. clampPoint: function ( point, target ) {
  31189. if ( target === undefined ) {
  31190. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  31191. target = new Vector2();
  31192. }
  31193. return target.copy( point ).clamp( this.min, this.max );
  31194. },
  31195. distanceToPoint: function () {
  31196. var v1 = new Vector2();
  31197. return function distanceToPoint( point ) {
  31198. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  31199. return clampedPoint.sub( point ).length();
  31200. };
  31201. }(),
  31202. intersect: function ( box ) {
  31203. this.min.max( box.min );
  31204. this.max.min( box.max );
  31205. return this;
  31206. },
  31207. union: function ( box ) {
  31208. this.min.min( box.min );
  31209. this.max.max( box.max );
  31210. return this;
  31211. },
  31212. translate: function ( offset ) {
  31213. this.min.add( offset );
  31214. this.max.add( offset );
  31215. return this;
  31216. },
  31217. equals: function ( box ) {
  31218. return box.min.equals( this.min ) && box.max.equals( this.max );
  31219. }
  31220. } );
  31221. /**
  31222. * @author bhouston / http://clara.io
  31223. */
  31224. function Line3( start, end ) {
  31225. this.start = ( start !== undefined ) ? start : new Vector3();
  31226. this.end = ( end !== undefined ) ? end : new Vector3();
  31227. }
  31228. Object.assign( Line3.prototype, {
  31229. set: function ( start, end ) {
  31230. this.start.copy( start );
  31231. this.end.copy( end );
  31232. return this;
  31233. },
  31234. clone: function () {
  31235. return new this.constructor().copy( this );
  31236. },
  31237. copy: function ( line ) {
  31238. this.start.copy( line.start );
  31239. this.end.copy( line.end );
  31240. return this;
  31241. },
  31242. getCenter: function ( target ) {
  31243. if ( target === undefined ) {
  31244. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  31245. target = new Vector3();
  31246. }
  31247. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  31248. },
  31249. delta: function ( target ) {
  31250. if ( target === undefined ) {
  31251. console.warn( 'THREE.Line3: .delta() target is now required' );
  31252. target = new Vector3();
  31253. }
  31254. return target.subVectors( this.end, this.start );
  31255. },
  31256. distanceSq: function () {
  31257. return this.start.distanceToSquared( this.end );
  31258. },
  31259. distance: function () {
  31260. return this.start.distanceTo( this.end );
  31261. },
  31262. at: function ( t, target ) {
  31263. if ( target === undefined ) {
  31264. console.warn( 'THREE.Line3: .at() target is now required' );
  31265. target = new Vector3();
  31266. }
  31267. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31268. },
  31269. closestPointToPointParameter: function () {
  31270. var startP = new Vector3();
  31271. var startEnd = new Vector3();
  31272. return function closestPointToPointParameter( point, clampToLine ) {
  31273. startP.subVectors( point, this.start );
  31274. startEnd.subVectors( this.end, this.start );
  31275. var startEnd2 = startEnd.dot( startEnd );
  31276. var startEnd_startP = startEnd.dot( startP );
  31277. var t = startEnd_startP / startEnd2;
  31278. if ( clampToLine ) {
  31279. t = _Math.clamp( t, 0, 1 );
  31280. }
  31281. return t;
  31282. };
  31283. }(),
  31284. closestPointToPoint: function ( point, clampToLine, target ) {
  31285. var t = this.closestPointToPointParameter( point, clampToLine );
  31286. if ( target === undefined ) {
  31287. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  31288. target = new Vector3();
  31289. }
  31290. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31291. },
  31292. applyMatrix4: function ( matrix ) {
  31293. this.start.applyMatrix4( matrix );
  31294. this.end.applyMatrix4( matrix );
  31295. return this;
  31296. },
  31297. equals: function ( line ) {
  31298. return line.start.equals( this.start ) && line.end.equals( this.end );
  31299. }
  31300. } );
  31301. /**
  31302. * @author alteredq / http://alteredqualia.com/
  31303. */
  31304. function ImmediateRenderObject( material ) {
  31305. Object3D.call( this );
  31306. this.material = material;
  31307. this.render = function ( /* renderCallback */ ) {};
  31308. }
  31309. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  31310. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  31311. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  31312. /**
  31313. * @author mrdoob / http://mrdoob.com/
  31314. * @author WestLangley / http://github.com/WestLangley
  31315. */
  31316. function VertexNormalsHelper( object, size, hex, linewidth ) {
  31317. this.object = object;
  31318. this.size = ( size !== undefined ) ? size : 1;
  31319. var color = ( hex !== undefined ) ? hex : 0xff0000;
  31320. var width = ( linewidth !== undefined ) ? linewidth : 1;
  31321. //
  31322. var nNormals = 0;
  31323. var objGeometry = this.object.geometry;
  31324. if ( objGeometry && objGeometry.isGeometry ) {
  31325. nNormals = objGeometry.faces.length * 3;
  31326. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  31327. nNormals = objGeometry.attributes.normal.count;
  31328. }
  31329. //
  31330. var geometry = new BufferGeometry();
  31331. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  31332. geometry.addAttribute( 'position', positions );
  31333. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  31334. //
  31335. this.matrixAutoUpdate = false;
  31336. this.update();
  31337. }
  31338. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  31339. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  31340. VertexNormalsHelper.prototype.update = ( function () {
  31341. var v1 = new Vector3();
  31342. var v2 = new Vector3();
  31343. var normalMatrix = new Matrix3();
  31344. return function update() {
  31345. var keys = [ 'a', 'b', 'c' ];
  31346. this.object.updateMatrixWorld( true );
  31347. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  31348. var matrixWorld = this.object.matrixWorld;
  31349. var position = this.geometry.attributes.position;
  31350. //
  31351. var objGeometry = this.object.geometry;
  31352. if ( objGeometry && objGeometry.isGeometry ) {
  31353. var vertices = objGeometry.vertices;
  31354. var faces = objGeometry.faces;
  31355. var idx = 0;
  31356. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  31357. var face = faces[ i ];
  31358. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  31359. var vertex = vertices[ face[ keys[ j ] ] ];
  31360. var normal = face.vertexNormals[ j ];
  31361. v1.copy( vertex ).applyMatrix4( matrixWorld );
  31362. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  31363. position.setXYZ( idx, v1.x, v1.y, v1.z );
  31364. idx = idx + 1;
  31365. position.setXYZ( idx, v2.x, v2.y, v2.z );
  31366. idx = idx + 1;
  31367. }
  31368. }
  31369. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  31370. var objPos = objGeometry.attributes.position;
  31371. var objNorm = objGeometry.attributes.normal;
  31372. var idx = 0;
  31373. // for simplicity, ignore index and drawcalls, and render every normal
  31374. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  31375. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  31376. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  31377. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  31378. position.setXYZ( idx, v1.x, v1.y, v1.z );
  31379. idx = idx + 1;
  31380. position.setXYZ( idx, v2.x, v2.y, v2.z );
  31381. idx = idx + 1;
  31382. }
  31383. }
  31384. position.needsUpdate = true;
  31385. };
  31386. }() );
  31387. /**
  31388. * @author alteredq / http://alteredqualia.com/
  31389. * @author mrdoob / http://mrdoob.com/
  31390. * @author WestLangley / http://github.com/WestLangley
  31391. */
  31392. function SpotLightHelper( light, color ) {
  31393. Object3D.call( this );
  31394. this.light = light;
  31395. this.light.updateMatrixWorld();
  31396. this.matrix = light.matrixWorld;
  31397. this.matrixAutoUpdate = false;
  31398. this.color = color;
  31399. var geometry = new BufferGeometry();
  31400. var positions = [
  31401. 0, 0, 0, 0, 0, 1,
  31402. 0, 0, 0, 1, 0, 1,
  31403. 0, 0, 0, - 1, 0, 1,
  31404. 0, 0, 0, 0, 1, 1,
  31405. 0, 0, 0, 0, - 1, 1
  31406. ];
  31407. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  31408. var p1 = ( i / l ) * Math.PI * 2;
  31409. var p2 = ( j / l ) * Math.PI * 2;
  31410. positions.push(
  31411. Math.cos( p1 ), Math.sin( p1 ), 1,
  31412. Math.cos( p2 ), Math.sin( p2 ), 1
  31413. );
  31414. }
  31415. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31416. var material = new LineBasicMaterial( { fog: false } );
  31417. this.cone = new LineSegments( geometry, material );
  31418. this.add( this.cone );
  31419. this.update();
  31420. }
  31421. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  31422. SpotLightHelper.prototype.constructor = SpotLightHelper;
  31423. SpotLightHelper.prototype.dispose = function () {
  31424. this.cone.geometry.dispose();
  31425. this.cone.material.dispose();
  31426. };
  31427. SpotLightHelper.prototype.update = function () {
  31428. var vector = new Vector3();
  31429. return function update() {
  31430. this.light.updateMatrixWorld();
  31431. var coneLength = this.light.distance ? this.light.distance : 1000;
  31432. var coneWidth = coneLength * Math.tan( this.light.angle );
  31433. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  31434. vector.setFromMatrixPosition( this.light.target.matrixWorld );
  31435. this.cone.lookAt( vector );
  31436. if ( this.color !== undefined ) {
  31437. this.cone.material.color.set( this.color );
  31438. } else {
  31439. this.cone.material.color.copy( this.light.color );
  31440. }
  31441. };
  31442. }();
  31443. /**
  31444. * @author Sean Griffin / http://twitter.com/sgrif
  31445. * @author Michael Guerrero / http://realitymeltdown.com
  31446. * @author mrdoob / http://mrdoob.com/
  31447. * @author ikerr / http://verold.com
  31448. * @author Mugen87 / https://github.com/Mugen87
  31449. */
  31450. function getBoneList( object ) {
  31451. var boneList = [];
  31452. if ( object && object.isBone ) {
  31453. boneList.push( object );
  31454. }
  31455. for ( var i = 0; i < object.children.length; i ++ ) {
  31456. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  31457. }
  31458. return boneList;
  31459. }
  31460. function SkeletonHelper( object ) {
  31461. var bones = getBoneList( object );
  31462. var geometry = new BufferGeometry();
  31463. var vertices = [];
  31464. var colors = [];
  31465. var color1 = new Color( 0, 0, 1 );
  31466. var color2 = new Color( 0, 1, 0 );
  31467. for ( var i = 0; i < bones.length; i ++ ) {
  31468. var bone = bones[ i ];
  31469. if ( bone.parent && bone.parent.isBone ) {
  31470. vertices.push( 0, 0, 0 );
  31471. vertices.push( 0, 0, 0 );
  31472. colors.push( color1.r, color1.g, color1.b );
  31473. colors.push( color2.r, color2.g, color2.b );
  31474. }
  31475. }
  31476. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31477. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31478. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  31479. LineSegments.call( this, geometry, material );
  31480. this.root = object;
  31481. this.bones = bones;
  31482. this.matrix = object.matrixWorld;
  31483. this.matrixAutoUpdate = false;
  31484. }
  31485. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  31486. SkeletonHelper.prototype.constructor = SkeletonHelper;
  31487. SkeletonHelper.prototype.updateMatrixWorld = function () {
  31488. var vector = new Vector3();
  31489. var boneMatrix = new Matrix4();
  31490. var matrixWorldInv = new Matrix4();
  31491. return function updateMatrixWorld( force ) {
  31492. var bones = this.bones;
  31493. var geometry = this.geometry;
  31494. var position = geometry.getAttribute( 'position' );
  31495. matrixWorldInv.getInverse( this.root.matrixWorld );
  31496. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  31497. var bone = bones[ i ];
  31498. if ( bone.parent && bone.parent.isBone ) {
  31499. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  31500. vector.setFromMatrixPosition( boneMatrix );
  31501. position.setXYZ( j, vector.x, vector.y, vector.z );
  31502. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  31503. vector.setFromMatrixPosition( boneMatrix );
  31504. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  31505. j += 2;
  31506. }
  31507. }
  31508. geometry.getAttribute( 'position' ).needsUpdate = true;
  31509. Object3D.prototype.updateMatrixWorld.call( this, force );
  31510. };
  31511. }();
  31512. /**
  31513. * @author alteredq / http://alteredqualia.com/
  31514. * @author mrdoob / http://mrdoob.com/
  31515. */
  31516. function PointLightHelper( light, sphereSize, color ) {
  31517. this.light = light;
  31518. this.light.updateMatrixWorld();
  31519. this.color = color;
  31520. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  31521. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  31522. Mesh.call( this, geometry, material );
  31523. this.matrix = this.light.matrixWorld;
  31524. this.matrixAutoUpdate = false;
  31525. this.update();
  31526. /*
  31527. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  31528. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  31529. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  31530. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  31531. var d = light.distance;
  31532. if ( d === 0.0 ) {
  31533. this.lightDistance.visible = false;
  31534. } else {
  31535. this.lightDistance.scale.set( d, d, d );
  31536. }
  31537. this.add( this.lightDistance );
  31538. */
  31539. }
  31540. PointLightHelper.prototype = Object.create( Mesh.prototype );
  31541. PointLightHelper.prototype.constructor = PointLightHelper;
  31542. PointLightHelper.prototype.dispose = function () {
  31543. this.geometry.dispose();
  31544. this.material.dispose();
  31545. };
  31546. PointLightHelper.prototype.update = function () {
  31547. if ( this.color !== undefined ) {
  31548. this.material.color.set( this.color );
  31549. } else {
  31550. this.material.color.copy( this.light.color );
  31551. }
  31552. /*
  31553. var d = this.light.distance;
  31554. if ( d === 0.0 ) {
  31555. this.lightDistance.visible = false;
  31556. } else {
  31557. this.lightDistance.visible = true;
  31558. this.lightDistance.scale.set( d, d, d );
  31559. }
  31560. */
  31561. };
  31562. /**
  31563. * @author abelnation / http://github.com/abelnation
  31564. * @author Mugen87 / http://github.com/Mugen87
  31565. * @author WestLangley / http://github.com/WestLangley
  31566. *
  31567. * This helper must be added as a child of the light
  31568. */
  31569. function RectAreaLightHelper( light, color ) {
  31570. this.type = 'RectAreaLightHelper';
  31571. this.light = light;
  31572. this.color = color; // optional hardwired color for the helper
  31573. var positions = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  31574. var geometry = new BufferGeometry();
  31575. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31576. geometry.computeBoundingSphere();
  31577. var material = new LineBasicMaterial( { fog: false } );
  31578. Line.call( this, geometry, material );
  31579. //
  31580. var positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31581. var geometry2 = new BufferGeometry();
  31582. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31583. geometry2.computeBoundingSphere();
  31584. this.add( new Mesh( geometry2, new MeshBasicMaterial( { side: BackSide, fog: false } ) ) );
  31585. this.update();
  31586. }
  31587. RectAreaLightHelper.prototype = Object.create( Line.prototype );
  31588. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  31589. RectAreaLightHelper.prototype.update = function () {
  31590. this.scale.set( 0.5 * this.light.width, 0.5 * this.light.height, 1 );
  31591. if ( this.color !== undefined ) {
  31592. this.material.color.set( this.color );
  31593. this.children[ 0 ].material.color.set( this.color );
  31594. } else {
  31595. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  31596. // prevent hue shift
  31597. var c = this.material.color;
  31598. var max = Math.max( c.r, c.g, c.b );
  31599. if ( max > 1 ) c.multiplyScalar( 1 / max );
  31600. this.children[ 0 ].material.color.copy( this.material.color );
  31601. }
  31602. };
  31603. RectAreaLightHelper.prototype.dispose = function () {
  31604. this.geometry.dispose();
  31605. this.material.dispose();
  31606. this.children[ 0 ].geometry.dispose();
  31607. this.children[ 0 ].material.dispose();
  31608. };
  31609. /**
  31610. * @author alteredq / http://alteredqualia.com/
  31611. * @author mrdoob / http://mrdoob.com/
  31612. * @author Mugen87 / https://github.com/Mugen87
  31613. */
  31614. function HemisphereLightHelper( light, size, color ) {
  31615. Object3D.call( this );
  31616. this.light = light;
  31617. this.light.updateMatrixWorld();
  31618. this.matrix = light.matrixWorld;
  31619. this.matrixAutoUpdate = false;
  31620. this.color = color;
  31621. var geometry = new OctahedronBufferGeometry( size );
  31622. geometry.rotateY( Math.PI * 0.5 );
  31623. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  31624. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  31625. var position = geometry.getAttribute( 'position' );
  31626. var colors = new Float32Array( position.count * 3 );
  31627. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  31628. this.add( new Mesh( geometry, this.material ) );
  31629. this.update();
  31630. }
  31631. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  31632. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  31633. HemisphereLightHelper.prototype.dispose = function () {
  31634. this.children[ 0 ].geometry.dispose();
  31635. this.children[ 0 ].material.dispose();
  31636. };
  31637. HemisphereLightHelper.prototype.update = function () {
  31638. var vector = new Vector3();
  31639. var color1 = new Color();
  31640. var color2 = new Color();
  31641. return function update() {
  31642. var mesh = this.children[ 0 ];
  31643. if ( this.color !== undefined ) {
  31644. this.material.color.set( this.color );
  31645. } else {
  31646. var colors = mesh.geometry.getAttribute( 'color' );
  31647. color1.copy( this.light.color );
  31648. color2.copy( this.light.groundColor );
  31649. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  31650. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  31651. colors.setXYZ( i, color.r, color.g, color.b );
  31652. }
  31653. colors.needsUpdate = true;
  31654. }
  31655. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  31656. };
  31657. }();
  31658. /**
  31659. * @author mrdoob / http://mrdoob.com/
  31660. */
  31661. function GridHelper( size, divisions, color1, color2 ) {
  31662. size = size || 10;
  31663. divisions = divisions || 10;
  31664. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  31665. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  31666. var center = divisions / 2;
  31667. var step = size / divisions;
  31668. var halfSize = size / 2;
  31669. var vertices = [], colors = [];
  31670. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  31671. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  31672. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  31673. var color = i === center ? color1 : color2;
  31674. color.toArray( colors, j ); j += 3;
  31675. color.toArray( colors, j ); j += 3;
  31676. color.toArray( colors, j ); j += 3;
  31677. color.toArray( colors, j ); j += 3;
  31678. }
  31679. var geometry = new BufferGeometry();
  31680. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31681. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31682. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  31683. LineSegments.call( this, geometry, material );
  31684. }
  31685. GridHelper.prototype = Object.create( LineSegments.prototype );
  31686. GridHelper.prototype.constructor = GridHelper;
  31687. /**
  31688. * @author mrdoob / http://mrdoob.com/
  31689. * @author Mugen87 / http://github.com/Mugen87
  31690. * @author Hectate / http://www.github.com/Hectate
  31691. */
  31692. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  31693. radius = radius || 10;
  31694. radials = radials || 16;
  31695. circles = circles || 8;
  31696. divisions = divisions || 64;
  31697. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  31698. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  31699. var vertices = [];
  31700. var colors = [];
  31701. var x, z;
  31702. var v, i, j, r, color;
  31703. // create the radials
  31704. for ( i = 0; i <= radials; i ++ ) {
  31705. v = ( i / radials ) * ( Math.PI * 2 );
  31706. x = Math.sin( v ) * radius;
  31707. z = Math.cos( v ) * radius;
  31708. vertices.push( 0, 0, 0 );
  31709. vertices.push( x, 0, z );
  31710. color = ( i & 1 ) ? color1 : color2;
  31711. colors.push( color.r, color.g, color.b );
  31712. colors.push( color.r, color.g, color.b );
  31713. }
  31714. // create the circles
  31715. for ( i = 0; i <= circles; i ++ ) {
  31716. color = ( i & 1 ) ? color1 : color2;
  31717. r = radius - ( radius / circles * i );
  31718. for ( j = 0; j < divisions; j ++ ) {
  31719. // first vertex
  31720. v = ( j / divisions ) * ( Math.PI * 2 );
  31721. x = Math.sin( v ) * r;
  31722. z = Math.cos( v ) * r;
  31723. vertices.push( x, 0, z );
  31724. colors.push( color.r, color.g, color.b );
  31725. // second vertex
  31726. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  31727. x = Math.sin( v ) * r;
  31728. z = Math.cos( v ) * r;
  31729. vertices.push( x, 0, z );
  31730. colors.push( color.r, color.g, color.b );
  31731. }
  31732. }
  31733. var geometry = new BufferGeometry();
  31734. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31735. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31736. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  31737. LineSegments.call( this, geometry, material );
  31738. }
  31739. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  31740. PolarGridHelper.prototype.constructor = PolarGridHelper;
  31741. /**
  31742. * @author Mugen87 / http://github.com/Mugen87
  31743. */
  31744. function PositionalAudioHelper( audio, range, divisionsInnerAngle, divisionsOuterAngle ) {
  31745. this.audio = audio;
  31746. this.range = range || 1;
  31747. this.divisionsInnerAngle = divisionsInnerAngle || 16;
  31748. this.divisionsOuterAngle = divisionsOuterAngle || 2;
  31749. var geometry = new BufferGeometry();
  31750. var divisions = this.divisionsInnerAngle + this.divisionsOuterAngle * 2;
  31751. var positions = new Float32Array( ( divisions * 3 + 3 ) * 3 );
  31752. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31753. var materialInnerAngle = new LineBasicMaterial( { color: 0x00ff00 } );
  31754. var materialOuterAngle = new LineBasicMaterial( { color: 0xffff00 } );
  31755. Line.call( this, geometry, [ materialOuterAngle, materialInnerAngle ] );
  31756. this.update();
  31757. }
  31758. PositionalAudioHelper.prototype = Object.create( Line.prototype );
  31759. PositionalAudioHelper.prototype.constructor = PositionalAudioHelper;
  31760. PositionalAudioHelper.prototype.update = function () {
  31761. var audio = this.audio;
  31762. var range = this.range;
  31763. var divisionsInnerAngle = this.divisionsInnerAngle;
  31764. var divisionsOuterAngle = this.divisionsOuterAngle;
  31765. var coneInnerAngle = _Math.degToRad( audio.panner.coneInnerAngle );
  31766. var coneOuterAngle = _Math.degToRad( audio.panner.coneOuterAngle );
  31767. var halfConeInnerAngle = coneInnerAngle / 2;
  31768. var halfConeOuterAngle = coneOuterAngle / 2;
  31769. var start = 0;
  31770. var count = 0;
  31771. var i, stride;
  31772. var geometry = this.geometry;
  31773. var positionAttribute = geometry.attributes.position;
  31774. geometry.clearGroups();
  31775. //
  31776. function generateSegment( from, to, divisions, materialIndex ) {
  31777. var step = ( to - from ) / divisions;
  31778. positionAttribute.setXYZ( start, 0, 0, 0 );
  31779. count ++;
  31780. for ( i = from; i < to; i += step ) {
  31781. stride = start + count;
  31782. positionAttribute.setXYZ( stride, Math.sin( i ) * range, 0, Math.cos( i ) * range );
  31783. positionAttribute.setXYZ( stride + 1, Math.sin( Math.min( i + step, to ) ) * range, 0, Math.cos( Math.min( i + step, to ) ) * range );
  31784. positionAttribute.setXYZ( stride + 2, 0, 0, 0 );
  31785. count += 3;
  31786. }
  31787. geometry.addGroup( start, count, materialIndex );
  31788. start += count;
  31789. count = 0;
  31790. }
  31791. //
  31792. generateSegment( - halfConeOuterAngle, - halfConeInnerAngle, divisionsOuterAngle, 0 );
  31793. generateSegment( - halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1 );
  31794. generateSegment( halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0 );
  31795. //
  31796. positionAttribute.needsUpdate = true;
  31797. if ( coneInnerAngle === coneOuterAngle ) this.material[ 0 ].visible = false;
  31798. };
  31799. PositionalAudioHelper.prototype.dispose = function () {
  31800. this.geometry.dispose();
  31801. this.material[ 0 ].dispose();
  31802. this.material[ 1 ].dispose();
  31803. };
  31804. /**
  31805. * @author mrdoob / http://mrdoob.com/
  31806. * @author WestLangley / http://github.com/WestLangley
  31807. */
  31808. function FaceNormalsHelper( object, size, hex, linewidth ) {
  31809. // FaceNormalsHelper only supports THREE.Geometry
  31810. this.object = object;
  31811. this.size = ( size !== undefined ) ? size : 1;
  31812. var color = ( hex !== undefined ) ? hex : 0xffff00;
  31813. var width = ( linewidth !== undefined ) ? linewidth : 1;
  31814. //
  31815. var nNormals = 0;
  31816. var objGeometry = this.object.geometry;
  31817. if ( objGeometry && objGeometry.isGeometry ) {
  31818. nNormals = objGeometry.faces.length;
  31819. } else {
  31820. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  31821. }
  31822. //
  31823. var geometry = new BufferGeometry();
  31824. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  31825. geometry.addAttribute( 'position', positions );
  31826. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  31827. //
  31828. this.matrixAutoUpdate = false;
  31829. this.update();
  31830. }
  31831. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  31832. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  31833. FaceNormalsHelper.prototype.update = ( function () {
  31834. var v1 = new Vector3();
  31835. var v2 = new Vector3();
  31836. var normalMatrix = new Matrix3();
  31837. return function update() {
  31838. this.object.updateMatrixWorld( true );
  31839. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  31840. var matrixWorld = this.object.matrixWorld;
  31841. var position = this.geometry.attributes.position;
  31842. //
  31843. var objGeometry = this.object.geometry;
  31844. var vertices = objGeometry.vertices;
  31845. var faces = objGeometry.faces;
  31846. var idx = 0;
  31847. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  31848. var face = faces[ i ];
  31849. var normal = face.normal;
  31850. v1.copy( vertices[ face.a ] )
  31851. .add( vertices[ face.b ] )
  31852. .add( vertices[ face.c ] )
  31853. .divideScalar( 3 )
  31854. .applyMatrix4( matrixWorld );
  31855. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  31856. position.setXYZ( idx, v1.x, v1.y, v1.z );
  31857. idx = idx + 1;
  31858. position.setXYZ( idx, v2.x, v2.y, v2.z );
  31859. idx = idx + 1;
  31860. }
  31861. position.needsUpdate = true;
  31862. };
  31863. }() );
  31864. /**
  31865. * @author alteredq / http://alteredqualia.com/
  31866. * @author mrdoob / http://mrdoob.com/
  31867. * @author WestLangley / http://github.com/WestLangley
  31868. */
  31869. function DirectionalLightHelper( light, size, color ) {
  31870. Object3D.call( this );
  31871. this.light = light;
  31872. this.light.updateMatrixWorld();
  31873. this.matrix = light.matrixWorld;
  31874. this.matrixAutoUpdate = false;
  31875. this.color = color;
  31876. if ( size === undefined ) size = 1;
  31877. var geometry = new BufferGeometry();
  31878. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  31879. - size, size, 0,
  31880. size, size, 0,
  31881. size, - size, 0,
  31882. - size, - size, 0,
  31883. - size, size, 0
  31884. ], 3 ) );
  31885. var material = new LineBasicMaterial( { fog: false } );
  31886. this.lightPlane = new Line( geometry, material );
  31887. this.add( this.lightPlane );
  31888. geometry = new BufferGeometry();
  31889. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  31890. this.targetLine = new Line( geometry, material );
  31891. this.add( this.targetLine );
  31892. this.update();
  31893. }
  31894. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  31895. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  31896. DirectionalLightHelper.prototype.dispose = function () {
  31897. this.lightPlane.geometry.dispose();
  31898. this.lightPlane.material.dispose();
  31899. this.targetLine.geometry.dispose();
  31900. this.targetLine.material.dispose();
  31901. };
  31902. DirectionalLightHelper.prototype.update = function () {
  31903. var v1 = new Vector3();
  31904. var v2 = new Vector3();
  31905. var v3 = new Vector3();
  31906. return function update() {
  31907. v1.setFromMatrixPosition( this.light.matrixWorld );
  31908. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  31909. v3.subVectors( v2, v1 );
  31910. this.lightPlane.lookAt( v2 );
  31911. if ( this.color !== undefined ) {
  31912. this.lightPlane.material.color.set( this.color );
  31913. this.targetLine.material.color.set( this.color );
  31914. } else {
  31915. this.lightPlane.material.color.copy( this.light.color );
  31916. this.targetLine.material.color.copy( this.light.color );
  31917. }
  31918. this.targetLine.lookAt( v2 );
  31919. this.targetLine.scale.z = v3.length();
  31920. };
  31921. }();
  31922. /**
  31923. * @author alteredq / http://alteredqualia.com/
  31924. * @author Mugen87 / https://github.com/Mugen87
  31925. *
  31926. * - shows frustum, line of sight and up of the camera
  31927. * - suitable for fast updates
  31928. * - based on frustum visualization in lightgl.js shadowmap example
  31929. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  31930. */
  31931. function CameraHelper( camera ) {
  31932. var geometry = new BufferGeometry();
  31933. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  31934. var vertices = [];
  31935. var colors = [];
  31936. var pointMap = {};
  31937. // colors
  31938. var colorFrustum = new Color( 0xffaa00 );
  31939. var colorCone = new Color( 0xff0000 );
  31940. var colorUp = new Color( 0x00aaff );
  31941. var colorTarget = new Color( 0xffffff );
  31942. var colorCross = new Color( 0x333333 );
  31943. // near
  31944. addLine( 'n1', 'n2', colorFrustum );
  31945. addLine( 'n2', 'n4', colorFrustum );
  31946. addLine( 'n4', 'n3', colorFrustum );
  31947. addLine( 'n3', 'n1', colorFrustum );
  31948. // far
  31949. addLine( 'f1', 'f2', colorFrustum );
  31950. addLine( 'f2', 'f4', colorFrustum );
  31951. addLine( 'f4', 'f3', colorFrustum );
  31952. addLine( 'f3', 'f1', colorFrustum );
  31953. // sides
  31954. addLine( 'n1', 'f1', colorFrustum );
  31955. addLine( 'n2', 'f2', colorFrustum );
  31956. addLine( 'n3', 'f3', colorFrustum );
  31957. addLine( 'n4', 'f4', colorFrustum );
  31958. // cone
  31959. addLine( 'p', 'n1', colorCone );
  31960. addLine( 'p', 'n2', colorCone );
  31961. addLine( 'p', 'n3', colorCone );
  31962. addLine( 'p', 'n4', colorCone );
  31963. // up
  31964. addLine( 'u1', 'u2', colorUp );
  31965. addLine( 'u2', 'u3', colorUp );
  31966. addLine( 'u3', 'u1', colorUp );
  31967. // target
  31968. addLine( 'c', 't', colorTarget );
  31969. addLine( 'p', 'c', colorCross );
  31970. // cross
  31971. addLine( 'cn1', 'cn2', colorCross );
  31972. addLine( 'cn3', 'cn4', colorCross );
  31973. addLine( 'cf1', 'cf2', colorCross );
  31974. addLine( 'cf3', 'cf4', colorCross );
  31975. function addLine( a, b, color ) {
  31976. addPoint( a, color );
  31977. addPoint( b, color );
  31978. }
  31979. function addPoint( id, color ) {
  31980. vertices.push( 0, 0, 0 );
  31981. colors.push( color.r, color.g, color.b );
  31982. if ( pointMap[ id ] === undefined ) {
  31983. pointMap[ id ] = [];
  31984. }
  31985. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  31986. }
  31987. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31988. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31989. LineSegments.call( this, geometry, material );
  31990. this.camera = camera;
  31991. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  31992. this.matrix = camera.matrixWorld;
  31993. this.matrixAutoUpdate = false;
  31994. this.pointMap = pointMap;
  31995. this.update();
  31996. }
  31997. CameraHelper.prototype = Object.create( LineSegments.prototype );
  31998. CameraHelper.prototype.constructor = CameraHelper;
  31999. CameraHelper.prototype.update = function () {
  32000. var geometry, pointMap;
  32001. var vector = new Vector3();
  32002. var camera = new Camera();
  32003. function setPoint( point, x, y, z ) {
  32004. vector.set( x, y, z ).unproject( camera );
  32005. var points = pointMap[ point ];
  32006. if ( points !== undefined ) {
  32007. var position = geometry.getAttribute( 'position' );
  32008. for ( var i = 0, l = points.length; i < l; i ++ ) {
  32009. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  32010. }
  32011. }
  32012. }
  32013. return function update() {
  32014. geometry = this.geometry;
  32015. pointMap = this.pointMap;
  32016. var w = 1, h = 1;
  32017. // we need just camera projection matrix
  32018. // world matrix must be identity
  32019. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  32020. // center / target
  32021. setPoint( 'c', 0, 0, - 1 );
  32022. setPoint( 't', 0, 0, 1 );
  32023. // near
  32024. setPoint( 'n1', - w, - h, - 1 );
  32025. setPoint( 'n2', w, - h, - 1 );
  32026. setPoint( 'n3', - w, h, - 1 );
  32027. setPoint( 'n4', w, h, - 1 );
  32028. // far
  32029. setPoint( 'f1', - w, - h, 1 );
  32030. setPoint( 'f2', w, - h, 1 );
  32031. setPoint( 'f3', - w, h, 1 );
  32032. setPoint( 'f4', w, h, 1 );
  32033. // up
  32034. setPoint( 'u1', w * 0.7, h * 1.1, - 1 );
  32035. setPoint( 'u2', - w * 0.7, h * 1.1, - 1 );
  32036. setPoint( 'u3', 0, h * 2, - 1 );
  32037. // cross
  32038. setPoint( 'cf1', - w, 0, 1 );
  32039. setPoint( 'cf2', w, 0, 1 );
  32040. setPoint( 'cf3', 0, - h, 1 );
  32041. setPoint( 'cf4', 0, h, 1 );
  32042. setPoint( 'cn1', - w, 0, - 1 );
  32043. setPoint( 'cn2', w, 0, - 1 );
  32044. setPoint( 'cn3', 0, - h, - 1 );
  32045. setPoint( 'cn4', 0, h, - 1 );
  32046. geometry.getAttribute( 'position' ).needsUpdate = true;
  32047. };
  32048. }();
  32049. /**
  32050. * @author mrdoob / http://mrdoob.com/
  32051. * @author Mugen87 / http://github.com/Mugen87
  32052. */
  32053. function BoxHelper( object, color ) {
  32054. this.object = object;
  32055. if ( color === undefined ) color = 0xffff00;
  32056. 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 ] );
  32057. var positions = new Float32Array( 8 * 3 );
  32058. var geometry = new BufferGeometry();
  32059. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32060. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  32061. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  32062. this.matrixAutoUpdate = false;
  32063. this.update();
  32064. }
  32065. BoxHelper.prototype = Object.create( LineSegments.prototype );
  32066. BoxHelper.prototype.constructor = BoxHelper;
  32067. BoxHelper.prototype.update = ( function () {
  32068. var box = new Box3();
  32069. return function update( object ) {
  32070. if ( object !== undefined ) {
  32071. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  32072. }
  32073. if ( this.object !== undefined ) {
  32074. box.setFromObject( this.object );
  32075. }
  32076. if ( box.isEmpty() ) return;
  32077. var min = box.min;
  32078. var max = box.max;
  32079. /*
  32080. 5____4
  32081. 1/___0/|
  32082. | 6__|_7
  32083. 2/___3/
  32084. 0: max.x, max.y, max.z
  32085. 1: min.x, max.y, max.z
  32086. 2: min.x, min.y, max.z
  32087. 3: max.x, min.y, max.z
  32088. 4: max.x, max.y, min.z
  32089. 5: min.x, max.y, min.z
  32090. 6: min.x, min.y, min.z
  32091. 7: max.x, min.y, min.z
  32092. */
  32093. var position = this.geometry.attributes.position;
  32094. var array = position.array;
  32095. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  32096. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  32097. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  32098. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  32099. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  32100. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  32101. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  32102. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  32103. position.needsUpdate = true;
  32104. this.geometry.computeBoundingSphere();
  32105. };
  32106. } )();
  32107. BoxHelper.prototype.setFromObject = function ( object ) {
  32108. this.object = object;
  32109. this.update();
  32110. return this;
  32111. };
  32112. BoxHelper.prototype.copy = function ( source ) {
  32113. LineSegments.prototype.copy.call( this, source );
  32114. this.object = source.object;
  32115. return this;
  32116. };
  32117. BoxHelper.prototype.clone = function () {
  32118. return new this.constructor().copy( this );
  32119. };
  32120. /**
  32121. * @author WestLangley / http://github.com/WestLangley
  32122. */
  32123. function Box3Helper( box, hex ) {
  32124. this.type = 'Box3Helper';
  32125. this.box = box;
  32126. var color = ( hex !== undefined ) ? hex : 0xffff00;
  32127. 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 ] );
  32128. 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 ];
  32129. var geometry = new BufferGeometry();
  32130. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32131. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32132. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  32133. this.geometry.computeBoundingSphere();
  32134. }
  32135. Box3Helper.prototype = Object.create( LineSegments.prototype );
  32136. Box3Helper.prototype.constructor = Box3Helper;
  32137. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  32138. var box = this.box;
  32139. if ( box.isEmpty() ) return;
  32140. box.getCenter( this.position );
  32141. box.getSize( this.scale );
  32142. this.scale.multiplyScalar( 0.5 );
  32143. Object3D.prototype.updateMatrixWorld.call( this, force );
  32144. };
  32145. /**
  32146. * @author WestLangley / http://github.com/WestLangley
  32147. */
  32148. function PlaneHelper( plane, size, hex ) {
  32149. this.type = 'PlaneHelper';
  32150. this.plane = plane;
  32151. this.size = ( size === undefined ) ? 1 : size;
  32152. var color = ( hex !== undefined ) ? hex : 0xffff00;
  32153. 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 ];
  32154. var geometry = new BufferGeometry();
  32155. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32156. geometry.computeBoundingSphere();
  32157. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  32158. //
  32159. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  32160. var geometry2 = new BufferGeometry();
  32161. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  32162. geometry2.computeBoundingSphere();
  32163. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  32164. }
  32165. PlaneHelper.prototype = Object.create( Line.prototype );
  32166. PlaneHelper.prototype.constructor = PlaneHelper;
  32167. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  32168. var scale = - this.plane.constant;
  32169. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  32170. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  32171. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  32172. this.lookAt( this.plane.normal );
  32173. Object3D.prototype.updateMatrixWorld.call( this, force );
  32174. };
  32175. /**
  32176. * @author WestLangley / http://github.com/WestLangley
  32177. * @author zz85 / http://github.com/zz85
  32178. * @author bhouston / http://clara.io
  32179. *
  32180. * Creates an arrow for visualizing directions
  32181. *
  32182. * Parameters:
  32183. * dir - Vector3
  32184. * origin - Vector3
  32185. * length - Number
  32186. * color - color in hex value
  32187. * headLength - Number
  32188. * headWidth - Number
  32189. */
  32190. var lineGeometry, coneGeometry;
  32191. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  32192. // dir is assumed to be normalized
  32193. Object3D.call( this );
  32194. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  32195. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  32196. if ( length === undefined ) length = 1;
  32197. if ( color === undefined ) color = 0xffff00;
  32198. if ( headLength === undefined ) headLength = 0.2 * length;
  32199. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  32200. if ( lineGeometry === undefined ) {
  32201. lineGeometry = new BufferGeometry();
  32202. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  32203. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  32204. coneGeometry.translate( 0, - 0.5, 0 );
  32205. }
  32206. this.position.copy( origin );
  32207. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  32208. this.line.matrixAutoUpdate = false;
  32209. this.add( this.line );
  32210. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  32211. this.cone.matrixAutoUpdate = false;
  32212. this.add( this.cone );
  32213. this.setDirection( dir );
  32214. this.setLength( length, headLength, headWidth );
  32215. }
  32216. ArrowHelper.prototype = Object.create( Object3D.prototype );
  32217. ArrowHelper.prototype.constructor = ArrowHelper;
  32218. ArrowHelper.prototype.setDirection = ( function () {
  32219. var axis = new Vector3();
  32220. var radians;
  32221. return function setDirection( dir ) {
  32222. // dir is assumed to be normalized
  32223. if ( dir.y > 0.99999 ) {
  32224. this.quaternion.set( 0, 0, 0, 1 );
  32225. } else if ( dir.y < - 0.99999 ) {
  32226. this.quaternion.set( 1, 0, 0, 0 );
  32227. } else {
  32228. axis.set( dir.z, 0, - dir.x ).normalize();
  32229. radians = Math.acos( dir.y );
  32230. this.quaternion.setFromAxisAngle( axis, radians );
  32231. }
  32232. };
  32233. }() );
  32234. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  32235. if ( headLength === undefined ) headLength = 0.2 * length;
  32236. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  32237. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  32238. this.line.updateMatrix();
  32239. this.cone.scale.set( headWidth, headLength, headWidth );
  32240. this.cone.position.y = length;
  32241. this.cone.updateMatrix();
  32242. };
  32243. ArrowHelper.prototype.setColor = function ( color ) {
  32244. this.line.material.color.copy( color );
  32245. this.cone.material.color.copy( color );
  32246. };
  32247. ArrowHelper.prototype.copy = function ( source ) {
  32248. Object3D.prototype.copy.call( this, source, false );
  32249. this.line.copy( source.line );
  32250. this.cone.copy( source.cone );
  32251. return this;
  32252. };
  32253. ArrowHelper.prototype.clone = function () {
  32254. return new this.constructor().copy( this );
  32255. };
  32256. /**
  32257. * @author sroucheray / http://sroucheray.org/
  32258. * @author mrdoob / http://mrdoob.com/
  32259. */
  32260. function AxesHelper( size ) {
  32261. size = size || 1;
  32262. var vertices = [
  32263. 0, 0, 0, size, 0, 0,
  32264. 0, 0, 0, 0, size, 0,
  32265. 0, 0, 0, 0, 0, size
  32266. ];
  32267. var colors = [
  32268. 1, 0, 0, 1, 0.6, 0,
  32269. 0, 1, 0, 0.6, 1, 0,
  32270. 0, 0, 1, 0, 0.6, 1
  32271. ];
  32272. var geometry = new BufferGeometry();
  32273. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32274. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32275. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  32276. LineSegments.call( this, geometry, material );
  32277. }
  32278. AxesHelper.prototype = Object.create( LineSegments.prototype );
  32279. AxesHelper.prototype.constructor = AxesHelper;
  32280. /**
  32281. * @author mrdoob / http://mrdoob.com/
  32282. */
  32283. function Face4( a, b, c, d, normal, color, materialIndex ) {
  32284. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  32285. return new Face3( a, b, c, normal, color, materialIndex );
  32286. }
  32287. var LineStrip = 0;
  32288. var LinePieces = 1;
  32289. function MeshFaceMaterial( materials ) {
  32290. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  32291. return materials;
  32292. }
  32293. function MultiMaterial( materials ) {
  32294. if ( materials === undefined ) materials = [];
  32295. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  32296. materials.isMultiMaterial = true;
  32297. materials.materials = materials;
  32298. materials.clone = function () {
  32299. return materials.slice();
  32300. };
  32301. return materials;
  32302. }
  32303. function PointCloud( geometry, material ) {
  32304. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  32305. return new Points( geometry, material );
  32306. }
  32307. function Particle( material ) {
  32308. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  32309. return new Sprite( material );
  32310. }
  32311. function ParticleSystem( geometry, material ) {
  32312. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  32313. return new Points( geometry, material );
  32314. }
  32315. function PointCloudMaterial( parameters ) {
  32316. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  32317. return new PointsMaterial( parameters );
  32318. }
  32319. function ParticleBasicMaterial( parameters ) {
  32320. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  32321. return new PointsMaterial( parameters );
  32322. }
  32323. function ParticleSystemMaterial( parameters ) {
  32324. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  32325. return new PointsMaterial( parameters );
  32326. }
  32327. function Vertex( x, y, z ) {
  32328. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  32329. return new Vector3( x, y, z );
  32330. }
  32331. //
  32332. function DynamicBufferAttribute( array, itemSize ) {
  32333. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  32334. return new BufferAttribute( array, itemSize ).setDynamic( true );
  32335. }
  32336. function Int8Attribute( array, itemSize ) {
  32337. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  32338. return new Int8BufferAttribute( array, itemSize );
  32339. }
  32340. function Uint8Attribute( array, itemSize ) {
  32341. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  32342. return new Uint8BufferAttribute( array, itemSize );
  32343. }
  32344. function Uint8ClampedAttribute( array, itemSize ) {
  32345. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  32346. return new Uint8ClampedBufferAttribute( array, itemSize );
  32347. }
  32348. function Int16Attribute( array, itemSize ) {
  32349. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  32350. return new Int16BufferAttribute( array, itemSize );
  32351. }
  32352. function Uint16Attribute( array, itemSize ) {
  32353. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  32354. return new Uint16BufferAttribute( array, itemSize );
  32355. }
  32356. function Int32Attribute( array, itemSize ) {
  32357. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  32358. return new Int32BufferAttribute( array, itemSize );
  32359. }
  32360. function Uint32Attribute( array, itemSize ) {
  32361. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  32362. return new Uint32BufferAttribute( array, itemSize );
  32363. }
  32364. function Float32Attribute( array, itemSize ) {
  32365. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  32366. return new Float32BufferAttribute( array, itemSize );
  32367. }
  32368. function Float64Attribute( array, itemSize ) {
  32369. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  32370. return new Float64BufferAttribute( array, itemSize );
  32371. }
  32372. //
  32373. Curve.create = function ( construct, getPoint ) {
  32374. console.log( 'THREE.Curve.create() has been deprecated' );
  32375. construct.prototype = Object.create( Curve.prototype );
  32376. construct.prototype.constructor = construct;
  32377. construct.prototype.getPoint = getPoint;
  32378. return construct;
  32379. };
  32380. //
  32381. Object.assign( CurvePath.prototype, {
  32382. createPointsGeometry: function ( divisions ) {
  32383. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  32384. // generate geometry from path points (for Line or Points objects)
  32385. var pts = this.getPoints( divisions );
  32386. return this.createGeometry( pts );
  32387. },
  32388. createSpacedPointsGeometry: function ( divisions ) {
  32389. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  32390. // generate geometry from equidistant sampling along the path
  32391. var pts = this.getSpacedPoints( divisions );
  32392. return this.createGeometry( pts );
  32393. },
  32394. createGeometry: function ( points ) {
  32395. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  32396. var geometry = new Geometry();
  32397. for ( var i = 0, l = points.length; i < l; i ++ ) {
  32398. var point = points[ i ];
  32399. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  32400. }
  32401. return geometry;
  32402. }
  32403. } );
  32404. //
  32405. Object.assign( Path.prototype, {
  32406. fromPoints: function ( points ) {
  32407. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  32408. this.setFromPoints( points );
  32409. }
  32410. } );
  32411. //
  32412. function ClosedSplineCurve3( points ) {
  32413. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  32414. CatmullRomCurve3.call( this, points );
  32415. this.type = 'catmullrom';
  32416. this.closed = true;
  32417. }
  32418. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  32419. //
  32420. function SplineCurve3( points ) {
  32421. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  32422. CatmullRomCurve3.call( this, points );
  32423. this.type = 'catmullrom';
  32424. }
  32425. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  32426. //
  32427. function Spline( points ) {
  32428. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  32429. CatmullRomCurve3.call( this, points );
  32430. this.type = 'catmullrom';
  32431. }
  32432. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  32433. Object.assign( Spline.prototype, {
  32434. initFromArray: function ( /* a */ ) {
  32435. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  32436. },
  32437. getControlPointsArray: function ( /* optionalTarget */ ) {
  32438. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  32439. },
  32440. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  32441. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  32442. }
  32443. } );
  32444. //
  32445. function AxisHelper( size ) {
  32446. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  32447. return new AxesHelper( size );
  32448. }
  32449. function BoundingBoxHelper( object, color ) {
  32450. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  32451. return new BoxHelper( object, color );
  32452. }
  32453. function EdgesHelper( object, hex ) {
  32454. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  32455. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  32456. }
  32457. GridHelper.prototype.setColors = function () {
  32458. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  32459. };
  32460. SkeletonHelper.prototype.update = function () {
  32461. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  32462. };
  32463. function WireframeHelper( object, hex ) {
  32464. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  32465. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  32466. }
  32467. //
  32468. Object.assign( Loader.prototype, {
  32469. extractUrlBase: function ( url ) {
  32470. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  32471. return LoaderUtils.extractUrlBase( url );
  32472. }
  32473. } );
  32474. function XHRLoader( manager ) {
  32475. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  32476. return new FileLoader( manager );
  32477. }
  32478. function BinaryTextureLoader( manager ) {
  32479. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  32480. return new DataTextureLoader( manager );
  32481. }
  32482. Object.assign( ObjectLoader.prototype, {
  32483. setTexturePath: function ( value ) {
  32484. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  32485. return this.setResourcePath( value );
  32486. }
  32487. } );
  32488. //
  32489. Object.assign( Box2.prototype, {
  32490. center: function ( optionalTarget ) {
  32491. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  32492. return this.getCenter( optionalTarget );
  32493. },
  32494. empty: function () {
  32495. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  32496. return this.isEmpty();
  32497. },
  32498. isIntersectionBox: function ( box ) {
  32499. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  32500. return this.intersectsBox( box );
  32501. },
  32502. size: function ( optionalTarget ) {
  32503. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  32504. return this.getSize( optionalTarget );
  32505. }
  32506. } );
  32507. Object.assign( Box3.prototype, {
  32508. center: function ( optionalTarget ) {
  32509. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  32510. return this.getCenter( optionalTarget );
  32511. },
  32512. empty: function () {
  32513. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  32514. return this.isEmpty();
  32515. },
  32516. isIntersectionBox: function ( box ) {
  32517. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  32518. return this.intersectsBox( box );
  32519. },
  32520. isIntersectionSphere: function ( sphere ) {
  32521. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  32522. return this.intersectsSphere( sphere );
  32523. },
  32524. size: function ( optionalTarget ) {
  32525. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  32526. return this.getSize( optionalTarget );
  32527. }
  32528. } );
  32529. Line3.prototype.center = function ( optionalTarget ) {
  32530. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  32531. return this.getCenter( optionalTarget );
  32532. };
  32533. Object.assign( _Math, {
  32534. random16: function () {
  32535. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  32536. return Math.random();
  32537. },
  32538. nearestPowerOfTwo: function ( value ) {
  32539. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  32540. return _Math.floorPowerOfTwo( value );
  32541. },
  32542. nextPowerOfTwo: function ( value ) {
  32543. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  32544. return _Math.ceilPowerOfTwo( value );
  32545. }
  32546. } );
  32547. Object.assign( Matrix3.prototype, {
  32548. flattenToArrayOffset: function ( array, offset ) {
  32549. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  32550. return this.toArray( array, offset );
  32551. },
  32552. multiplyVector3: function ( vector ) {
  32553. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  32554. return vector.applyMatrix3( this );
  32555. },
  32556. multiplyVector3Array: function ( /* a */ ) {
  32557. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  32558. },
  32559. applyToBuffer: function ( buffer /*, offset, length */ ) {
  32560. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  32561. return this.applyToBufferAttribute( buffer );
  32562. },
  32563. applyToVector3Array: function ( /* array, offset, length */ ) {
  32564. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  32565. }
  32566. } );
  32567. Object.assign( Matrix4.prototype, {
  32568. extractPosition: function ( m ) {
  32569. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  32570. return this.copyPosition( m );
  32571. },
  32572. flattenToArrayOffset: function ( array, offset ) {
  32573. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  32574. return this.toArray( array, offset );
  32575. },
  32576. getPosition: function () {
  32577. var v1;
  32578. return function getPosition() {
  32579. if ( v1 === undefined ) v1 = new Vector3();
  32580. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  32581. return v1.setFromMatrixColumn( this, 3 );
  32582. };
  32583. }(),
  32584. setRotationFromQuaternion: function ( q ) {
  32585. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  32586. return this.makeRotationFromQuaternion( q );
  32587. },
  32588. multiplyToArray: function () {
  32589. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  32590. },
  32591. multiplyVector3: function ( vector ) {
  32592. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  32593. return vector.applyMatrix4( this );
  32594. },
  32595. multiplyVector4: function ( vector ) {
  32596. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  32597. return vector.applyMatrix4( this );
  32598. },
  32599. multiplyVector3Array: function ( /* a */ ) {
  32600. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  32601. },
  32602. rotateAxis: function ( v ) {
  32603. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  32604. v.transformDirection( this );
  32605. },
  32606. crossVector: function ( vector ) {
  32607. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  32608. return vector.applyMatrix4( this );
  32609. },
  32610. translate: function () {
  32611. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  32612. },
  32613. rotateX: function () {
  32614. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  32615. },
  32616. rotateY: function () {
  32617. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  32618. },
  32619. rotateZ: function () {
  32620. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  32621. },
  32622. rotateByAxis: function () {
  32623. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  32624. },
  32625. applyToBuffer: function ( buffer /*, offset, length */ ) {
  32626. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  32627. return this.applyToBufferAttribute( buffer );
  32628. },
  32629. applyToVector3Array: function ( /* array, offset, length */ ) {
  32630. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  32631. },
  32632. makeFrustum: function ( left, right, bottom, top, near, far ) {
  32633. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  32634. return this.makePerspective( left, right, top, bottom, near, far );
  32635. }
  32636. } );
  32637. Plane.prototype.isIntersectionLine = function ( line ) {
  32638. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  32639. return this.intersectsLine( line );
  32640. };
  32641. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  32642. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  32643. return vector.applyQuaternion( this );
  32644. };
  32645. Object.assign( Ray.prototype, {
  32646. isIntersectionBox: function ( box ) {
  32647. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  32648. return this.intersectsBox( box );
  32649. },
  32650. isIntersectionPlane: function ( plane ) {
  32651. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  32652. return this.intersectsPlane( plane );
  32653. },
  32654. isIntersectionSphere: function ( sphere ) {
  32655. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  32656. return this.intersectsSphere( sphere );
  32657. }
  32658. } );
  32659. Object.assign( Triangle.prototype, {
  32660. area: function () {
  32661. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  32662. return this.getArea();
  32663. },
  32664. barycoordFromPoint: function ( point, target ) {
  32665. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  32666. return this.getBarycoord( point, target );
  32667. },
  32668. midpoint: function ( target ) {
  32669. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  32670. return this.getMidpoint( target );
  32671. },
  32672. normal: function ( target ) {
  32673. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  32674. return this.getNormal( target );
  32675. },
  32676. plane: function ( target ) {
  32677. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  32678. return this.getPlane( target );
  32679. }
  32680. } );
  32681. Object.assign( Triangle, {
  32682. barycoordFromPoint: function ( point, a, b, c, target ) {
  32683. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  32684. return Triangle.getBarycoord( point, a, b, c, target );
  32685. },
  32686. normal: function ( a, b, c, target ) {
  32687. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  32688. return Triangle.getNormal( a, b, c, target );
  32689. }
  32690. } );
  32691. Object.assign( Shape.prototype, {
  32692. extractAllPoints: function ( divisions ) {
  32693. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  32694. return this.extractPoints( divisions );
  32695. },
  32696. extrude: function ( options ) {
  32697. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  32698. return new ExtrudeGeometry( this, options );
  32699. },
  32700. makeGeometry: function ( options ) {
  32701. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  32702. return new ShapeGeometry( this, options );
  32703. }
  32704. } );
  32705. Object.assign( Vector2.prototype, {
  32706. fromAttribute: function ( attribute, index, offset ) {
  32707. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  32708. return this.fromBufferAttribute( attribute, index, offset );
  32709. },
  32710. distanceToManhattan: function ( v ) {
  32711. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  32712. return this.manhattanDistanceTo( v );
  32713. },
  32714. lengthManhattan: function () {
  32715. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  32716. return this.manhattanLength();
  32717. }
  32718. } );
  32719. Object.assign( Vector3.prototype, {
  32720. setEulerFromRotationMatrix: function () {
  32721. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  32722. },
  32723. setEulerFromQuaternion: function () {
  32724. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  32725. },
  32726. getPositionFromMatrix: function ( m ) {
  32727. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  32728. return this.setFromMatrixPosition( m );
  32729. },
  32730. getScaleFromMatrix: function ( m ) {
  32731. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  32732. return this.setFromMatrixScale( m );
  32733. },
  32734. getColumnFromMatrix: function ( index, matrix ) {
  32735. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  32736. return this.setFromMatrixColumn( matrix, index );
  32737. },
  32738. applyProjection: function ( m ) {
  32739. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  32740. return this.applyMatrix4( m );
  32741. },
  32742. fromAttribute: function ( attribute, index, offset ) {
  32743. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  32744. return this.fromBufferAttribute( attribute, index, offset );
  32745. },
  32746. distanceToManhattan: function ( v ) {
  32747. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  32748. return this.manhattanDistanceTo( v );
  32749. },
  32750. lengthManhattan: function () {
  32751. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  32752. return this.manhattanLength();
  32753. }
  32754. } );
  32755. Object.assign( Vector4.prototype, {
  32756. fromAttribute: function ( attribute, index, offset ) {
  32757. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  32758. return this.fromBufferAttribute( attribute, index, offset );
  32759. },
  32760. lengthManhattan: function () {
  32761. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  32762. return this.manhattanLength();
  32763. }
  32764. } );
  32765. //
  32766. Object.assign( Geometry.prototype, {
  32767. computeTangents: function () {
  32768. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  32769. },
  32770. computeLineDistances: function () {
  32771. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  32772. }
  32773. } );
  32774. Object.assign( Object3D.prototype, {
  32775. getChildByName: function ( name ) {
  32776. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  32777. return this.getObjectByName( name );
  32778. },
  32779. renderDepth: function () {
  32780. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  32781. },
  32782. translate: function ( distance, axis ) {
  32783. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  32784. return this.translateOnAxis( axis, distance );
  32785. },
  32786. getWorldRotation: function () {
  32787. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  32788. }
  32789. } );
  32790. Object.defineProperties( Object3D.prototype, {
  32791. eulerOrder: {
  32792. get: function () {
  32793. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  32794. return this.rotation.order;
  32795. },
  32796. set: function ( value ) {
  32797. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  32798. this.rotation.order = value;
  32799. }
  32800. },
  32801. useQuaternion: {
  32802. get: function () {
  32803. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  32804. },
  32805. set: function () {
  32806. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  32807. }
  32808. }
  32809. } );
  32810. Object.defineProperties( LOD.prototype, {
  32811. objects: {
  32812. get: function () {
  32813. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  32814. return this.levels;
  32815. }
  32816. }
  32817. } );
  32818. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  32819. get: function () {
  32820. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  32821. },
  32822. set: function () {
  32823. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  32824. }
  32825. } );
  32826. SkinnedMesh.prototype.initBones = function () {
  32827. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  32828. };
  32829. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  32830. get: function () {
  32831. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  32832. return this.arcLengthDivisions;
  32833. },
  32834. set: function ( value ) {
  32835. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  32836. this.arcLengthDivisions = value;
  32837. }
  32838. } );
  32839. //
  32840. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  32841. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  32842. "Use .setFocalLength and .filmGauge for a photographic setup." );
  32843. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  32844. this.setFocalLength( focalLength );
  32845. };
  32846. //
  32847. Object.defineProperties( Light.prototype, {
  32848. onlyShadow: {
  32849. set: function () {
  32850. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  32851. }
  32852. },
  32853. shadowCameraFov: {
  32854. set: function ( value ) {
  32855. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  32856. this.shadow.camera.fov = value;
  32857. }
  32858. },
  32859. shadowCameraLeft: {
  32860. set: function ( value ) {
  32861. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  32862. this.shadow.camera.left = value;
  32863. }
  32864. },
  32865. shadowCameraRight: {
  32866. set: function ( value ) {
  32867. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  32868. this.shadow.camera.right = value;
  32869. }
  32870. },
  32871. shadowCameraTop: {
  32872. set: function ( value ) {
  32873. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  32874. this.shadow.camera.top = value;
  32875. }
  32876. },
  32877. shadowCameraBottom: {
  32878. set: function ( value ) {
  32879. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  32880. this.shadow.camera.bottom = value;
  32881. }
  32882. },
  32883. shadowCameraNear: {
  32884. set: function ( value ) {
  32885. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  32886. this.shadow.camera.near = value;
  32887. }
  32888. },
  32889. shadowCameraFar: {
  32890. set: function ( value ) {
  32891. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  32892. this.shadow.camera.far = value;
  32893. }
  32894. },
  32895. shadowCameraVisible: {
  32896. set: function () {
  32897. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  32898. }
  32899. },
  32900. shadowBias: {
  32901. set: function ( value ) {
  32902. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  32903. this.shadow.bias = value;
  32904. }
  32905. },
  32906. shadowDarkness: {
  32907. set: function () {
  32908. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  32909. }
  32910. },
  32911. shadowMapWidth: {
  32912. set: function ( value ) {
  32913. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  32914. this.shadow.mapSize.width = value;
  32915. }
  32916. },
  32917. shadowMapHeight: {
  32918. set: function ( value ) {
  32919. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  32920. this.shadow.mapSize.height = value;
  32921. }
  32922. }
  32923. } );
  32924. //
  32925. Object.defineProperties( BufferAttribute.prototype, {
  32926. length: {
  32927. get: function () {
  32928. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  32929. return this.array.length;
  32930. }
  32931. },
  32932. copyIndicesArray: function ( /* indices */ ) {
  32933. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  32934. }
  32935. } );
  32936. Object.assign( BufferGeometry.prototype, {
  32937. addIndex: function ( index ) {
  32938. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  32939. this.setIndex( index );
  32940. },
  32941. addDrawCall: function ( start, count, indexOffset ) {
  32942. if ( indexOffset !== undefined ) {
  32943. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  32944. }
  32945. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  32946. this.addGroup( start, count );
  32947. },
  32948. clearDrawCalls: function () {
  32949. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  32950. this.clearGroups();
  32951. },
  32952. computeTangents: function () {
  32953. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  32954. },
  32955. computeOffsets: function () {
  32956. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  32957. }
  32958. } );
  32959. Object.defineProperties( BufferGeometry.prototype, {
  32960. drawcalls: {
  32961. get: function () {
  32962. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  32963. return this.groups;
  32964. }
  32965. },
  32966. offsets: {
  32967. get: function () {
  32968. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  32969. return this.groups;
  32970. }
  32971. }
  32972. } );
  32973. //
  32974. Object.assign( ExtrudeBufferGeometry.prototype, {
  32975. getArrays: function () {
  32976. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  32977. },
  32978. addShapeList: function () {
  32979. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  32980. },
  32981. addShape: function () {
  32982. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  32983. }
  32984. } );
  32985. //
  32986. Object.defineProperties( Uniform.prototype, {
  32987. dynamic: {
  32988. set: function () {
  32989. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  32990. }
  32991. },
  32992. onUpdate: {
  32993. value: function () {
  32994. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  32995. return this;
  32996. }
  32997. }
  32998. } );
  32999. //
  33000. Object.defineProperties( Material.prototype, {
  33001. wrapAround: {
  33002. get: function () {
  33003. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  33004. },
  33005. set: function () {
  33006. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  33007. }
  33008. },
  33009. overdraw: {
  33010. get: function () {
  33011. console.warn( 'THREE.Material: .overdraw has been removed.' );
  33012. },
  33013. set: function () {
  33014. console.warn( 'THREE.Material: .overdraw has been removed.' );
  33015. }
  33016. },
  33017. wrapRGB: {
  33018. get: function () {
  33019. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  33020. return new Color();
  33021. }
  33022. },
  33023. shading: {
  33024. get: function () {
  33025. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  33026. },
  33027. set: function ( value ) {
  33028. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  33029. this.flatShading = ( value === FlatShading );
  33030. }
  33031. }
  33032. } );
  33033. Object.defineProperties( MeshPhongMaterial.prototype, {
  33034. metal: {
  33035. get: function () {
  33036. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  33037. return false;
  33038. },
  33039. set: function () {
  33040. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  33041. }
  33042. }
  33043. } );
  33044. Object.defineProperties( ShaderMaterial.prototype, {
  33045. derivatives: {
  33046. get: function () {
  33047. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  33048. return this.extensions.derivatives;
  33049. },
  33050. set: function ( value ) {
  33051. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  33052. this.extensions.derivatives = value;
  33053. }
  33054. }
  33055. } );
  33056. //
  33057. Object.assign( WebGLRenderer.prototype, {
  33058. clearTarget: function ( renderTarget, color, depth, stencil ) {
  33059. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  33060. this.setRenderTarget( renderTarget );
  33061. this.clear( color, depth, stencil );
  33062. },
  33063. animate: function ( callback ) {
  33064. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  33065. this.setAnimationLoop( callback );
  33066. },
  33067. getCurrentRenderTarget: function () {
  33068. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  33069. return this.getRenderTarget();
  33070. },
  33071. getMaxAnisotropy: function () {
  33072. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  33073. return this.capabilities.getMaxAnisotropy();
  33074. },
  33075. getPrecision: function () {
  33076. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  33077. return this.capabilities.precision;
  33078. },
  33079. resetGLState: function () {
  33080. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  33081. return this.state.reset();
  33082. },
  33083. supportsFloatTextures: function () {
  33084. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  33085. return this.extensions.get( 'OES_texture_float' );
  33086. },
  33087. supportsHalfFloatTextures: function () {
  33088. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  33089. return this.extensions.get( 'OES_texture_half_float' );
  33090. },
  33091. supportsStandardDerivatives: function () {
  33092. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  33093. return this.extensions.get( 'OES_standard_derivatives' );
  33094. },
  33095. supportsCompressedTextureS3TC: function () {
  33096. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  33097. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  33098. },
  33099. supportsCompressedTexturePVRTC: function () {
  33100. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  33101. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  33102. },
  33103. supportsBlendMinMax: function () {
  33104. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  33105. return this.extensions.get( 'EXT_blend_minmax' );
  33106. },
  33107. supportsVertexTextures: function () {
  33108. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  33109. return this.capabilities.vertexTextures;
  33110. },
  33111. supportsInstancedArrays: function () {
  33112. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  33113. return this.extensions.get( 'ANGLE_instanced_arrays' );
  33114. },
  33115. enableScissorTest: function ( boolean ) {
  33116. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  33117. this.setScissorTest( boolean );
  33118. },
  33119. initMaterial: function () {
  33120. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  33121. },
  33122. addPrePlugin: function () {
  33123. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  33124. },
  33125. addPostPlugin: function () {
  33126. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  33127. },
  33128. updateShadowMap: function () {
  33129. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  33130. },
  33131. setFaceCulling: function () {
  33132. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  33133. }
  33134. } );
  33135. Object.defineProperties( WebGLRenderer.prototype, {
  33136. shadowMapEnabled: {
  33137. get: function () {
  33138. return this.shadowMap.enabled;
  33139. },
  33140. set: function ( value ) {
  33141. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  33142. this.shadowMap.enabled = value;
  33143. }
  33144. },
  33145. shadowMapType: {
  33146. get: function () {
  33147. return this.shadowMap.type;
  33148. },
  33149. set: function ( value ) {
  33150. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  33151. this.shadowMap.type = value;
  33152. }
  33153. },
  33154. shadowMapCullFace: {
  33155. get: function () {
  33156. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  33157. return undefined;
  33158. },
  33159. set: function ( /* value */ ) {
  33160. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  33161. }
  33162. }
  33163. } );
  33164. Object.defineProperties( WebGLShadowMap.prototype, {
  33165. cullFace: {
  33166. get: function () {
  33167. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  33168. return undefined;
  33169. },
  33170. set: function ( /* cullFace */ ) {
  33171. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  33172. }
  33173. },
  33174. renderReverseSided: {
  33175. get: function () {
  33176. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  33177. return undefined;
  33178. },
  33179. set: function () {
  33180. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  33181. }
  33182. },
  33183. renderSingleSided: {
  33184. get: function () {
  33185. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  33186. return undefined;
  33187. },
  33188. set: function () {
  33189. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  33190. }
  33191. }
  33192. } );
  33193. //
  33194. Object.defineProperties( WebGLRenderTargetCube.prototype, {
  33195. activeCubeFace: {
  33196. set: function ( /* value */ ) {
  33197. console.warn( 'THREE.WebGLRenderTargetCube: .activeCubeFace has been removed. It is now the second parameter of WebGLRenderer.setRenderTarget().' );
  33198. }
  33199. },
  33200. activeMipMapLevel: {
  33201. set: function ( /* value */ ) {
  33202. console.warn( 'THREE.WebGLRenderTargetCube: .activeMipMapLevel has been removed. It is now the third parameter of WebGLRenderer.setRenderTarget().' );
  33203. }
  33204. }
  33205. } );
  33206. //
  33207. Object.defineProperties( WebGLRenderTarget.prototype, {
  33208. wrapS: {
  33209. get: function () {
  33210. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  33211. return this.texture.wrapS;
  33212. },
  33213. set: function ( value ) {
  33214. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  33215. this.texture.wrapS = value;
  33216. }
  33217. },
  33218. wrapT: {
  33219. get: function () {
  33220. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  33221. return this.texture.wrapT;
  33222. },
  33223. set: function ( value ) {
  33224. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  33225. this.texture.wrapT = value;
  33226. }
  33227. },
  33228. magFilter: {
  33229. get: function () {
  33230. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  33231. return this.texture.magFilter;
  33232. },
  33233. set: function ( value ) {
  33234. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  33235. this.texture.magFilter = value;
  33236. }
  33237. },
  33238. minFilter: {
  33239. get: function () {
  33240. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  33241. return this.texture.minFilter;
  33242. },
  33243. set: function ( value ) {
  33244. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  33245. this.texture.minFilter = value;
  33246. }
  33247. },
  33248. anisotropy: {
  33249. get: function () {
  33250. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  33251. return this.texture.anisotropy;
  33252. },
  33253. set: function ( value ) {
  33254. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  33255. this.texture.anisotropy = value;
  33256. }
  33257. },
  33258. offset: {
  33259. get: function () {
  33260. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  33261. return this.texture.offset;
  33262. },
  33263. set: function ( value ) {
  33264. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  33265. this.texture.offset = value;
  33266. }
  33267. },
  33268. repeat: {
  33269. get: function () {
  33270. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  33271. return this.texture.repeat;
  33272. },
  33273. set: function ( value ) {
  33274. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  33275. this.texture.repeat = value;
  33276. }
  33277. },
  33278. format: {
  33279. get: function () {
  33280. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  33281. return this.texture.format;
  33282. },
  33283. set: function ( value ) {
  33284. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  33285. this.texture.format = value;
  33286. }
  33287. },
  33288. type: {
  33289. get: function () {
  33290. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  33291. return this.texture.type;
  33292. },
  33293. set: function ( value ) {
  33294. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  33295. this.texture.type = value;
  33296. }
  33297. },
  33298. generateMipmaps: {
  33299. get: function () {
  33300. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  33301. return this.texture.generateMipmaps;
  33302. },
  33303. set: function ( value ) {
  33304. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  33305. this.texture.generateMipmaps = value;
  33306. }
  33307. }
  33308. } );
  33309. //
  33310. Object.defineProperties( WebVRManager.prototype, {
  33311. standing: {
  33312. set: function ( /* value */ ) {
  33313. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  33314. }
  33315. },
  33316. userHeight: {
  33317. set: function ( /* value */ ) {
  33318. console.warn( 'THREE.WebVRManager: .userHeight has been removed.' );
  33319. }
  33320. }
  33321. } );
  33322. //
  33323. Audio.prototype.load = function ( file ) {
  33324. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  33325. var scope = this;
  33326. var audioLoader = new AudioLoader();
  33327. audioLoader.load( file, function ( buffer ) {
  33328. scope.setBuffer( buffer );
  33329. } );
  33330. return this;
  33331. };
  33332. AudioAnalyser.prototype.getData = function () {
  33333. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  33334. return this.getFrequencyData();
  33335. };
  33336. //
  33337. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  33338. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  33339. return this.update( renderer, scene );
  33340. };
  33341. //
  33342. var GeometryUtils = {
  33343. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  33344. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  33345. var matrix;
  33346. if ( geometry2.isMesh ) {
  33347. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  33348. matrix = geometry2.matrix;
  33349. geometry2 = geometry2.geometry;
  33350. }
  33351. geometry1.merge( geometry2, matrix, materialIndexOffset );
  33352. },
  33353. center: function ( geometry ) {
  33354. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  33355. return geometry.center();
  33356. }
  33357. };
  33358. ImageUtils.crossOrigin = undefined;
  33359. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  33360. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  33361. var loader = new TextureLoader();
  33362. loader.setCrossOrigin( this.crossOrigin );
  33363. var texture = loader.load( url, onLoad, undefined, onError );
  33364. if ( mapping ) texture.mapping = mapping;
  33365. return texture;
  33366. };
  33367. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  33368. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  33369. var loader = new CubeTextureLoader();
  33370. loader.setCrossOrigin( this.crossOrigin );
  33371. var texture = loader.load( urls, onLoad, undefined, onError );
  33372. if ( mapping ) texture.mapping = mapping;
  33373. return texture;
  33374. };
  33375. ImageUtils.loadCompressedTexture = function () {
  33376. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  33377. };
  33378. ImageUtils.loadCompressedTextureCube = function () {
  33379. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  33380. };
  33381. //
  33382. function Projector() {
  33383. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  33384. this.projectVector = function ( vector, camera ) {
  33385. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  33386. vector.project( camera );
  33387. };
  33388. this.unprojectVector = function ( vector, camera ) {
  33389. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  33390. vector.unproject( camera );
  33391. };
  33392. this.pickingRay = function () {
  33393. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  33394. };
  33395. }
  33396. //
  33397. function CanvasRenderer() {
  33398. console.error( 'THREE.CanvasRenderer has been removed' );
  33399. }
  33400. //
  33401. function JSONLoader() {
  33402. console.error( 'THREE.JSONLoader has been removed.' );
  33403. }
  33404. //
  33405. var SceneUtils = {
  33406. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  33407. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  33408. },
  33409. detach: function ( /* child, parent, scene */ ) {
  33410. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  33411. },
  33412. attach: function ( /* child, scene, parent */ ) {
  33413. console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );
  33414. }
  33415. };
  33416. //
  33417. function LensFlare() {
  33418. console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );
  33419. }
  33420. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  33421. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  33422. exports.WebGLRenderTarget = WebGLRenderTarget;
  33423. exports.WebGLRenderer = WebGLRenderer;
  33424. exports.ShaderLib = ShaderLib;
  33425. exports.UniformsLib = UniformsLib;
  33426. exports.UniformsUtils = UniformsUtils;
  33427. exports.ShaderChunk = ShaderChunk;
  33428. exports.FogExp2 = FogExp2;
  33429. exports.Fog = Fog;
  33430. exports.Scene = Scene;
  33431. exports.Sprite = Sprite;
  33432. exports.LOD = LOD;
  33433. exports.SkinnedMesh = SkinnedMesh;
  33434. exports.Skeleton = Skeleton;
  33435. exports.Bone = Bone;
  33436. exports.Mesh = Mesh;
  33437. exports.LineSegments = LineSegments;
  33438. exports.LineLoop = LineLoop;
  33439. exports.Line = Line;
  33440. exports.Points = Points;
  33441. exports.Group = Group;
  33442. exports.VideoTexture = VideoTexture;
  33443. exports.DataTexture = DataTexture;
  33444. exports.DataTexture2DArray = DataTexture2DArray;
  33445. exports.DataTexture3D = DataTexture3D;
  33446. exports.CompressedTexture = CompressedTexture;
  33447. exports.CubeTexture = CubeTexture;
  33448. exports.CanvasTexture = CanvasTexture;
  33449. exports.DepthTexture = DepthTexture;
  33450. exports.Texture = Texture;
  33451. exports.AnimationLoader = AnimationLoader;
  33452. exports.CompressedTextureLoader = CompressedTextureLoader;
  33453. exports.DataTextureLoader = DataTextureLoader;
  33454. exports.CubeTextureLoader = CubeTextureLoader;
  33455. exports.TextureLoader = TextureLoader;
  33456. exports.ObjectLoader = ObjectLoader;
  33457. exports.MaterialLoader = MaterialLoader;
  33458. exports.BufferGeometryLoader = BufferGeometryLoader;
  33459. exports.DefaultLoadingManager = DefaultLoadingManager;
  33460. exports.LoadingManager = LoadingManager;
  33461. exports.ImageLoader = ImageLoader;
  33462. exports.ImageBitmapLoader = ImageBitmapLoader;
  33463. exports.FontLoader = FontLoader;
  33464. exports.FileLoader = FileLoader;
  33465. exports.Loader = Loader;
  33466. exports.LoaderUtils = LoaderUtils;
  33467. exports.Cache = Cache;
  33468. exports.AudioLoader = AudioLoader;
  33469. exports.SpotLightShadow = SpotLightShadow;
  33470. exports.SpotLight = SpotLight;
  33471. exports.PointLight = PointLight;
  33472. exports.RectAreaLight = RectAreaLight;
  33473. exports.HemisphereLight = HemisphereLight;
  33474. exports.DirectionalLightShadow = DirectionalLightShadow;
  33475. exports.DirectionalLight = DirectionalLight;
  33476. exports.AmbientLight = AmbientLight;
  33477. exports.LightShadow = LightShadow;
  33478. exports.Light = Light;
  33479. exports.StereoCamera = StereoCamera;
  33480. exports.PerspectiveCamera = PerspectiveCamera;
  33481. exports.OrthographicCamera = OrthographicCamera;
  33482. exports.CubeCamera = CubeCamera;
  33483. exports.ArrayCamera = ArrayCamera;
  33484. exports.Camera = Camera;
  33485. exports.AudioListener = AudioListener;
  33486. exports.PositionalAudio = PositionalAudio;
  33487. exports.AudioContext = AudioContext;
  33488. exports.AudioAnalyser = AudioAnalyser;
  33489. exports.Audio = Audio;
  33490. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  33491. exports.StringKeyframeTrack = StringKeyframeTrack;
  33492. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  33493. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  33494. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  33495. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  33496. exports.PropertyMixer = PropertyMixer;
  33497. exports.PropertyBinding = PropertyBinding;
  33498. exports.KeyframeTrack = KeyframeTrack;
  33499. exports.AnimationUtils = AnimationUtils;
  33500. exports.AnimationObjectGroup = AnimationObjectGroup;
  33501. exports.AnimationMixer = AnimationMixer;
  33502. exports.AnimationClip = AnimationClip;
  33503. exports.Uniform = Uniform;
  33504. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  33505. exports.BufferGeometry = BufferGeometry;
  33506. exports.Geometry = Geometry;
  33507. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  33508. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  33509. exports.InterleavedBuffer = InterleavedBuffer;
  33510. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  33511. exports.Face3 = Face3;
  33512. exports.Object3D = Object3D;
  33513. exports.Raycaster = Raycaster;
  33514. exports.Layers = Layers;
  33515. exports.EventDispatcher = EventDispatcher;
  33516. exports.Clock = Clock;
  33517. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  33518. exports.LinearInterpolant = LinearInterpolant;
  33519. exports.DiscreteInterpolant = DiscreteInterpolant;
  33520. exports.CubicInterpolant = CubicInterpolant;
  33521. exports.Interpolant = Interpolant;
  33522. exports.Triangle = Triangle;
  33523. exports.Math = _Math;
  33524. exports.Spherical = Spherical;
  33525. exports.Cylindrical = Cylindrical;
  33526. exports.Plane = Plane;
  33527. exports.Frustum = Frustum;
  33528. exports.Sphere = Sphere;
  33529. exports.Ray = Ray;
  33530. exports.Matrix4 = Matrix4;
  33531. exports.Matrix3 = Matrix3;
  33532. exports.Box3 = Box3;
  33533. exports.Box2 = Box2;
  33534. exports.Line3 = Line3;
  33535. exports.Euler = Euler;
  33536. exports.Vector4 = Vector4;
  33537. exports.Vector3 = Vector3;
  33538. exports.Vector2 = Vector2;
  33539. exports.Quaternion = Quaternion;
  33540. exports.Color = Color;
  33541. exports.ImmediateRenderObject = ImmediateRenderObject;
  33542. exports.VertexNormalsHelper = VertexNormalsHelper;
  33543. exports.SpotLightHelper = SpotLightHelper;
  33544. exports.SkeletonHelper = SkeletonHelper;
  33545. exports.PointLightHelper = PointLightHelper;
  33546. exports.RectAreaLightHelper = RectAreaLightHelper;
  33547. exports.HemisphereLightHelper = HemisphereLightHelper;
  33548. exports.GridHelper = GridHelper;
  33549. exports.PolarGridHelper = PolarGridHelper;
  33550. exports.PositionalAudioHelper = PositionalAudioHelper;
  33551. exports.FaceNormalsHelper = FaceNormalsHelper;
  33552. exports.DirectionalLightHelper = DirectionalLightHelper;
  33553. exports.CameraHelper = CameraHelper;
  33554. exports.BoxHelper = BoxHelper;
  33555. exports.Box3Helper = Box3Helper;
  33556. exports.PlaneHelper = PlaneHelper;
  33557. exports.ArrowHelper = ArrowHelper;
  33558. exports.AxesHelper = AxesHelper;
  33559. exports.Shape = Shape;
  33560. exports.Path = Path;
  33561. exports.ShapePath = ShapePath;
  33562. exports.Font = Font;
  33563. exports.CurvePath = CurvePath;
  33564. exports.Curve = Curve;
  33565. exports.ImageUtils = ImageUtils;
  33566. exports.ShapeUtils = ShapeUtils;
  33567. exports.WebGLUtils = WebGLUtils;
  33568. exports.WireframeGeometry = WireframeGeometry;
  33569. exports.ParametricGeometry = ParametricGeometry;
  33570. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  33571. exports.TetrahedronGeometry = TetrahedronGeometry;
  33572. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  33573. exports.OctahedronGeometry = OctahedronGeometry;
  33574. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  33575. exports.IcosahedronGeometry = IcosahedronGeometry;
  33576. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  33577. exports.DodecahedronGeometry = DodecahedronGeometry;
  33578. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  33579. exports.PolyhedronGeometry = PolyhedronGeometry;
  33580. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  33581. exports.TubeGeometry = TubeGeometry;
  33582. exports.TubeBufferGeometry = TubeBufferGeometry;
  33583. exports.TorusKnotGeometry = TorusKnotGeometry;
  33584. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  33585. exports.TorusGeometry = TorusGeometry;
  33586. exports.TorusBufferGeometry = TorusBufferGeometry;
  33587. exports.TextGeometry = TextGeometry;
  33588. exports.TextBufferGeometry = TextBufferGeometry;
  33589. exports.SphereGeometry = SphereGeometry;
  33590. exports.SphereBufferGeometry = SphereBufferGeometry;
  33591. exports.RingGeometry = RingGeometry;
  33592. exports.RingBufferGeometry = RingBufferGeometry;
  33593. exports.PlaneGeometry = PlaneGeometry;
  33594. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  33595. exports.LatheGeometry = LatheGeometry;
  33596. exports.LatheBufferGeometry = LatheBufferGeometry;
  33597. exports.ShapeGeometry = ShapeGeometry;
  33598. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  33599. exports.ExtrudeGeometry = ExtrudeGeometry;
  33600. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  33601. exports.EdgesGeometry = EdgesGeometry;
  33602. exports.ConeGeometry = ConeGeometry;
  33603. exports.ConeBufferGeometry = ConeBufferGeometry;
  33604. exports.CylinderGeometry = CylinderGeometry;
  33605. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  33606. exports.CircleGeometry = CircleGeometry;
  33607. exports.CircleBufferGeometry = CircleBufferGeometry;
  33608. exports.BoxGeometry = BoxGeometry;
  33609. exports.CubeGeometry = BoxGeometry;
  33610. exports.BoxBufferGeometry = BoxBufferGeometry;
  33611. exports.ShadowMaterial = ShadowMaterial;
  33612. exports.SpriteMaterial = SpriteMaterial;
  33613. exports.RawShaderMaterial = RawShaderMaterial;
  33614. exports.ShaderMaterial = ShaderMaterial;
  33615. exports.PointsMaterial = PointsMaterial;
  33616. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  33617. exports.MeshStandardMaterial = MeshStandardMaterial;
  33618. exports.MeshPhongMaterial = MeshPhongMaterial;
  33619. exports.MeshToonMaterial = MeshToonMaterial;
  33620. exports.MeshNormalMaterial = MeshNormalMaterial;
  33621. exports.MeshLambertMaterial = MeshLambertMaterial;
  33622. exports.MeshDepthMaterial = MeshDepthMaterial;
  33623. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  33624. exports.MeshBasicMaterial = MeshBasicMaterial;
  33625. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  33626. exports.LineDashedMaterial = LineDashedMaterial;
  33627. exports.LineBasicMaterial = LineBasicMaterial;
  33628. exports.Material = Material;
  33629. exports.Float64BufferAttribute = Float64BufferAttribute;
  33630. exports.Float32BufferAttribute = Float32BufferAttribute;
  33631. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  33632. exports.Int32BufferAttribute = Int32BufferAttribute;
  33633. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  33634. exports.Int16BufferAttribute = Int16BufferAttribute;
  33635. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  33636. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  33637. exports.Int8BufferAttribute = Int8BufferAttribute;
  33638. exports.BufferAttribute = BufferAttribute;
  33639. exports.ArcCurve = ArcCurve;
  33640. exports.CatmullRomCurve3 = CatmullRomCurve3;
  33641. exports.CubicBezierCurve = CubicBezierCurve;
  33642. exports.CubicBezierCurve3 = CubicBezierCurve3;
  33643. exports.EllipseCurve = EllipseCurve;
  33644. exports.LineCurve = LineCurve;
  33645. exports.LineCurve3 = LineCurve3;
  33646. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  33647. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  33648. exports.SplineCurve = SplineCurve;
  33649. exports.REVISION = REVISION;
  33650. exports.MOUSE = MOUSE;
  33651. exports.CullFaceNone = CullFaceNone;
  33652. exports.CullFaceBack = CullFaceBack;
  33653. exports.CullFaceFront = CullFaceFront;
  33654. exports.CullFaceFrontBack = CullFaceFrontBack;
  33655. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  33656. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  33657. exports.BasicShadowMap = BasicShadowMap;
  33658. exports.PCFShadowMap = PCFShadowMap;
  33659. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  33660. exports.FrontSide = FrontSide;
  33661. exports.BackSide = BackSide;
  33662. exports.DoubleSide = DoubleSide;
  33663. exports.FlatShading = FlatShading;
  33664. exports.SmoothShading = SmoothShading;
  33665. exports.NoColors = NoColors;
  33666. exports.FaceColors = FaceColors;
  33667. exports.VertexColors = VertexColors;
  33668. exports.NoBlending = NoBlending;
  33669. exports.NormalBlending = NormalBlending;
  33670. exports.AdditiveBlending = AdditiveBlending;
  33671. exports.SubtractiveBlending = SubtractiveBlending;
  33672. exports.MultiplyBlending = MultiplyBlending;
  33673. exports.CustomBlending = CustomBlending;
  33674. exports.AddEquation = AddEquation;
  33675. exports.SubtractEquation = SubtractEquation;
  33676. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  33677. exports.MinEquation = MinEquation;
  33678. exports.MaxEquation = MaxEquation;
  33679. exports.ZeroFactor = ZeroFactor;
  33680. exports.OneFactor = OneFactor;
  33681. exports.SrcColorFactor = SrcColorFactor;
  33682. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  33683. exports.SrcAlphaFactor = SrcAlphaFactor;
  33684. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  33685. exports.DstAlphaFactor = DstAlphaFactor;
  33686. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  33687. exports.DstColorFactor = DstColorFactor;
  33688. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  33689. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  33690. exports.NeverDepth = NeverDepth;
  33691. exports.AlwaysDepth = AlwaysDepth;
  33692. exports.LessDepth = LessDepth;
  33693. exports.LessEqualDepth = LessEqualDepth;
  33694. exports.EqualDepth = EqualDepth;
  33695. exports.GreaterEqualDepth = GreaterEqualDepth;
  33696. exports.GreaterDepth = GreaterDepth;
  33697. exports.NotEqualDepth = NotEqualDepth;
  33698. exports.MultiplyOperation = MultiplyOperation;
  33699. exports.MixOperation = MixOperation;
  33700. exports.AddOperation = AddOperation;
  33701. exports.NoToneMapping = NoToneMapping;
  33702. exports.LinearToneMapping = LinearToneMapping;
  33703. exports.ReinhardToneMapping = ReinhardToneMapping;
  33704. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  33705. exports.CineonToneMapping = CineonToneMapping;
  33706. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  33707. exports.UVMapping = UVMapping;
  33708. exports.CubeReflectionMapping = CubeReflectionMapping;
  33709. exports.CubeRefractionMapping = CubeRefractionMapping;
  33710. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  33711. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  33712. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  33713. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  33714. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  33715. exports.RepeatWrapping = RepeatWrapping;
  33716. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  33717. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  33718. exports.NearestFilter = NearestFilter;
  33719. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  33720. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  33721. exports.LinearFilter = LinearFilter;
  33722. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  33723. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  33724. exports.UnsignedByteType = UnsignedByteType;
  33725. exports.ByteType = ByteType;
  33726. exports.ShortType = ShortType;
  33727. exports.UnsignedShortType = UnsignedShortType;
  33728. exports.IntType = IntType;
  33729. exports.UnsignedIntType = UnsignedIntType;
  33730. exports.FloatType = FloatType;
  33731. exports.HalfFloatType = HalfFloatType;
  33732. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  33733. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  33734. exports.UnsignedShort565Type = UnsignedShort565Type;
  33735. exports.UnsignedInt248Type = UnsignedInt248Type;
  33736. exports.AlphaFormat = AlphaFormat;
  33737. exports.RGBFormat = RGBFormat;
  33738. exports.RGBAFormat = RGBAFormat;
  33739. exports.LuminanceFormat = LuminanceFormat;
  33740. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  33741. exports.RGBEFormat = RGBEFormat;
  33742. exports.DepthFormat = DepthFormat;
  33743. exports.DepthStencilFormat = DepthStencilFormat;
  33744. exports.RedFormat = RedFormat;
  33745. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  33746. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  33747. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  33748. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  33749. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  33750. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  33751. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  33752. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  33753. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  33754. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  33755. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  33756. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  33757. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  33758. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  33759. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  33760. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  33761. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  33762. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  33763. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  33764. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  33765. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  33766. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  33767. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  33768. exports.LoopOnce = LoopOnce;
  33769. exports.LoopRepeat = LoopRepeat;
  33770. exports.LoopPingPong = LoopPingPong;
  33771. exports.InterpolateDiscrete = InterpolateDiscrete;
  33772. exports.InterpolateLinear = InterpolateLinear;
  33773. exports.InterpolateSmooth = InterpolateSmooth;
  33774. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  33775. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  33776. exports.WrapAroundEnding = WrapAroundEnding;
  33777. exports.TrianglesDrawMode = TrianglesDrawMode;
  33778. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  33779. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  33780. exports.LinearEncoding = LinearEncoding;
  33781. exports.sRGBEncoding = sRGBEncoding;
  33782. exports.GammaEncoding = GammaEncoding;
  33783. exports.RGBEEncoding = RGBEEncoding;
  33784. exports.LogLuvEncoding = LogLuvEncoding;
  33785. exports.RGBM7Encoding = RGBM7Encoding;
  33786. exports.RGBM16Encoding = RGBM16Encoding;
  33787. exports.RGBDEncoding = RGBDEncoding;
  33788. exports.BasicDepthPacking = BasicDepthPacking;
  33789. exports.RGBADepthPacking = RGBADepthPacking;
  33790. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  33791. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  33792. exports.Face4 = Face4;
  33793. exports.LineStrip = LineStrip;
  33794. exports.LinePieces = LinePieces;
  33795. exports.MeshFaceMaterial = MeshFaceMaterial;
  33796. exports.MultiMaterial = MultiMaterial;
  33797. exports.PointCloud = PointCloud;
  33798. exports.Particle = Particle;
  33799. exports.ParticleSystem = ParticleSystem;
  33800. exports.PointCloudMaterial = PointCloudMaterial;
  33801. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  33802. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  33803. exports.Vertex = Vertex;
  33804. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  33805. exports.Int8Attribute = Int8Attribute;
  33806. exports.Uint8Attribute = Uint8Attribute;
  33807. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  33808. exports.Int16Attribute = Int16Attribute;
  33809. exports.Uint16Attribute = Uint16Attribute;
  33810. exports.Int32Attribute = Int32Attribute;
  33811. exports.Uint32Attribute = Uint32Attribute;
  33812. exports.Float32Attribute = Float32Attribute;
  33813. exports.Float64Attribute = Float64Attribute;
  33814. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  33815. exports.SplineCurve3 = SplineCurve3;
  33816. exports.Spline = Spline;
  33817. exports.AxisHelper = AxisHelper;
  33818. exports.BoundingBoxHelper = BoundingBoxHelper;
  33819. exports.EdgesHelper = EdgesHelper;
  33820. exports.WireframeHelper = WireframeHelper;
  33821. exports.XHRLoader = XHRLoader;
  33822. exports.BinaryTextureLoader = BinaryTextureLoader;
  33823. exports.GeometryUtils = GeometryUtils;
  33824. exports.Projector = Projector;
  33825. exports.CanvasRenderer = CanvasRenderer;
  33826. exports.JSONLoader = JSONLoader;
  33827. exports.SceneUtils = SceneUtils;
  33828. exports.LensFlare = LensFlare;
  33829. Object.defineProperty(exports, '__esModule', { value: true });
  33830. }));
  33831. },{}],37:[function(_dereq_,module,exports){
  33832. // Copyright 2016 The Draco Authors.
  33833. //
  33834. // Licensed under the Apache License, Version 2.0 (the "License");
  33835. // you may not use this file except in compliance with the License.
  33836. // You may obtain a copy of the License at
  33837. //
  33838. // http://www.apache.org/licenses/LICENSE-2.0
  33839. //
  33840. // Unless required by applicable law or agreed to in writing, software
  33841. // distributed under the License is distributed on an "AS IS" BASIS,
  33842. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  33843. // See the License for the specific language governing permissions and
  33844. // limitations under the License.
  33845. //
  33846. 'use strict';
  33847. /**
  33848. * @param {THREE.LoadingManager} manager
  33849. */
  33850. THREE.DRACOLoader = function(manager) {
  33851. this.timeLoaded = 0;
  33852. this.manager = manager || THREE.DefaultLoadingManager;
  33853. this.materials = null;
  33854. this.verbosity = 0;
  33855. this.attributeOptions = {};
  33856. this.drawMode = THREE.TrianglesDrawMode;
  33857. // Native Draco attribute type to Three.JS attribute type.
  33858. this.nativeAttributeMap = {
  33859. 'position' : 'POSITION',
  33860. 'normal' : 'NORMAL',
  33861. 'color' : 'COLOR',
  33862. 'uv' : 'TEX_COORD'
  33863. };
  33864. };
  33865. THREE.DRACOLoader.prototype = {
  33866. constructor: THREE.DRACOLoader,
  33867. load: function(url, onLoad, onProgress, onError) {
  33868. var scope = this;
  33869. var loader = new THREE.FileLoader(scope.manager);
  33870. loader.setPath(this.path);
  33871. loader.setResponseType('arraybuffer');
  33872. loader.load(url, function(blob) {
  33873. scope.decodeDracoFile(blob, onLoad);
  33874. }, onProgress, onError);
  33875. },
  33876. setPath: function(value) {
  33877. this.path = value;
  33878. return this;
  33879. },
  33880. setVerbosity: function(level) {
  33881. this.verbosity = level;
  33882. return this;
  33883. },
  33884. /**
  33885. * Sets desired mode for generated geometry indices.
  33886. * Can be either:
  33887. * THREE.TrianglesDrawMode
  33888. * THREE.TriangleStripDrawMode
  33889. */
  33890. setDrawMode: function(drawMode) {
  33891. this.drawMode = drawMode;
  33892. return this;
  33893. },
  33894. /**
  33895. * Skips dequantization for a specific attribute.
  33896. * |attributeName| is the THREE.js name of the given attribute type.
  33897. * The only currently supported |attributeName| is 'position', more may be
  33898. * added in future.
  33899. */
  33900. setSkipDequantization: function(attributeName, skip) {
  33901. var skipDequantization = true;
  33902. if (typeof skip !== 'undefined')
  33903. skipDequantization = skip;
  33904. this.getAttributeOptions(attributeName).skipDequantization =
  33905. skipDequantization;
  33906. return this;
  33907. },
  33908. /**
  33909. * Decompresses a Draco buffer. Names of attributes (for ID and type maps)
  33910. * must be one of the supported three.js types, including: position, color,
  33911. * normal, uv, uv2, skinIndex, skinWeight.
  33912. *
  33913. * @param {ArrayBuffer} rawBuffer
  33914. * @param {Function} callback
  33915. * @param {Object|undefined} attributeUniqueIdMap Provides a pre-defined ID
  33916. * for each attribute in the geometry to be decoded. If given,
  33917. * `attributeTypeMap` is required and `nativeAttributeMap` will be
  33918. * ignored.
  33919. * @param {Object|undefined} attributeTypeMap Provides a predefined data
  33920. * type (as a typed array constructor) for each attribute in the
  33921. * geometry to be decoded.
  33922. */
  33923. decodeDracoFile: function(rawBuffer, callback, attributeUniqueIdMap,
  33924. attributeTypeMap) {
  33925. var scope = this;
  33926. THREE.DRACOLoader.getDecoderModule()
  33927. .then( function ( module ) {
  33928. scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback,
  33929. attributeUniqueIdMap, attributeTypeMap);
  33930. });
  33931. },
  33932. decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback,
  33933. attributeUniqueIdMap, attributeTypeMap) {
  33934. /*
  33935. * Here is how to use Draco Javascript decoder and get the geometry.
  33936. */
  33937. var buffer = new dracoDecoder.DecoderBuffer();
  33938. buffer.Init(new Int8Array(rawBuffer), rawBuffer.byteLength);
  33939. var decoder = new dracoDecoder.Decoder();
  33940. /*
  33941. * Determine what type is this file: mesh or point cloud.
  33942. */
  33943. var geometryType = decoder.GetEncodedGeometryType(buffer);
  33944. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  33945. if (this.verbosity > 0) {
  33946. console.log('Loaded a mesh.');
  33947. }
  33948. } else if (geometryType == dracoDecoder.POINT_CLOUD) {
  33949. if (this.verbosity > 0) {
  33950. console.log('Loaded a point cloud.');
  33951. }
  33952. } else {
  33953. var errorMsg = 'THREE.DRACOLoader: Unknown geometry type.';
  33954. console.error(errorMsg);
  33955. throw new Error(errorMsg);
  33956. }
  33957. callback(this.convertDracoGeometryTo3JS(dracoDecoder, decoder,
  33958. geometryType, buffer, attributeUniqueIdMap, attributeTypeMap));
  33959. },
  33960. addAttributeToGeometry: function(dracoDecoder, decoder, dracoGeometry,
  33961. attributeName, attributeType, attribute,
  33962. geometry, geometryBuffer) {
  33963. if (attribute.ptr === 0) {
  33964. var errorMsg = 'THREE.DRACOLoader: No attribute ' + attributeName;
  33965. console.error(errorMsg);
  33966. throw new Error(errorMsg);
  33967. }
  33968. var numComponents = attribute.num_components();
  33969. var numPoints = dracoGeometry.num_points();
  33970. var numValues = numPoints * numComponents;
  33971. var attributeData;
  33972. var TypedBufferAttribute;
  33973. switch ( attributeType ) {
  33974. case Float32Array:
  33975. attributeData = new dracoDecoder.DracoFloat32Array();
  33976. decoder.GetAttributeFloatForAllPoints(
  33977. dracoGeometry, attribute, attributeData);
  33978. geometryBuffer[ attributeName ] = new Float32Array( numValues );
  33979. TypedBufferAttribute = THREE.Float32BufferAttribute;
  33980. break;
  33981. case Int8Array:
  33982. attributeData = new dracoDecoder.DracoInt8Array();
  33983. decoder.GetAttributeInt8ForAllPoints(
  33984. dracoGeometry, attribute, attributeData );
  33985. geometryBuffer[ attributeName ] = new Int8Array( numValues );
  33986. TypedBufferAttribute = THREE.Int8BufferAttribute;
  33987. break;
  33988. case Int16Array:
  33989. attributeData = new dracoDecoder.DracoInt16Array();
  33990. decoder.GetAttributeInt16ForAllPoints(
  33991. dracoGeometry, attribute, attributeData);
  33992. geometryBuffer[ attributeName ] = new Int16Array( numValues );
  33993. TypedBufferAttribute = THREE.Int16BufferAttribute;
  33994. break;
  33995. case Int32Array:
  33996. attributeData = new dracoDecoder.DracoInt32Array();
  33997. decoder.GetAttributeInt32ForAllPoints(
  33998. dracoGeometry, attribute, attributeData);
  33999. geometryBuffer[ attributeName ] = new Int32Array( numValues );
  34000. TypedBufferAttribute = THREE.Int32BufferAttribute;
  34001. break;
  34002. case Uint8Array:
  34003. attributeData = new dracoDecoder.DracoUInt8Array();
  34004. decoder.GetAttributeUInt8ForAllPoints(
  34005. dracoGeometry, attribute, attributeData);
  34006. geometryBuffer[ attributeName ] = new Uint8Array( numValues );
  34007. TypedBufferAttribute = THREE.Uint8BufferAttribute;
  34008. break;
  34009. case Uint16Array:
  34010. attributeData = new dracoDecoder.DracoUInt16Array();
  34011. decoder.GetAttributeUInt16ForAllPoints(
  34012. dracoGeometry, attribute, attributeData);
  34013. geometryBuffer[ attributeName ] = new Uint16Array( numValues );
  34014. TypedBufferAttribute = THREE.Uint16BufferAttribute;
  34015. break;
  34016. case Uint32Array:
  34017. attributeData = new dracoDecoder.DracoUInt32Array();
  34018. decoder.GetAttributeUInt32ForAllPoints(
  34019. dracoGeometry, attribute, attributeData);
  34020. geometryBuffer[ attributeName ] = new Uint32Array( numValues );
  34021. TypedBufferAttribute = THREE.Uint32BufferAttribute;
  34022. break;
  34023. default:
  34024. var errorMsg = 'THREE.DRACOLoader: Unexpected attribute type.';
  34025. console.error( errorMsg );
  34026. throw new Error( errorMsg );
  34027. }
  34028. // Copy data from decoder.
  34029. for (var i = 0; i < numValues; i++) {
  34030. geometryBuffer[attributeName][i] = attributeData.GetValue(i);
  34031. }
  34032. // Add attribute to THREEJS geometry for rendering.
  34033. geometry.addAttribute(attributeName,
  34034. new TypedBufferAttribute(geometryBuffer[attributeName],
  34035. numComponents));
  34036. dracoDecoder.destroy(attributeData);
  34037. },
  34038. convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType,
  34039. buffer, attributeUniqueIdMap,
  34040. attributeTypeMap) {
  34041. // TODO: Should not assume native Draco attribute IDs apply.
  34042. if (this.getAttributeOptions('position').skipDequantization === true) {
  34043. decoder.SkipAttributeTransform(dracoDecoder.POSITION);
  34044. }
  34045. var dracoGeometry;
  34046. var decodingStatus;
  34047. var start_time = performance.now();
  34048. if (geometryType === dracoDecoder.TRIANGULAR_MESH) {
  34049. dracoGeometry = new dracoDecoder.Mesh();
  34050. decodingStatus = decoder.DecodeBufferToMesh(buffer, dracoGeometry);
  34051. } else {
  34052. dracoGeometry = new dracoDecoder.PointCloud();
  34053. decodingStatus =
  34054. decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
  34055. }
  34056. if (!decodingStatus.ok() || dracoGeometry.ptr == 0) {
  34057. var errorMsg = 'THREE.DRACOLoader: Decoding failed: ';
  34058. errorMsg += decodingStatus.error_msg();
  34059. console.error(errorMsg);
  34060. dracoDecoder.destroy(decoder);
  34061. dracoDecoder.destroy(dracoGeometry);
  34062. throw new Error(errorMsg);
  34063. }
  34064. var decode_end = performance.now();
  34065. dracoDecoder.destroy(buffer);
  34066. /*
  34067. * Example on how to retrieve mesh and attributes.
  34068. */
  34069. var numFaces;
  34070. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  34071. numFaces = dracoGeometry.num_faces();
  34072. if (this.verbosity > 0) {
  34073. console.log('Number of faces loaded: ' + numFaces.toString());
  34074. }
  34075. } else {
  34076. numFaces = 0;
  34077. }
  34078. var numPoints = dracoGeometry.num_points();
  34079. var numAttributes = dracoGeometry.num_attributes();
  34080. if (this.verbosity > 0) {
  34081. console.log('Number of points loaded: ' + numPoints.toString());
  34082. console.log('Number of attributes loaded: ' +
  34083. numAttributes.toString());
  34084. }
  34085. // Verify if there is position attribute.
  34086. // TODO: Should not assume native Draco attribute IDs apply.
  34087. var posAttId = decoder.GetAttributeId(dracoGeometry,
  34088. dracoDecoder.POSITION);
  34089. if (posAttId == -1) {
  34090. var errorMsg = 'THREE.DRACOLoader: No position attribute found.';
  34091. console.error(errorMsg);
  34092. dracoDecoder.destroy(decoder);
  34093. dracoDecoder.destroy(dracoGeometry);
  34094. throw new Error(errorMsg);
  34095. }
  34096. var posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
  34097. // Structure for converting to THREEJS geometry later.
  34098. var geometryBuffer = {};
  34099. // Import data to Three JS geometry.
  34100. var geometry = new THREE.BufferGeometry();
  34101. // Do not use both the native attribute map and a provided (e.g. glTF) map.
  34102. if ( attributeUniqueIdMap ) {
  34103. // Add attributes of user specified unique id. E.g. GLTF models.
  34104. for (var attributeName in attributeUniqueIdMap) {
  34105. var attributeType = attributeTypeMap[attributeName];
  34106. var attributeId = attributeUniqueIdMap[attributeName];
  34107. var attribute = decoder.GetAttributeByUniqueId(dracoGeometry,
  34108. attributeId);
  34109. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  34110. attributeName, attributeType, attribute, geometry, geometryBuffer);
  34111. }
  34112. } else {
  34113. // Add native Draco attribute type to geometry.
  34114. for (var attributeName in this.nativeAttributeMap) {
  34115. var attId = decoder.GetAttributeId(dracoGeometry,
  34116. dracoDecoder[this.nativeAttributeMap[attributeName]]);
  34117. if (attId !== -1) {
  34118. if (this.verbosity > 0) {
  34119. console.log('Loaded ' + attributeName + ' attribute.');
  34120. }
  34121. var attribute = decoder.GetAttribute(dracoGeometry, attId);
  34122. this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
  34123. attributeName, Float32Array, attribute, geometry, geometryBuffer);
  34124. }
  34125. }
  34126. }
  34127. // For mesh, we need to generate the faces.
  34128. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  34129. if (this.drawMode === THREE.TriangleStripDrawMode) {
  34130. var stripsArray = new dracoDecoder.DracoInt32Array();
  34131. var numStrips = decoder.GetTriangleStripsFromMesh(
  34132. dracoGeometry, stripsArray);
  34133. geometryBuffer.indices = new Uint32Array(stripsArray.size());
  34134. for (var i = 0; i < stripsArray.size(); ++i) {
  34135. geometryBuffer.indices[i] = stripsArray.GetValue(i);
  34136. }
  34137. dracoDecoder.destroy(stripsArray);
  34138. } else {
  34139. var numIndices = numFaces * 3;
  34140. geometryBuffer.indices = new Uint32Array(numIndices);
  34141. var ia = new dracoDecoder.DracoInt32Array();
  34142. for (var i = 0; i < numFaces; ++i) {
  34143. decoder.GetFaceFromMesh(dracoGeometry, i, ia);
  34144. var index = i * 3;
  34145. geometryBuffer.indices[index] = ia.GetValue(0);
  34146. geometryBuffer.indices[index + 1] = ia.GetValue(1);
  34147. geometryBuffer.indices[index + 2] = ia.GetValue(2);
  34148. }
  34149. dracoDecoder.destroy(ia);
  34150. }
  34151. }
  34152. geometry.drawMode = this.drawMode;
  34153. if (geometryType == dracoDecoder.TRIANGULAR_MESH) {
  34154. geometry.setIndex(new(geometryBuffer.indices.length > 65535 ?
  34155. THREE.Uint32BufferAttribute : THREE.Uint16BufferAttribute)
  34156. (geometryBuffer.indices, 1));
  34157. }
  34158. // TODO: Should not assume native Draco attribute IDs apply.
  34159. // TODO: Can other attribute types be quantized?
  34160. var posTransform = new dracoDecoder.AttributeQuantizationTransform();
  34161. if (posTransform.InitFromAttribute(posAttribute)) {
  34162. // Quantized attribute. Store the quantization parameters into the
  34163. // THREE.js attribute.
  34164. geometry.attributes['position'].isQuantized = true;
  34165. geometry.attributes['position'].maxRange = posTransform.range();
  34166. geometry.attributes['position'].numQuantizationBits =
  34167. posTransform.quantization_bits();
  34168. geometry.attributes['position'].minValues = new Float32Array(3);
  34169. for (var i = 0; i < 3; ++i) {
  34170. geometry.attributes['position'].minValues[i] =
  34171. posTransform.min_value(i);
  34172. }
  34173. }
  34174. dracoDecoder.destroy(posTransform);
  34175. dracoDecoder.destroy(decoder);
  34176. dracoDecoder.destroy(dracoGeometry);
  34177. this.decode_time = decode_end - start_time;
  34178. this.import_time = performance.now() - decode_end;
  34179. if (this.verbosity > 0) {
  34180. console.log('Decode time: ' + this.decode_time);
  34181. console.log('Import time: ' + this.import_time);
  34182. }
  34183. return geometry;
  34184. },
  34185. isVersionSupported: function(version, callback) {
  34186. THREE.DRACOLoader.getDecoderModule()
  34187. .then( function ( module ) {
  34188. callback( module.decoder.isVersionSupported( version ) );
  34189. });
  34190. },
  34191. getAttributeOptions: function(attributeName) {
  34192. if (typeof this.attributeOptions[attributeName] === 'undefined')
  34193. this.attributeOptions[attributeName] = {};
  34194. return this.attributeOptions[attributeName];
  34195. }
  34196. };
  34197. THREE.DRACOLoader.decoderPath = './';
  34198. THREE.DRACOLoader.decoderConfig = {};
  34199. THREE.DRACOLoader.decoderModulePromise = null;
  34200. /**
  34201. * Sets the base path for decoder source files.
  34202. * @param {string} path
  34203. */
  34204. THREE.DRACOLoader.setDecoderPath = function ( path ) {
  34205. THREE.DRACOLoader.decoderPath = path;
  34206. };
  34207. /**
  34208. * Sets decoder configuration and releases singleton decoder module. Module
  34209. * will be recreated with the next decoding call.
  34210. * @param {Object} config
  34211. */
  34212. THREE.DRACOLoader.setDecoderConfig = function ( config ) {
  34213. var wasmBinary = THREE.DRACOLoader.decoderConfig.wasmBinary;
  34214. THREE.DRACOLoader.decoderConfig = config || {};
  34215. THREE.DRACOLoader.releaseDecoderModule();
  34216. // Reuse WASM binary.
  34217. if ( wasmBinary ) THREE.DRACOLoader.decoderConfig.wasmBinary = wasmBinary;
  34218. };
  34219. /**
  34220. * Releases the singleton DracoDecoderModule instance. Module will be recreated
  34221. * with the next decoding call.
  34222. */
  34223. THREE.DRACOLoader.releaseDecoderModule = function () {
  34224. THREE.DRACOLoader.decoderModulePromise = null;
  34225. };
  34226. /**
  34227. * Gets WebAssembly or asm.js singleton instance of DracoDecoderModule
  34228. * after testing for browser support. Returns Promise that resolves when
  34229. * module is available.
  34230. * @return {Promise<{decoder: DracoDecoderModule}>}
  34231. */
  34232. THREE.DRACOLoader.getDecoderModule = function () {
  34233. var scope = this;
  34234. var path = THREE.DRACOLoader.decoderPath;
  34235. var config = THREE.DRACOLoader.decoderConfig;
  34236. var promise = THREE.DRACOLoader.decoderModulePromise;
  34237. if ( promise ) return promise;
  34238. // Load source files.
  34239. if ( typeof DracoDecoderModule !== 'undefined' ) {
  34240. // Loaded externally.
  34241. promise = Promise.resolve();
  34242. } else if ( typeof WebAssembly !== 'object' || config.type === 'js' ) {
  34243. // Load with asm.js.
  34244. promise = THREE.DRACOLoader._loadScript( path + 'draco_decoder.js' );
  34245. } else {
  34246. // Load with WebAssembly.
  34247. config.wasmBinaryFile = path + 'draco_decoder.wasm';
  34248. promise = THREE.DRACOLoader._loadScript( path + 'draco_wasm_wrapper.js' )
  34249. .then( function () {
  34250. return THREE.DRACOLoader._loadArrayBuffer( config.wasmBinaryFile );
  34251. } )
  34252. .then( function ( wasmBinary ) {
  34253. config.wasmBinary = wasmBinary;
  34254. } );
  34255. }
  34256. // Wait for source files, then create and return a decoder.
  34257. promise = promise.then( function () {
  34258. return new Promise( function ( resolve ) {
  34259. config.onModuleLoaded = function ( decoder ) {
  34260. scope.timeLoaded = performance.now();
  34261. // Module is Promise-like. Wrap before resolving to avoid loop.
  34262. resolve( { decoder: decoder } );
  34263. };
  34264. DracoDecoderModule( config );
  34265. } );
  34266. } );
  34267. THREE.DRACOLoader.decoderModulePromise = promise;
  34268. return promise;
  34269. };
  34270. /**
  34271. * @param {string} src
  34272. * @return {Promise}
  34273. */
  34274. THREE.DRACOLoader._loadScript = function ( src ) {
  34275. var prevScript = document.getElementById( 'decoder_script' );
  34276. if ( prevScript !== null ) {
  34277. prevScript.parentNode.removeChild( prevScript );
  34278. }
  34279. var head = document.getElementsByTagName( 'head' )[ 0 ];
  34280. var script = document.createElement( 'script' );
  34281. script.id = 'decoder_script';
  34282. script.type = 'text/javascript';
  34283. script.src = src;
  34284. return new Promise( function ( resolve ) {
  34285. script.onload = resolve;
  34286. head.appendChild( script );
  34287. });
  34288. };
  34289. /**
  34290. * @param {string} src
  34291. * @return {Promise}
  34292. */
  34293. THREE.DRACOLoader._loadArrayBuffer = function ( src ) {
  34294. var loader = new THREE.FileLoader();
  34295. loader.setResponseType( 'arraybuffer' );
  34296. return new Promise( function( resolve, reject ) {
  34297. loader.load( src, resolve, undefined, reject );
  34298. });
  34299. };
  34300. },{}],38:[function(_dereq_,module,exports){
  34301. /**
  34302. * @author Rich Tibbett / https://github.com/richtr
  34303. * @author mrdoob / http://mrdoob.com/
  34304. * @author Tony Parisi / http://www.tonyparisi.com/
  34305. * @author Takahiro / https://github.com/takahirox
  34306. * @author Don McCurdy / https://www.donmccurdy.com
  34307. */
  34308. THREE.GLTFLoader = ( function () {
  34309. function GLTFLoader( manager ) {
  34310. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34311. this.dracoLoader = null;
  34312. }
  34313. GLTFLoader.prototype = {
  34314. constructor: GLTFLoader,
  34315. crossOrigin: 'anonymous',
  34316. load: function ( url, onLoad, onProgress, onError ) {
  34317. var scope = this;
  34318. var resourcePath;
  34319. if ( this.resourcePath !== undefined ) {
  34320. resourcePath = this.resourcePath;
  34321. } else if ( this.path !== undefined ) {
  34322. resourcePath = this.path;
  34323. } else {
  34324. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  34325. }
  34326. // Tells the LoadingManager to track an extra item, which resolves after
  34327. // the model is fully loaded. This means the count of items loaded will
  34328. // be incorrect, but ensures manager.onLoad() does not fire early.
  34329. scope.manager.itemStart( url );
  34330. var _onError = function ( e ) {
  34331. if ( onError ) {
  34332. onError( e );
  34333. } else {
  34334. console.error( e );
  34335. }
  34336. scope.manager.itemError( url );
  34337. scope.manager.itemEnd( url );
  34338. };
  34339. var loader = new THREE.FileLoader( scope.manager );
  34340. loader.setPath( this.path );
  34341. loader.setResponseType( 'arraybuffer' );
  34342. loader.load( url, function ( data ) {
  34343. try {
  34344. scope.parse( data, resourcePath, function ( gltf ) {
  34345. onLoad( gltf );
  34346. scope.manager.itemEnd( url );
  34347. }, _onError );
  34348. } catch ( e ) {
  34349. _onError( e );
  34350. }
  34351. }, onProgress, _onError );
  34352. },
  34353. setCrossOrigin: function ( value ) {
  34354. this.crossOrigin = value;
  34355. return this;
  34356. },
  34357. setPath: function ( value ) {
  34358. this.path = value;
  34359. return this;
  34360. },
  34361. setResourcePath: function ( value ) {
  34362. this.resourcePath = value;
  34363. return this;
  34364. },
  34365. setDRACOLoader: function ( dracoLoader ) {
  34366. this.dracoLoader = dracoLoader;
  34367. return this;
  34368. },
  34369. parse: function ( data, path, onLoad, onError ) {
  34370. var content;
  34371. var extensions = {};
  34372. if ( typeof data === 'string' ) {
  34373. content = data;
  34374. } else {
  34375. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  34376. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34377. try {
  34378. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34379. } catch ( error ) {
  34380. if ( onError ) onError( error );
  34381. return;
  34382. }
  34383. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34384. } else {
  34385. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  34386. }
  34387. }
  34388. var json = JSON.parse( content );
  34389. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  34390. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  34391. return;
  34392. }
  34393. if ( json.extensionsUsed ) {
  34394. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  34395. var extensionName = json.extensionsUsed[ i ];
  34396. var extensionsRequired = json.extensionsRequired || [];
  34397. switch ( extensionName ) {
  34398. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  34399. extensions[ extensionName ] = new GLTFLightsExtension( json );
  34400. break;
  34401. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  34402. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension( json );
  34403. break;
  34404. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  34405. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension( json );
  34406. break;
  34407. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  34408. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  34409. break;
  34410. case EXTENSIONS.MSFT_TEXTURE_DDS:
  34411. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension();
  34412. break;
  34413. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  34414. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension( json );
  34415. break;
  34416. default:
  34417. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  34418. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  34419. }
  34420. }
  34421. }
  34422. }
  34423. var parser = new GLTFParser( json, extensions, {
  34424. path: path || this.resourcePath || '',
  34425. crossOrigin: this.crossOrigin,
  34426. manager: this.manager
  34427. } );
  34428. parser.parse( onLoad, onError );
  34429. }
  34430. };
  34431. /* GLTFREGISTRY */
  34432. function GLTFRegistry() {
  34433. var objects = {};
  34434. return {
  34435. get: function ( key ) {
  34436. return objects[ key ];
  34437. },
  34438. add: function ( key, object ) {
  34439. objects[ key ] = object;
  34440. },
  34441. remove: function ( key ) {
  34442. delete objects[ key ];
  34443. },
  34444. removeAll: function () {
  34445. objects = {};
  34446. }
  34447. };
  34448. }
  34449. /*********************************/
  34450. /********** EXTENSIONS ***********/
  34451. /*********************************/
  34452. var EXTENSIONS = {
  34453. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34454. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  34455. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  34456. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  34457. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  34458. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  34459. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  34460. };
  34461. /**
  34462. * DDS Texture Extension
  34463. *
  34464. * Specification:
  34465. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  34466. *
  34467. */
  34468. function GLTFTextureDDSExtension() {
  34469. if ( ! THREE.DDSLoader ) {
  34470. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  34471. }
  34472. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  34473. this.ddsLoader = new THREE.DDSLoader();
  34474. }
  34475. /**
  34476. * Lights Extension
  34477. *
  34478. * Specification: PENDING
  34479. */
  34480. function GLTFLightsExtension( json ) {
  34481. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  34482. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  34483. this.lightDefs = extension.lights || [];
  34484. }
  34485. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  34486. var lightDef = this.lightDefs[ lightIndex ];
  34487. var lightNode;
  34488. var color = new THREE.Color( 0xffffff );
  34489. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  34490. var range = lightDef.range !== undefined ? lightDef.range : 0;
  34491. switch ( lightDef.type ) {
  34492. case 'directional':
  34493. lightNode = new THREE.DirectionalLight( color );
  34494. lightNode.target.position.set( 0, 0, - 1 );
  34495. lightNode.add( lightNode.target );
  34496. break;
  34497. case 'point':
  34498. lightNode = new THREE.PointLight( color );
  34499. lightNode.distance = range;
  34500. break;
  34501. case 'spot':
  34502. lightNode = new THREE.SpotLight( color );
  34503. lightNode.distance = range;
  34504. // Handle spotlight properties.
  34505. lightDef.spot = lightDef.spot || {};
  34506. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  34507. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  34508. lightNode.angle = lightDef.spot.outerConeAngle;
  34509. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  34510. lightNode.target.position.set( 0, 0, - 1 );
  34511. lightNode.add( lightNode.target );
  34512. break;
  34513. default:
  34514. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  34515. }
  34516. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  34517. // here, because node-level parsing will only override position if explicitly specified.
  34518. lightNode.position.set( 0, 0, 0 );
  34519. lightNode.decay = 2;
  34520. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  34521. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  34522. return Promise.resolve( lightNode );
  34523. };
  34524. /**
  34525. * Unlit Materials Extension (pending)
  34526. *
  34527. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  34528. */
  34529. function GLTFMaterialsUnlitExtension( json ) {
  34530. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  34531. }
  34532. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function ( material ) {
  34533. return THREE.MeshBasicMaterial;
  34534. };
  34535. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  34536. var pending = [];
  34537. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34538. materialParams.opacity = 1.0;
  34539. var metallicRoughness = material.pbrMetallicRoughness;
  34540. if ( metallicRoughness ) {
  34541. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  34542. var array = metallicRoughness.baseColorFactor;
  34543. materialParams.color.fromArray( array );
  34544. materialParams.opacity = array[ 3 ];
  34545. }
  34546. if ( metallicRoughness.baseColorTexture !== undefined ) {
  34547. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  34548. }
  34549. }
  34550. return Promise.all( pending );
  34551. };
  34552. /* BINARY EXTENSION */
  34553. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34554. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  34555. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  34556. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  34557. function GLTFBinaryExtension( data ) {
  34558. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34559. this.content = null;
  34560. this.body = null;
  34561. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34562. this.header = {
  34563. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  34564. version: headerView.getUint32( 4, true ),
  34565. length: headerView.getUint32( 8, true )
  34566. };
  34567. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  34568. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  34569. } else if ( this.header.version < 2.0 ) {
  34570. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  34571. }
  34572. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  34573. var chunkIndex = 0;
  34574. while ( chunkIndex < chunkView.byteLength ) {
  34575. var chunkLength = chunkView.getUint32( chunkIndex, true );
  34576. chunkIndex += 4;
  34577. var chunkType = chunkView.getUint32( chunkIndex, true );
  34578. chunkIndex += 4;
  34579. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  34580. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  34581. this.content = THREE.LoaderUtils.decodeText( contentArray );
  34582. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  34583. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  34584. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  34585. }
  34586. // Clients must ignore chunks with unknown types.
  34587. chunkIndex += chunkLength;
  34588. }
  34589. if ( this.content === null ) {
  34590. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  34591. }
  34592. }
  34593. /**
  34594. * DRACO Mesh Compression Extension
  34595. *
  34596. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  34597. */
  34598. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  34599. if ( ! dracoLoader ) {
  34600. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  34601. }
  34602. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  34603. this.json = json;
  34604. this.dracoLoader = dracoLoader;
  34605. }
  34606. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  34607. var json = this.json;
  34608. var dracoLoader = this.dracoLoader;
  34609. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  34610. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  34611. var threeAttributeMap = {};
  34612. var attributeNormalizedMap = {};
  34613. var attributeTypeMap = {};
  34614. for ( var attributeName in gltfAttributeMap ) {
  34615. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  34616. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  34617. }
  34618. for ( attributeName in primitive.attributes ) {
  34619. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  34620. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  34621. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  34622. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  34623. attributeTypeMap[ threeAttributeName ] = componentType;
  34624. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  34625. }
  34626. }
  34627. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  34628. return new Promise( function ( resolve ) {
  34629. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  34630. for ( var attributeName in geometry.attributes ) {
  34631. var attribute = geometry.attributes[ attributeName ];
  34632. var normalized = attributeNormalizedMap[ attributeName ];
  34633. if ( normalized !== undefined ) attribute.normalized = normalized;
  34634. }
  34635. resolve( geometry );
  34636. }, threeAttributeMap, attributeTypeMap );
  34637. } );
  34638. } );
  34639. };
  34640. /**
  34641. * Texture Transform Extension
  34642. *
  34643. * Specification:
  34644. */
  34645. function GLTFTextureTransformExtension( json ) {
  34646. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  34647. }
  34648. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  34649. texture = texture.clone();
  34650. if ( transform.offset !== undefined ) {
  34651. texture.offset.fromArray( transform.offset );
  34652. }
  34653. if ( transform.rotation !== undefined ) {
  34654. texture.rotation = transform.rotation;
  34655. }
  34656. if ( transform.scale !== undefined ) {
  34657. texture.repeat.fromArray( transform.scale );
  34658. }
  34659. if ( transform.texCoord !== undefined ) {
  34660. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  34661. }
  34662. texture.needsUpdate = true;
  34663. return texture;
  34664. };
  34665. /**
  34666. * Specular-Glossiness Extension
  34667. *
  34668. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  34669. */
  34670. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  34671. return {
  34672. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  34673. specularGlossinessParams: [
  34674. 'color',
  34675. 'map',
  34676. 'lightMap',
  34677. 'lightMapIntensity',
  34678. 'aoMap',
  34679. 'aoMapIntensity',
  34680. 'emissive',
  34681. 'emissiveIntensity',
  34682. 'emissiveMap',
  34683. 'bumpMap',
  34684. 'bumpScale',
  34685. 'normalMap',
  34686. 'displacementMap',
  34687. 'displacementScale',
  34688. 'displacementBias',
  34689. 'specularMap',
  34690. 'specular',
  34691. 'glossinessMap',
  34692. 'glossiness',
  34693. 'alphaMap',
  34694. 'envMap',
  34695. 'envMapIntensity',
  34696. 'refractionRatio',
  34697. ],
  34698. getMaterialType: function () {
  34699. return THREE.ShaderMaterial;
  34700. },
  34701. extendParams: function ( params, material, parser ) {
  34702. var pbrSpecularGlossiness = material.extensions[ this.name ];
  34703. var shader = THREE.ShaderLib[ 'standard' ];
  34704. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  34705. var specularMapParsFragmentChunk = [
  34706. '#ifdef USE_SPECULARMAP',
  34707. ' uniform sampler2D specularMap;',
  34708. '#endif'
  34709. ].join( '\n' );
  34710. var glossinessMapParsFragmentChunk = [
  34711. '#ifdef USE_GLOSSINESSMAP',
  34712. ' uniform sampler2D glossinessMap;',
  34713. '#endif'
  34714. ].join( '\n' );
  34715. var specularMapFragmentChunk = [
  34716. 'vec3 specularFactor = specular;',
  34717. '#ifdef USE_SPECULARMAP',
  34718. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  34719. ' texelSpecular = sRGBToLinear( texelSpecular );',
  34720. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34721. ' specularFactor *= texelSpecular.rgb;',
  34722. '#endif'
  34723. ].join( '\n' );
  34724. var glossinessMapFragmentChunk = [
  34725. 'float glossinessFactor = glossiness;',
  34726. '#ifdef USE_GLOSSINESSMAP',
  34727. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  34728. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34729. ' glossinessFactor *= texelGlossiness.a;',
  34730. '#endif'
  34731. ].join( '\n' );
  34732. var lightPhysicalFragmentChunk = [
  34733. 'PhysicalMaterial material;',
  34734. 'material.diffuseColor = diffuseColor.rgb;',
  34735. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  34736. 'material.specularColor = specularFactor.rgb;',
  34737. ].join( '\n' );
  34738. var fragmentShader = shader.fragmentShader
  34739. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  34740. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  34741. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  34742. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  34743. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  34744. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  34745. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  34746. delete uniforms.roughness;
  34747. delete uniforms.metalness;
  34748. delete uniforms.roughnessMap;
  34749. delete uniforms.metalnessMap;
  34750. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  34751. uniforms.glossiness = { value: 0.5 };
  34752. uniforms.specularMap = { value: null };
  34753. uniforms.glossinessMap = { value: null };
  34754. params.vertexShader = shader.vertexShader;
  34755. params.fragmentShader = fragmentShader;
  34756. params.uniforms = uniforms;
  34757. params.defines = { 'STANDARD': '' };
  34758. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34759. params.opacity = 1.0;
  34760. var pending = [];
  34761. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  34762. var array = pbrSpecularGlossiness.diffuseFactor;
  34763. params.color.fromArray( array );
  34764. params.opacity = array[ 3 ];
  34765. }
  34766. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  34767. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  34768. }
  34769. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  34770. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  34771. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  34772. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  34773. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  34774. }
  34775. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  34776. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  34777. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossMapDef ) );
  34778. pending.push( parser.assignTexture( params, 'specularMap', specGlossMapDef ) );
  34779. }
  34780. return Promise.all( pending );
  34781. },
  34782. createMaterial: function ( params ) {
  34783. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  34784. var material = new THREE.ShaderMaterial( {
  34785. defines: params.defines,
  34786. vertexShader: params.vertexShader,
  34787. fragmentShader: params.fragmentShader,
  34788. uniforms: params.uniforms,
  34789. fog: true,
  34790. lights: true,
  34791. opacity: params.opacity,
  34792. transparent: params.transparent
  34793. } );
  34794. material.isGLTFSpecularGlossinessMaterial = true;
  34795. material.color = params.color;
  34796. material.map = params.map === undefined ? null : params.map;
  34797. material.lightMap = null;
  34798. material.lightMapIntensity = 1.0;
  34799. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  34800. material.aoMapIntensity = 1.0;
  34801. material.emissive = params.emissive;
  34802. material.emissiveIntensity = 1.0;
  34803. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  34804. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  34805. material.bumpScale = 1;
  34806. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  34807. if ( params.normalScale ) material.normalScale = params.normalScale;
  34808. material.displacementMap = null;
  34809. material.displacementScale = 1;
  34810. material.displacementBias = 0;
  34811. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  34812. material.specular = params.specular;
  34813. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  34814. material.glossiness = params.glossiness;
  34815. material.alphaMap = null;
  34816. material.envMap = params.envMap === undefined ? null : params.envMap;
  34817. material.envMapIntensity = 1.0;
  34818. material.refractionRatio = 0.98;
  34819. material.extensions.derivatives = true;
  34820. return material;
  34821. },
  34822. /**
  34823. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  34824. * copy only properties it knows about or inherits, and misses many properties that would
  34825. * normally be defined by MeshStandardMaterial.
  34826. *
  34827. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  34828. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  34829. * AND also updating `.onBeforeRender` on the parent mesh.
  34830. *
  34831. * @param {THREE.ShaderMaterial} source
  34832. * @return {THREE.ShaderMaterial}
  34833. */
  34834. cloneMaterial: function ( source ) {
  34835. var target = source.clone();
  34836. target.isGLTFSpecularGlossinessMaterial = true;
  34837. var params = this.specularGlossinessParams;
  34838. for ( var i = 0, il = params.length; i < il; i ++ ) {
  34839. target[ params[ i ] ] = source[ params[ i ] ];
  34840. }
  34841. return target;
  34842. },
  34843. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  34844. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  34845. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  34846. return;
  34847. }
  34848. var uniforms = material.uniforms;
  34849. var defines = material.defines;
  34850. uniforms.opacity.value = material.opacity;
  34851. uniforms.diffuse.value.copy( material.color );
  34852. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  34853. uniforms.map.value = material.map;
  34854. uniforms.specularMap.value = material.specularMap;
  34855. uniforms.alphaMap.value = material.alphaMap;
  34856. uniforms.lightMap.value = material.lightMap;
  34857. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  34858. uniforms.aoMap.value = material.aoMap;
  34859. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  34860. // uv repeat and offset setting priorities
  34861. // 1. color map
  34862. // 2. specular map
  34863. // 3. normal map
  34864. // 4. bump map
  34865. // 5. alpha map
  34866. // 6. emissive map
  34867. var uvScaleMap;
  34868. if ( material.map ) {
  34869. uvScaleMap = material.map;
  34870. } else if ( material.specularMap ) {
  34871. uvScaleMap = material.specularMap;
  34872. } else if ( material.displacementMap ) {
  34873. uvScaleMap = material.displacementMap;
  34874. } else if ( material.normalMap ) {
  34875. uvScaleMap = material.normalMap;
  34876. } else if ( material.bumpMap ) {
  34877. uvScaleMap = material.bumpMap;
  34878. } else if ( material.glossinessMap ) {
  34879. uvScaleMap = material.glossinessMap;
  34880. } else if ( material.alphaMap ) {
  34881. uvScaleMap = material.alphaMap;
  34882. } else if ( material.emissiveMap ) {
  34883. uvScaleMap = material.emissiveMap;
  34884. }
  34885. if ( uvScaleMap !== undefined ) {
  34886. // backwards compatibility
  34887. if ( uvScaleMap.isWebGLRenderTarget ) {
  34888. uvScaleMap = uvScaleMap.texture;
  34889. }
  34890. if ( uvScaleMap.matrixAutoUpdate === true ) {
  34891. uvScaleMap.updateMatrix();
  34892. }
  34893. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  34894. }
  34895. if ( material.envMap ) {
  34896. uniforms.envMap.value = material.envMap;
  34897. uniforms.envMapIntensity.value = material.envMapIntensity;
  34898. // don't flip CubeTexture envMaps, flip everything else:
  34899. // WebGLRenderTargetCube will be flipped for backwards compatibility
  34900. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  34901. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  34902. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  34903. uniforms.reflectivity.value = material.reflectivity;
  34904. uniforms.refractionRatio.value = material.refractionRatio;
  34905. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  34906. }
  34907. uniforms.specular.value.copy( material.specular );
  34908. uniforms.glossiness.value = material.glossiness;
  34909. uniforms.glossinessMap.value = material.glossinessMap;
  34910. uniforms.emissiveMap.value = material.emissiveMap;
  34911. uniforms.bumpMap.value = material.bumpMap;
  34912. uniforms.normalMap.value = material.normalMap;
  34913. uniforms.displacementMap.value = material.displacementMap;
  34914. uniforms.displacementScale.value = material.displacementScale;
  34915. uniforms.displacementBias.value = material.displacementBias;
  34916. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  34917. defines.USE_GLOSSINESSMAP = '';
  34918. // set USE_ROUGHNESSMAP to enable vUv
  34919. defines.USE_ROUGHNESSMAP = '';
  34920. }
  34921. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  34922. delete defines.USE_GLOSSINESSMAP;
  34923. delete defines.USE_ROUGHNESSMAP;
  34924. }
  34925. }
  34926. };
  34927. }
  34928. /*********************************/
  34929. /********** INTERPOLATION ********/
  34930. /*********************************/
  34931. // Spline Interpolation
  34932. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  34933. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  34934. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  34935. }
  34936. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  34937. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  34938. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  34939. // Copies a sample value to the result buffer. See description of glTF
  34940. // CUBICSPLINE values layout in interpolate_() function below.
  34941. var result = this.resultBuffer,
  34942. values = this.sampleValues,
  34943. valueSize = this.valueSize,
  34944. offset = index * valueSize * 3 + valueSize;
  34945. for ( var i = 0; i !== valueSize; i ++ ) {
  34946. result[ i ] = values[ offset + i ];
  34947. }
  34948. return result;
  34949. };
  34950. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  34951. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  34952. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  34953. var result = this.resultBuffer;
  34954. var values = this.sampleValues;
  34955. var stride = this.valueSize;
  34956. var stride2 = stride * 2;
  34957. var stride3 = stride * 3;
  34958. var td = t1 - t0;
  34959. var p = ( t - t0 ) / td;
  34960. var pp = p * p;
  34961. var ppp = pp * p;
  34962. var offset1 = i1 * stride3;
  34963. var offset0 = offset1 - stride3;
  34964. var s2 = - 2 * ppp + 3 * pp;
  34965. var s3 = ppp - pp;
  34966. var s0 = 1 - s2;
  34967. var s1 = s3 - pp + p;
  34968. // Layout of keyframe output values for CUBICSPLINE animations:
  34969. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  34970. for ( var i = 0; i !== stride; i ++ ) {
  34971. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  34972. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  34973. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  34974. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  34975. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  34976. }
  34977. return result;
  34978. };
  34979. /*********************************/
  34980. /********** INTERNALS ************/
  34981. /*********************************/
  34982. /* CONSTANTS */
  34983. var WEBGL_CONSTANTS = {
  34984. FLOAT: 5126,
  34985. //FLOAT_MAT2: 35674,
  34986. FLOAT_MAT3: 35675,
  34987. FLOAT_MAT4: 35676,
  34988. FLOAT_VEC2: 35664,
  34989. FLOAT_VEC3: 35665,
  34990. FLOAT_VEC4: 35666,
  34991. LINEAR: 9729,
  34992. REPEAT: 10497,
  34993. SAMPLER_2D: 35678,
  34994. POINTS: 0,
  34995. LINES: 1,
  34996. LINE_LOOP: 2,
  34997. LINE_STRIP: 3,
  34998. TRIANGLES: 4,
  34999. TRIANGLE_STRIP: 5,
  35000. TRIANGLE_FAN: 6,
  35001. UNSIGNED_BYTE: 5121,
  35002. UNSIGNED_SHORT: 5123
  35003. };
  35004. var WEBGL_TYPE = {
  35005. 5126: Number,
  35006. //35674: THREE.Matrix2,
  35007. 35675: THREE.Matrix3,
  35008. 35676: THREE.Matrix4,
  35009. 35664: THREE.Vector2,
  35010. 35665: THREE.Vector3,
  35011. 35666: THREE.Vector4,
  35012. 35678: THREE.Texture
  35013. };
  35014. var WEBGL_COMPONENT_TYPES = {
  35015. 5120: Int8Array,
  35016. 5121: Uint8Array,
  35017. 5122: Int16Array,
  35018. 5123: Uint16Array,
  35019. 5125: Uint32Array,
  35020. 5126: Float32Array
  35021. };
  35022. var WEBGL_FILTERS = {
  35023. 9728: THREE.NearestFilter,
  35024. 9729: THREE.LinearFilter,
  35025. 9984: THREE.NearestMipMapNearestFilter,
  35026. 9985: THREE.LinearMipMapNearestFilter,
  35027. 9986: THREE.NearestMipMapLinearFilter,
  35028. 9987: THREE.LinearMipMapLinearFilter
  35029. };
  35030. var WEBGL_WRAPPINGS = {
  35031. 33071: THREE.ClampToEdgeWrapping,
  35032. 33648: THREE.MirroredRepeatWrapping,
  35033. 10497: THREE.RepeatWrapping
  35034. };
  35035. var WEBGL_SIDES = {
  35036. 1028: THREE.BackSide, // Culling front
  35037. 1029: THREE.FrontSide // Culling back
  35038. //1032: THREE.NoSide // Culling front and back, what to do?
  35039. };
  35040. var WEBGL_DEPTH_FUNCS = {
  35041. 512: THREE.NeverDepth,
  35042. 513: THREE.LessDepth,
  35043. 514: THREE.EqualDepth,
  35044. 515: THREE.LessEqualDepth,
  35045. 516: THREE.GreaterEqualDepth,
  35046. 517: THREE.NotEqualDepth,
  35047. 518: THREE.GreaterEqualDepth,
  35048. 519: THREE.AlwaysDepth
  35049. };
  35050. var WEBGL_BLEND_EQUATIONS = {
  35051. 32774: THREE.AddEquation,
  35052. 32778: THREE.SubtractEquation,
  35053. 32779: THREE.ReverseSubtractEquation
  35054. };
  35055. var WEBGL_BLEND_FUNCS = {
  35056. 0: THREE.ZeroFactor,
  35057. 1: THREE.OneFactor,
  35058. 768: THREE.SrcColorFactor,
  35059. 769: THREE.OneMinusSrcColorFactor,
  35060. 770: THREE.SrcAlphaFactor,
  35061. 771: THREE.OneMinusSrcAlphaFactor,
  35062. 772: THREE.DstAlphaFactor,
  35063. 773: THREE.OneMinusDstAlphaFactor,
  35064. 774: THREE.DstColorFactor,
  35065. 775: THREE.OneMinusDstColorFactor,
  35066. 776: THREE.SrcAlphaSaturateFactor
  35067. // The followings are not supported by Three.js yet
  35068. //32769: CONSTANT_COLOR,
  35069. //32770: ONE_MINUS_CONSTANT_COLOR,
  35070. //32771: CONSTANT_ALPHA,
  35071. //32772: ONE_MINUS_CONSTANT_COLOR
  35072. };
  35073. var WEBGL_TYPE_SIZES = {
  35074. 'SCALAR': 1,
  35075. 'VEC2': 2,
  35076. 'VEC3': 3,
  35077. 'VEC4': 4,
  35078. 'MAT2': 4,
  35079. 'MAT3': 9,
  35080. 'MAT4': 16
  35081. };
  35082. var ATTRIBUTES = {
  35083. POSITION: 'position',
  35084. NORMAL: 'normal',
  35085. TANGENT: 'tangent',
  35086. TEXCOORD_0: 'uv',
  35087. TEXCOORD_1: 'uv2',
  35088. COLOR_0: 'color',
  35089. WEIGHTS_0: 'skinWeight',
  35090. JOINTS_0: 'skinIndex',
  35091. };
  35092. var PATH_PROPERTIES = {
  35093. scale: 'scale',
  35094. translation: 'position',
  35095. rotation: 'quaternion',
  35096. weights: 'morphTargetInfluences'
  35097. };
  35098. var INTERPOLATION = {
  35099. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  35100. // keyframe track will be initialized with a default interpolation type, then modified.
  35101. LINEAR: THREE.InterpolateLinear,
  35102. STEP: THREE.InterpolateDiscrete
  35103. };
  35104. var STATES_ENABLES = {
  35105. 2884: 'CULL_FACE',
  35106. 2929: 'DEPTH_TEST',
  35107. 3042: 'BLEND',
  35108. 3089: 'SCISSOR_TEST',
  35109. 32823: 'POLYGON_OFFSET_FILL',
  35110. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  35111. };
  35112. var ALPHA_MODES = {
  35113. OPAQUE: 'OPAQUE',
  35114. MASK: 'MASK',
  35115. BLEND: 'BLEND'
  35116. };
  35117. var MIME_TYPE_FORMATS = {
  35118. 'image/png': THREE.RGBAFormat,
  35119. 'image/jpeg': THREE.RGBFormat
  35120. };
  35121. /* UTILITY FUNCTIONS */
  35122. function resolveURL( url, path ) {
  35123. // Invalid URL
  35124. if ( typeof url !== 'string' || url === '' ) return '';
  35125. // Absolute URL http://,https://,//
  35126. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35127. // Data URI
  35128. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35129. // Blob URL
  35130. if ( /^blob:.*$/i.test( url ) ) return url;
  35131. // Relative URL
  35132. return path + url;
  35133. }
  35134. var defaultMaterial;
  35135. /**
  35136. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  35137. */
  35138. function createDefaultMaterial() {
  35139. defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( {
  35140. color: 0xFFFFFF,
  35141. emissive: 0x000000,
  35142. metalness: 1,
  35143. roughness: 1,
  35144. transparent: false,
  35145. depthTest: true,
  35146. side: THREE.FrontSide
  35147. } );
  35148. return defaultMaterial;
  35149. }
  35150. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  35151. // Add unknown glTF extensions to an object's userData.
  35152. for ( var name in objectDef.extensions ) {
  35153. if ( knownExtensions[ name ] === undefined ) {
  35154. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  35155. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  35156. }
  35157. }
  35158. }
  35159. /**
  35160. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  35161. * @param {GLTF.definition} gltfDef
  35162. */
  35163. function assignExtrasToUserData( object, gltfDef ) {
  35164. if ( gltfDef.extras !== undefined ) {
  35165. if ( typeof gltfDef.extras === 'object' ) {
  35166. object.userData = gltfDef.extras;
  35167. } else {
  35168. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  35169. }
  35170. }
  35171. }
  35172. /**
  35173. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  35174. *
  35175. * @param {THREE.BufferGeometry} geometry
  35176. * @param {Array<GLTF.Target>} targets
  35177. * @param {GLTFParser} parser
  35178. * @return {Promise<THREE.BufferGeometry>}
  35179. */
  35180. function addMorphTargets( geometry, targets, parser ) {
  35181. var hasMorphPosition = false;
  35182. var hasMorphNormal = false;
  35183. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35184. var target = targets[ i ];
  35185. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  35186. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  35187. if ( hasMorphPosition && hasMorphNormal ) break;
  35188. }
  35189. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  35190. var pendingPositionAccessors = [];
  35191. var pendingNormalAccessors = [];
  35192. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35193. var target = targets[ i ];
  35194. if ( hasMorphPosition ) {
  35195. var pendingAccessor = target.POSITION !== undefined
  35196. ? parser.getDependency( 'accessor', target.POSITION )
  35197. : geometry.attributes.position;
  35198. pendingPositionAccessors.push( pendingAccessor );
  35199. }
  35200. if ( hasMorphNormal ) {
  35201. var pendingAccessor = target.NORMAL !== undefined
  35202. ? parser.getDependency( 'accessor', target.NORMAL )
  35203. : geometry.attributes.normal;
  35204. pendingNormalAccessors.push( pendingAccessor );
  35205. }
  35206. }
  35207. return Promise.all( [
  35208. Promise.all( pendingPositionAccessors ),
  35209. Promise.all( pendingNormalAccessors )
  35210. ] ).then( function ( accessors ) {
  35211. var morphPositions = accessors[ 0 ];
  35212. var morphNormals = accessors[ 1 ];
  35213. // Clone morph target accessors before modifying them.
  35214. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  35215. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  35216. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  35217. }
  35218. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  35219. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  35220. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  35221. }
  35222. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35223. var target = targets[ i ];
  35224. var attributeName = 'morphTarget' + i;
  35225. if ( hasMorphPosition ) {
  35226. // Three.js morph position is absolute value. The formula is
  35227. // basePosition
  35228. // + weight0 * ( morphPosition0 - basePosition )
  35229. // + weight1 * ( morphPosition1 - basePosition )
  35230. // ...
  35231. // while the glTF one is relative
  35232. // basePosition
  35233. // + weight0 * glTFmorphPosition0
  35234. // + weight1 * glTFmorphPosition1
  35235. // ...
  35236. // then we need to convert from relative to absolute here.
  35237. if ( target.POSITION !== undefined ) {
  35238. var positionAttribute = morphPositions[ i ];
  35239. positionAttribute.name = attributeName;
  35240. var position = geometry.attributes.position;
  35241. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  35242. positionAttribute.setXYZ(
  35243. j,
  35244. positionAttribute.getX( j ) + position.getX( j ),
  35245. positionAttribute.getY( j ) + position.getY( j ),
  35246. positionAttribute.getZ( j ) + position.getZ( j )
  35247. );
  35248. }
  35249. }
  35250. }
  35251. if ( hasMorphNormal ) {
  35252. // see target.POSITION's comment
  35253. if ( target.NORMAL !== undefined ) {
  35254. var normalAttribute = morphNormals[ i ];
  35255. normalAttribute.name = attributeName;
  35256. var normal = geometry.attributes.normal;
  35257. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  35258. normalAttribute.setXYZ(
  35259. j,
  35260. normalAttribute.getX( j ) + normal.getX( j ),
  35261. normalAttribute.getY( j ) + normal.getY( j ),
  35262. normalAttribute.getZ( j ) + normal.getZ( j )
  35263. );
  35264. }
  35265. }
  35266. }
  35267. }
  35268. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  35269. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  35270. return geometry;
  35271. } );
  35272. }
  35273. /**
  35274. * @param {THREE.Mesh} mesh
  35275. * @param {GLTF.Mesh} meshDef
  35276. */
  35277. function updateMorphTargets( mesh, meshDef ) {
  35278. mesh.updateMorphTargets();
  35279. if ( meshDef.weights !== undefined ) {
  35280. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  35281. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  35282. }
  35283. }
  35284. // .extras has user-defined data, so check that .extras.targetNames is an array.
  35285. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  35286. var targetNames = meshDef.extras.targetNames;
  35287. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  35288. mesh.morphTargetDictionary = {};
  35289. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  35290. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  35291. }
  35292. } else {
  35293. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  35294. }
  35295. }
  35296. }
  35297. function isObjectEqual( a, b ) {
  35298. if ( Object.keys( a ).length !== Object.keys( b ).length ) return false;
  35299. for ( var key in a ) {
  35300. if ( a[ key ] !== b[ key ] ) return false;
  35301. }
  35302. return true;
  35303. }
  35304. function createPrimitiveKey( primitiveDef ) {
  35305. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  35306. var geometryKey;
  35307. if ( dracoExtension ) {
  35308. geometryKey = 'draco:' + dracoExtension.bufferView
  35309. + ':' + dracoExtension.indices
  35310. + ':' + createAttributesKey( dracoExtension.attributes );
  35311. } else {
  35312. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  35313. }
  35314. return geometryKey;
  35315. }
  35316. function createAttributesKey( attributes ) {
  35317. var attributesKey = '';
  35318. var keys = Object.keys( attributes ).sort();
  35319. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  35320. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  35321. }
  35322. return attributesKey;
  35323. }
  35324. function cloneBufferAttribute( attribute ) {
  35325. if ( attribute.isInterleavedBufferAttribute ) {
  35326. var count = attribute.count;
  35327. var itemSize = attribute.itemSize;
  35328. var array = attribute.array.slice( 0, count * itemSize );
  35329. for ( var i = 0, j = 0; i < count; ++ i ) {
  35330. array[ j ++ ] = attribute.getX( i );
  35331. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  35332. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  35333. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  35334. }
  35335. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  35336. }
  35337. return attribute.clone();
  35338. }
  35339. /* GLTF PARSER */
  35340. function GLTFParser( json, extensions, options ) {
  35341. this.json = json || {};
  35342. this.extensions = extensions || {};
  35343. this.options = options || {};
  35344. // loader object cache
  35345. this.cache = new GLTFRegistry();
  35346. // BufferGeometry caching
  35347. this.primitiveCache = {};
  35348. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  35349. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  35350. this.fileLoader = new THREE.FileLoader( this.options.manager );
  35351. this.fileLoader.setResponseType( 'arraybuffer' );
  35352. }
  35353. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  35354. var parser = this;
  35355. var json = this.json;
  35356. var extensions = this.extensions;
  35357. // Clear the loader cache
  35358. this.cache.removeAll();
  35359. // Mark the special nodes/meshes in json for efficient parse
  35360. this.markDefs();
  35361. Promise.all( [
  35362. this.getDependencies( 'scene' ),
  35363. this.getDependencies( 'animation' ),
  35364. this.getDependencies( 'camera' ),
  35365. ] ).then( function ( dependencies ) {
  35366. var result = {
  35367. scene: dependencies[ 0 ][ json.scene || 0 ],
  35368. scenes: dependencies[ 0 ],
  35369. animations: dependencies[ 1 ],
  35370. cameras: dependencies[ 2 ],
  35371. asset: json.asset,
  35372. parser: parser,
  35373. userData: {}
  35374. };
  35375. addUnknownExtensionsToUserData( extensions, result, json );
  35376. onLoad( result );
  35377. } ).catch( onError );
  35378. };
  35379. /**
  35380. * Marks the special nodes/meshes in json for efficient parse.
  35381. */
  35382. GLTFParser.prototype.markDefs = function () {
  35383. var nodeDefs = this.json.nodes || [];
  35384. var skinDefs = this.json.skins || [];
  35385. var meshDefs = this.json.meshes || [];
  35386. var meshReferences = {};
  35387. var meshUses = {};
  35388. // Nothing in the node definition indicates whether it is a Bone or an
  35389. // Object3D. Use the skins' joint references to mark bones.
  35390. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  35391. var joints = skinDefs[ skinIndex ].joints;
  35392. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  35393. nodeDefs[ joints[ i ] ].isBone = true;
  35394. }
  35395. }
  35396. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  35397. // avoid having more than one THREE.Mesh with the same name, count
  35398. // references and rename instances below.
  35399. //
  35400. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  35401. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  35402. var nodeDef = nodeDefs[ nodeIndex ];
  35403. if ( nodeDef.mesh !== undefined ) {
  35404. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  35405. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  35406. }
  35407. meshReferences[ nodeDef.mesh ] ++;
  35408. // Nothing in the mesh definition indicates whether it is
  35409. // a SkinnedMesh or Mesh. Use the node's mesh reference
  35410. // to mark SkinnedMesh if node has skin.
  35411. if ( nodeDef.skin !== undefined ) {
  35412. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  35413. }
  35414. }
  35415. }
  35416. this.json.meshReferences = meshReferences;
  35417. this.json.meshUses = meshUses;
  35418. };
  35419. /**
  35420. * Requests the specified dependency asynchronously, with caching.
  35421. * @param {string} type
  35422. * @param {number} index
  35423. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  35424. */
  35425. GLTFParser.prototype.getDependency = function ( type, index ) {
  35426. var cacheKey = type + ':' + index;
  35427. var dependency = this.cache.get( cacheKey );
  35428. if ( ! dependency ) {
  35429. switch ( type ) {
  35430. case 'scene':
  35431. dependency = this.loadScene( index );
  35432. break;
  35433. case 'node':
  35434. dependency = this.loadNode( index );
  35435. break;
  35436. case 'mesh':
  35437. dependency = this.loadMesh( index );
  35438. break;
  35439. case 'accessor':
  35440. dependency = this.loadAccessor( index );
  35441. break;
  35442. case 'bufferView':
  35443. dependency = this.loadBufferView( index );
  35444. break;
  35445. case 'buffer':
  35446. dependency = this.loadBuffer( index );
  35447. break;
  35448. case 'material':
  35449. dependency = this.loadMaterial( index );
  35450. break;
  35451. case 'texture':
  35452. dependency = this.loadTexture( index );
  35453. break;
  35454. case 'skin':
  35455. dependency = this.loadSkin( index );
  35456. break;
  35457. case 'animation':
  35458. dependency = this.loadAnimation( index );
  35459. break;
  35460. case 'camera':
  35461. dependency = this.loadCamera( index );
  35462. break;
  35463. case 'light':
  35464. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  35465. break;
  35466. default:
  35467. throw new Error( 'Unknown type: ' + type );
  35468. }
  35469. this.cache.add( cacheKey, dependency );
  35470. }
  35471. return dependency;
  35472. };
  35473. /**
  35474. * Requests all dependencies of the specified type asynchronously, with caching.
  35475. * @param {string} type
  35476. * @return {Promise<Array<Object>>}
  35477. */
  35478. GLTFParser.prototype.getDependencies = function ( type ) {
  35479. var dependencies = this.cache.get( type );
  35480. if ( ! dependencies ) {
  35481. var parser = this;
  35482. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  35483. dependencies = Promise.all( defs.map( function ( def, index ) {
  35484. return parser.getDependency( type, index );
  35485. } ) );
  35486. this.cache.add( type, dependencies );
  35487. }
  35488. return dependencies;
  35489. };
  35490. /**
  35491. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35492. * @param {number} bufferIndex
  35493. * @return {Promise<ArrayBuffer>}
  35494. */
  35495. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  35496. var bufferDef = this.json.buffers[ bufferIndex ];
  35497. var loader = this.fileLoader;
  35498. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  35499. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  35500. }
  35501. // If present, GLB container is required to be the first buffer.
  35502. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  35503. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  35504. }
  35505. var options = this.options;
  35506. return new Promise( function ( resolve, reject ) {
  35507. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  35508. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  35509. } );
  35510. } );
  35511. };
  35512. /**
  35513. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35514. * @param {number} bufferViewIndex
  35515. * @return {Promise<ArrayBuffer>}
  35516. */
  35517. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  35518. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  35519. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  35520. var byteLength = bufferViewDef.byteLength || 0;
  35521. var byteOffset = bufferViewDef.byteOffset || 0;
  35522. return buffer.slice( byteOffset, byteOffset + byteLength );
  35523. } );
  35524. };
  35525. /**
  35526. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  35527. * @param {number} accessorIndex
  35528. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  35529. */
  35530. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  35531. var parser = this;
  35532. var json = this.json;
  35533. var accessorDef = this.json.accessors[ accessorIndex ];
  35534. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  35535. // Ignore empty accessors, which may be used to declare runtime
  35536. // information about attributes coming from another source (e.g. Draco
  35537. // compression extension).
  35538. return Promise.resolve( null );
  35539. }
  35540. var pendingBufferViews = [];
  35541. if ( accessorDef.bufferView !== undefined ) {
  35542. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  35543. } else {
  35544. pendingBufferViews.push( null );
  35545. }
  35546. if ( accessorDef.sparse !== undefined ) {
  35547. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  35548. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  35549. }
  35550. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  35551. var bufferView = bufferViews[ 0 ];
  35552. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  35553. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  35554. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  35555. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  35556. var itemBytes = elementBytes * itemSize;
  35557. var byteOffset = accessorDef.byteOffset || 0;
  35558. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  35559. var normalized = accessorDef.normalized === true;
  35560. var array, bufferAttribute;
  35561. // The buffer is not interleaved if the stride is the item size in bytes.
  35562. if ( byteStride && byteStride !== itemBytes ) {
  35563. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  35564. var ib = parser.cache.get( ibCacheKey );
  35565. if ( ! ib ) {
  35566. // Use the full buffer if it's interleaved.
  35567. array = new TypedArray( bufferView );
  35568. // Integer parameters to IB/IBA are in array elements, not bytes.
  35569. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  35570. parser.cache.add( ibCacheKey, ib );
  35571. }
  35572. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  35573. } else {
  35574. if ( bufferView === null ) {
  35575. array = new TypedArray( accessorDef.count * itemSize );
  35576. } else {
  35577. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  35578. }
  35579. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  35580. }
  35581. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  35582. if ( accessorDef.sparse !== undefined ) {
  35583. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  35584. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  35585. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  35586. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  35587. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  35588. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  35589. if ( bufferView !== null ) {
  35590. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  35591. bufferAttribute.setArray( bufferAttribute.array.slice() );
  35592. }
  35593. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  35594. var index = sparseIndices[ i ];
  35595. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  35596. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  35597. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  35598. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  35599. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  35600. }
  35601. }
  35602. return bufferAttribute;
  35603. } );
  35604. };
  35605. /**
  35606. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  35607. * @param {number} textureIndex
  35608. * @return {Promise<THREE.Texture>}
  35609. */
  35610. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  35611. var parser = this;
  35612. var json = this.json;
  35613. var options = this.options;
  35614. var textureLoader = this.textureLoader;
  35615. var URL = window.URL || window.webkitURL;
  35616. var textureDef = json.textures[ textureIndex ];
  35617. var textureExtensions = textureDef.extensions || {};
  35618. var source;
  35619. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  35620. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  35621. } else {
  35622. source = json.images[ textureDef.source ];
  35623. }
  35624. var sourceURI = source.uri;
  35625. var isObjectURL = false;
  35626. if ( source.bufferView !== undefined ) {
  35627. // Load binary image data from bufferView, if provided.
  35628. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  35629. isObjectURL = true;
  35630. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  35631. sourceURI = URL.createObjectURL( blob );
  35632. return sourceURI;
  35633. } );
  35634. }
  35635. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  35636. // Load Texture resource.
  35637. var loader = THREE.Loader.Handlers.get( sourceURI );
  35638. if ( ! loader ) {
  35639. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  35640. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  35641. : textureLoader;
  35642. }
  35643. return new Promise( function ( resolve, reject ) {
  35644. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  35645. } );
  35646. } ).then( function ( texture ) {
  35647. // Clean up resources and configure Texture.
  35648. if ( isObjectURL === true ) {
  35649. URL.revokeObjectURL( sourceURI );
  35650. }
  35651. texture.flipY = false;
  35652. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  35653. // Ignore unknown mime types, like DDS files.
  35654. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  35655. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  35656. }
  35657. var samplers = json.samplers || {};
  35658. var sampler = samplers[ textureDef.sampler ] || {};
  35659. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  35660. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  35661. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  35662. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  35663. return texture;
  35664. } );
  35665. };
  35666. /**
  35667. * Asynchronously assigns a texture to the given material parameters.
  35668. * @param {Object} materialParams
  35669. * @param {string} mapName
  35670. * @param {Object} mapDef
  35671. * @return {Promise}
  35672. */
  35673. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  35674. var parser = this;
  35675. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  35676. switch ( mapName ) {
  35677. case 'aoMap':
  35678. case 'emissiveMap':
  35679. case 'metalnessMap':
  35680. case 'normalMap':
  35681. case 'roughnessMap':
  35682. texture.format = THREE.RGBFormat;
  35683. break;
  35684. }
  35685. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  35686. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  35687. if ( transform ) {
  35688. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  35689. }
  35690. }
  35691. materialParams[ mapName ] = texture;
  35692. } );
  35693. };
  35694. /**
  35695. * Assigns final material to a Mesh, Line, or Points instance. The instance
  35696. * already has a material (generated from the glTF material options alone)
  35697. * but reuse of the same glTF material may require multiple threejs materials
  35698. * to accomodate different primitive types, defines, etc. New materials will
  35699. * be created if necessary, and reused from a cache.
  35700. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  35701. */
  35702. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  35703. var geometry = mesh.geometry;
  35704. var material = mesh.material;
  35705. var extensions = this.extensions;
  35706. var useVertexTangents = geometry.attributes.tangent !== undefined;
  35707. var useVertexColors = geometry.attributes.color !== undefined;
  35708. var useFlatShading = geometry.attributes.normal === undefined;
  35709. var useSkinning = mesh.isSkinnedMesh === true;
  35710. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  35711. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  35712. if ( mesh.isPoints ) {
  35713. var cacheKey = 'PointsMaterial:' + material.uuid;
  35714. var pointsMaterial = this.cache.get( cacheKey );
  35715. if ( ! pointsMaterial ) {
  35716. pointsMaterial = new THREE.PointsMaterial();
  35717. THREE.Material.prototype.copy.call( pointsMaterial, material );
  35718. pointsMaterial.color.copy( material.color );
  35719. pointsMaterial.map = material.map;
  35720. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  35721. this.cache.add( cacheKey, pointsMaterial );
  35722. }
  35723. material = pointsMaterial;
  35724. } else if ( mesh.isLine ) {
  35725. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  35726. var lineMaterial = this.cache.get( cacheKey );
  35727. if ( ! lineMaterial ) {
  35728. lineMaterial = new THREE.LineBasicMaterial();
  35729. THREE.Material.prototype.copy.call( lineMaterial, material );
  35730. lineMaterial.color.copy( material.color );
  35731. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  35732. this.cache.add( cacheKey, lineMaterial );
  35733. }
  35734. material = lineMaterial;
  35735. }
  35736. // Clone the material if it will be modified
  35737. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  35738. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  35739. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  35740. if ( useSkinning ) cacheKey += 'skinning:';
  35741. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  35742. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  35743. if ( useFlatShading ) cacheKey += 'flat-shading:';
  35744. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  35745. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  35746. var cachedMaterial = this.cache.get( cacheKey );
  35747. if ( ! cachedMaterial ) {
  35748. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  35749. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  35750. : material.clone();
  35751. if ( useSkinning ) cachedMaterial.skinning = true;
  35752. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  35753. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  35754. if ( useFlatShading ) cachedMaterial.flatShading = true;
  35755. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  35756. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  35757. this.cache.add( cacheKey, cachedMaterial );
  35758. }
  35759. material = cachedMaterial;
  35760. }
  35761. // workarounds for mesh and geometry
  35762. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  35763. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  35764. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  35765. }
  35766. if ( material.isGLTFSpecularGlossinessMaterial ) {
  35767. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  35768. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  35769. }
  35770. mesh.material = material;
  35771. };
  35772. /**
  35773. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  35774. * @param {number} materialIndex
  35775. * @return {Promise<THREE.Material>}
  35776. */
  35777. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  35778. var parser = this;
  35779. var json = this.json;
  35780. var extensions = this.extensions;
  35781. var materialDef = json.materials[ materialIndex ];
  35782. var materialType;
  35783. var materialParams = {};
  35784. var materialExtensions = materialDef.extensions || {};
  35785. var pending = [];
  35786. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  35787. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35788. materialType = sgExtension.getMaterialType( materialDef );
  35789. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  35790. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  35791. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  35792. materialType = kmuExtension.getMaterialType( materialDef );
  35793. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  35794. } else {
  35795. // Specification:
  35796. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  35797. materialType = THREE.MeshStandardMaterial;
  35798. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  35799. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35800. materialParams.opacity = 1.0;
  35801. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35802. var array = metallicRoughness.baseColorFactor;
  35803. materialParams.color.fromArray( array );
  35804. materialParams.opacity = array[ 3 ];
  35805. }
  35806. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35807. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  35808. }
  35809. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  35810. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  35811. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  35812. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  35813. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  35814. }
  35815. }
  35816. if ( materialDef.doubleSided === true ) {
  35817. materialParams.side = THREE.DoubleSide;
  35818. }
  35819. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  35820. if ( alphaMode === ALPHA_MODES.BLEND ) {
  35821. materialParams.transparent = true;
  35822. } else {
  35823. materialParams.transparent = false;
  35824. if ( alphaMode === ALPHA_MODES.MASK ) {
  35825. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  35826. }
  35827. }
  35828. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35829. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  35830. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  35831. if ( materialDef.normalTexture.scale !== undefined ) {
  35832. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  35833. }
  35834. }
  35835. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35836. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  35837. if ( materialDef.occlusionTexture.strength !== undefined ) {
  35838. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  35839. }
  35840. }
  35841. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35842. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  35843. }
  35844. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  35845. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  35846. }
  35847. return Promise.all( pending ).then( function () {
  35848. var material;
  35849. if ( materialType === THREE.ShaderMaterial ) {
  35850. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  35851. } else {
  35852. material = new materialType( materialParams );
  35853. }
  35854. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  35855. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  35856. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  35857. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  35858. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  35859. assignExtrasToUserData( material, materialDef );
  35860. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  35861. return material;
  35862. } );
  35863. };
  35864. /**
  35865. * @param {THREE.BufferGeometry} geometry
  35866. * @param {GLTF.Primitive} primitiveDef
  35867. * @param {GLTFParser} parser
  35868. * @return {Promise<THREE.BufferGeometry>}
  35869. */
  35870. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  35871. var attributes = primitiveDef.attributes;
  35872. var pending = [];
  35873. function assignAttributeAccessor( accessorIndex, attributeName ) {
  35874. return parser.getDependency( 'accessor', accessorIndex )
  35875. .then( function ( accessor ) {
  35876. geometry.addAttribute( attributeName, accessor );
  35877. } );
  35878. }
  35879. for ( var gltfAttributeName in attributes ) {
  35880. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  35881. // Skip attributes already provided by e.g. Draco extension.
  35882. if ( threeAttributeName in geometry.attributes ) continue;
  35883. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  35884. }
  35885. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  35886. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  35887. geometry.setIndex( accessor );
  35888. } );
  35889. pending.push( accessor );
  35890. }
  35891. assignExtrasToUserData( geometry, primitiveDef );
  35892. return Promise.all( pending ).then( function () {
  35893. return primitiveDef.targets !== undefined
  35894. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  35895. : geometry;
  35896. } );
  35897. }
  35898. /**
  35899. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  35900. *
  35901. * Creates BufferGeometries from primitives.
  35902. *
  35903. * @param {Array<GLTF.Primitive>} primitives
  35904. * @return {Promise<Array<THREE.BufferGeometry>>}
  35905. */
  35906. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  35907. var parser = this;
  35908. var extensions = this.extensions;
  35909. var cache = this.primitiveCache;
  35910. function createDracoPrimitive( primitive ) {
  35911. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  35912. .decodePrimitive( primitive, parser )
  35913. .then( function ( geometry ) {
  35914. return addPrimitiveAttributes( geometry, primitive, parser );
  35915. } );
  35916. }
  35917. var pending = [];
  35918. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35919. var primitive = primitives[ i ];
  35920. var cacheKey = createPrimitiveKey( primitive );
  35921. // See if we've already created this geometry
  35922. var cached = cache[ cacheKey ];
  35923. if ( cached ) {
  35924. // Use the cached geometry if it exists
  35925. pending.push( cached.promise );
  35926. } else {
  35927. var geometryPromise;
  35928. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  35929. // Use DRACO geometry if available
  35930. geometryPromise = createDracoPrimitive( primitive );
  35931. } else {
  35932. // Otherwise create a new geometry
  35933. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  35934. }
  35935. // Cache this geometry
  35936. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  35937. pending.push( geometryPromise );
  35938. }
  35939. }
  35940. return Promise.all( pending );
  35941. };
  35942. /**
  35943. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  35944. * @param {number} meshIndex
  35945. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  35946. */
  35947. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  35948. var parser = this;
  35949. var json = this.json;
  35950. var extensions = this.extensions;
  35951. var meshDef = json.meshes[ meshIndex ];
  35952. var primitives = meshDef.primitives;
  35953. var pending = [];
  35954. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35955. var material = primitives[ i ].material === undefined
  35956. ? createDefaultMaterial()
  35957. : this.getDependency( 'material', primitives[ i ].material );
  35958. pending.push( material );
  35959. }
  35960. return Promise.all( pending ).then( function ( originalMaterials ) {
  35961. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  35962. var meshes = [];
  35963. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  35964. var geometry = geometries[ i ];
  35965. var primitive = primitives[ i ];
  35966. // 1. create Mesh
  35967. var mesh;
  35968. var material = originalMaterials[ i ];
  35969. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  35970. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  35971. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  35972. primitive.mode === undefined ) {
  35973. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  35974. mesh = meshDef.isSkinnedMesh === true
  35975. ? new THREE.SkinnedMesh( geometry, material )
  35976. : new THREE.Mesh( geometry, material );
  35977. if ( mesh.isSkinnedMesh === true ) mesh.normalizeSkinWeights(); // #15319
  35978. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  35979. mesh.drawMode = THREE.TriangleStripDrawMode;
  35980. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  35981. mesh.drawMode = THREE.TriangleFanDrawMode;
  35982. }
  35983. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  35984. mesh = new THREE.LineSegments( geometry, material );
  35985. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  35986. mesh = new THREE.Line( geometry, material );
  35987. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  35988. mesh = new THREE.LineLoop( geometry, material );
  35989. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  35990. mesh = new THREE.Points( geometry, material );
  35991. } else {
  35992. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  35993. }
  35994. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  35995. updateMorphTargets( mesh, meshDef );
  35996. }
  35997. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  35998. if ( geometries.length > 1 ) mesh.name += '_' + i;
  35999. assignExtrasToUserData( mesh, meshDef );
  36000. parser.assignFinalMaterial( mesh );
  36001. meshes.push( mesh );
  36002. }
  36003. if ( meshes.length === 1 ) {
  36004. return meshes[ 0 ];
  36005. }
  36006. var group = new THREE.Group();
  36007. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36008. group.add( meshes[ i ] );
  36009. }
  36010. return group;
  36011. } );
  36012. } );
  36013. };
  36014. /**
  36015. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  36016. * @param {number} cameraIndex
  36017. * @return {Promise<THREE.Camera>}
  36018. */
  36019. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  36020. var camera;
  36021. var cameraDef = this.json.cameras[ cameraIndex ];
  36022. var params = cameraDef[ cameraDef.type ];
  36023. if ( ! params ) {
  36024. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  36025. return;
  36026. }
  36027. if ( cameraDef.type === 'perspective' ) {
  36028. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  36029. } else if ( cameraDef.type === 'orthographic' ) {
  36030. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  36031. }
  36032. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  36033. assignExtrasToUserData( camera, cameraDef );
  36034. return Promise.resolve( camera );
  36035. };
  36036. /**
  36037. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  36038. * @param {number} skinIndex
  36039. * @return {Promise<Object>}
  36040. */
  36041. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  36042. var skinDef = this.json.skins[ skinIndex ];
  36043. var skinEntry = { joints: skinDef.joints };
  36044. if ( skinDef.inverseBindMatrices === undefined ) {
  36045. return Promise.resolve( skinEntry );
  36046. }
  36047. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  36048. skinEntry.inverseBindMatrices = accessor;
  36049. return skinEntry;
  36050. } );
  36051. };
  36052. /**
  36053. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  36054. * @param {number} animationIndex
  36055. * @return {Promise<THREE.AnimationClip>}
  36056. */
  36057. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  36058. var json = this.json;
  36059. var animationDef = json.animations[ animationIndex ];
  36060. var pendingNodes = [];
  36061. var pendingInputAccessors = [];
  36062. var pendingOutputAccessors = [];
  36063. var pendingSamplers = [];
  36064. var pendingTargets = [];
  36065. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  36066. var channel = animationDef.channels[ i ];
  36067. var sampler = animationDef.samplers[ channel.sampler ];
  36068. var target = channel.target;
  36069. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  36070. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  36071. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  36072. pendingNodes.push( this.getDependency( 'node', name ) );
  36073. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  36074. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  36075. pendingSamplers.push( sampler );
  36076. pendingTargets.push( target );
  36077. }
  36078. return Promise.all( [
  36079. Promise.all( pendingNodes ),
  36080. Promise.all( pendingInputAccessors ),
  36081. Promise.all( pendingOutputAccessors ),
  36082. Promise.all( pendingSamplers ),
  36083. Promise.all( pendingTargets )
  36084. ] ).then( function ( dependencies ) {
  36085. var nodes = dependencies[ 0 ];
  36086. var inputAccessors = dependencies[ 1 ];
  36087. var outputAccessors = dependencies[ 2 ];
  36088. var samplers = dependencies[ 3 ];
  36089. var targets = dependencies[ 4 ];
  36090. var tracks = [];
  36091. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  36092. var node = nodes[ i ];
  36093. var inputAccessor = inputAccessors[ i ];
  36094. var outputAccessor = outputAccessors[ i ];
  36095. var sampler = samplers[ i ];
  36096. var target = targets[ i ];
  36097. if ( node === undefined ) continue;
  36098. node.updateMatrix();
  36099. node.matrixAutoUpdate = true;
  36100. var TypedKeyframeTrack;
  36101. switch ( PATH_PROPERTIES[ target.path ] ) {
  36102. case PATH_PROPERTIES.weights:
  36103. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  36104. break;
  36105. case PATH_PROPERTIES.rotation:
  36106. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  36107. break;
  36108. case PATH_PROPERTIES.position:
  36109. case PATH_PROPERTIES.scale:
  36110. default:
  36111. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  36112. break;
  36113. }
  36114. var targetName = node.name ? node.name : node.uuid;
  36115. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  36116. var targetNames = [];
  36117. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  36118. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  36119. node.traverse( function ( object ) {
  36120. if ( object.isMesh === true && object.morphTargetInfluences ) {
  36121. targetNames.push( object.name ? object.name : object.uuid );
  36122. }
  36123. } );
  36124. } else {
  36125. targetNames.push( targetName );
  36126. }
  36127. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  36128. var track = new TypedKeyframeTrack(
  36129. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  36130. inputAccessor.array,
  36131. outputAccessor.array,
  36132. interpolation
  36133. );
  36134. // Override interpolation with custom factory method.
  36135. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  36136. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  36137. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  36138. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  36139. // must be divided by three to get the interpolant's sampleSize argument.
  36140. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  36141. };
  36142. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  36143. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  36144. }
  36145. tracks.push( track );
  36146. }
  36147. }
  36148. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  36149. return new THREE.AnimationClip( name, undefined, tracks );
  36150. } );
  36151. };
  36152. /**
  36153. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  36154. * @param {number} nodeIndex
  36155. * @return {Promise<THREE.Object3D>}
  36156. */
  36157. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  36158. var json = this.json;
  36159. var extensions = this.extensions;
  36160. var parser = this;
  36161. var meshReferences = json.meshReferences;
  36162. var meshUses = json.meshUses;
  36163. var nodeDef = json.nodes[ nodeIndex ];
  36164. return ( function () {
  36165. // .isBone isn't in glTF spec. See .markDefs
  36166. if ( nodeDef.isBone === true ) {
  36167. return Promise.resolve( new THREE.Bone() );
  36168. } else if ( nodeDef.mesh !== undefined ) {
  36169. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  36170. var node;
  36171. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  36172. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  36173. node = mesh.clone();
  36174. node.name += '_instance_' + instanceNum;
  36175. // onBeforeRender copy for Specular-Glossiness
  36176. node.onBeforeRender = mesh.onBeforeRender;
  36177. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  36178. node.children[ i ].name += '_instance_' + instanceNum;
  36179. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  36180. }
  36181. } else {
  36182. node = mesh;
  36183. }
  36184. // if weights are provided on the node, override weights on the mesh.
  36185. if ( nodeDef.weights !== undefined ) {
  36186. node.traverse( function ( o ) {
  36187. if ( ! o.isMesh ) return;
  36188. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  36189. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  36190. }
  36191. } );
  36192. }
  36193. return node;
  36194. } );
  36195. } else if ( nodeDef.camera !== undefined ) {
  36196. return parser.getDependency( 'camera', nodeDef.camera );
  36197. } else if ( nodeDef.extensions
  36198. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  36199. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  36200. return parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light );
  36201. } else {
  36202. return Promise.resolve( new THREE.Object3D() );
  36203. }
  36204. }() ).then( function ( node ) {
  36205. if ( nodeDef.name !== undefined ) {
  36206. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  36207. }
  36208. assignExtrasToUserData( node, nodeDef );
  36209. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  36210. if ( nodeDef.matrix !== undefined ) {
  36211. var matrix = new THREE.Matrix4();
  36212. matrix.fromArray( nodeDef.matrix );
  36213. node.applyMatrix( matrix );
  36214. } else {
  36215. if ( nodeDef.translation !== undefined ) {
  36216. node.position.fromArray( nodeDef.translation );
  36217. }
  36218. if ( nodeDef.rotation !== undefined ) {
  36219. node.quaternion.fromArray( nodeDef.rotation );
  36220. }
  36221. if ( nodeDef.scale !== undefined ) {
  36222. node.scale.fromArray( nodeDef.scale );
  36223. }
  36224. }
  36225. return node;
  36226. } );
  36227. };
  36228. /**
  36229. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  36230. * @param {number} sceneIndex
  36231. * @return {Promise<THREE.Scene>}
  36232. */
  36233. GLTFParser.prototype.loadScene = function () {
  36234. // scene node hierachy builder
  36235. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  36236. var nodeDef = json.nodes[ nodeId ];
  36237. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  36238. if ( nodeDef.skin === undefined ) return node;
  36239. // build skeleton here as well
  36240. var skinEntry;
  36241. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  36242. skinEntry = skin;
  36243. var pendingJoints = [];
  36244. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  36245. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  36246. }
  36247. return Promise.all( pendingJoints );
  36248. } ).then( function ( jointNodes ) {
  36249. var meshes = node.isGroup === true ? node.children : [ node ];
  36250. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  36251. var mesh = meshes[ i ];
  36252. var bones = [];
  36253. var boneInverses = [];
  36254. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  36255. var jointNode = jointNodes[ j ];
  36256. if ( jointNode ) {
  36257. bones.push( jointNode );
  36258. var mat = new THREE.Matrix4();
  36259. if ( skinEntry.inverseBindMatrices !== undefined ) {
  36260. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  36261. }
  36262. boneInverses.push( mat );
  36263. } else {
  36264. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  36265. }
  36266. }
  36267. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  36268. }
  36269. return node;
  36270. } );
  36271. } ).then( function ( node ) {
  36272. // build node hierachy
  36273. parentObject.add( node );
  36274. var pending = [];
  36275. if ( nodeDef.children ) {
  36276. var children = nodeDef.children;
  36277. for ( var i = 0, il = children.length; i < il; i ++ ) {
  36278. var child = children[ i ];
  36279. pending.push( buildNodeHierachy( child, node, json, parser ) );
  36280. }
  36281. }
  36282. return Promise.all( pending );
  36283. } );
  36284. }
  36285. return function loadScene( sceneIndex ) {
  36286. var json = this.json;
  36287. var extensions = this.extensions;
  36288. var sceneDef = this.json.scenes[ sceneIndex ];
  36289. var parser = this;
  36290. var scene = new THREE.Scene();
  36291. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  36292. assignExtrasToUserData( scene, sceneDef );
  36293. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  36294. var nodeIds = sceneDef.nodes || [];
  36295. var pending = [];
  36296. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  36297. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  36298. }
  36299. return Promise.all( pending ).then( function () {
  36300. return scene;
  36301. } );
  36302. };
  36303. }();
  36304. return GLTFLoader;
  36305. } )();
  36306. },{}],39:[function(_dereq_,module,exports){
  36307. /**
  36308. * Loads a Wavefront .mtl file specifying materials
  36309. *
  36310. * @author angelxuanchang
  36311. */
  36312. THREE.MTLLoader = function ( manager ) {
  36313. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36314. };
  36315. THREE.MTLLoader.prototype = {
  36316. constructor: THREE.MTLLoader,
  36317. /**
  36318. * Loads and parses a MTL asset from a URL.
  36319. *
  36320. * @param {String} url - URL to the MTL file.
  36321. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  36322. * @param {Function} [onProgress] - Callback for download progress.
  36323. * @param {Function} [onError] - Callback for download errors.
  36324. *
  36325. * @see setPath setResourcePath
  36326. *
  36327. * @note In order for relative texture references to resolve correctly
  36328. * you must call setResourcePath() explicitly prior to load.
  36329. */
  36330. load: function ( url, onLoad, onProgress, onError ) {
  36331. var scope = this;
  36332. var path = ( this.path === undefined ) ? THREE.LoaderUtils.extractUrlBase( url ) : this.path;
  36333. var loader = new THREE.FileLoader( this.manager );
  36334. loader.setPath( this.path );
  36335. loader.load( url, function ( text ) {
  36336. onLoad( scope.parse( text, path ) );
  36337. }, onProgress, onError );
  36338. },
  36339. /**
  36340. * Set base path for resolving references.
  36341. * If set this path will be prepended to each loaded and found reference.
  36342. *
  36343. * @see setResourcePath
  36344. * @param {String} path
  36345. * @return {THREE.MTLLoader}
  36346. *
  36347. * @example
  36348. * mtlLoader.setPath( 'assets/obj/' );
  36349. * mtlLoader.load( 'my.mtl', ... );
  36350. */
  36351. setPath: function ( path ) {
  36352. this.path = path;
  36353. return this;
  36354. },
  36355. /**
  36356. * Set base path for additional resources like textures.
  36357. *
  36358. * @see setPath
  36359. * @param {String} path
  36360. * @return {THREE.MTLLoader}
  36361. *
  36362. * @example
  36363. * mtlLoader.setPath( 'assets/obj/' );
  36364. * mtlLoader.setResourcePath( 'assets/textures/' );
  36365. * mtlLoader.load( 'my.mtl', ... );
  36366. */
  36367. setResourcePath: function ( path ) {
  36368. this.resourcePath = path;
  36369. return this;
  36370. },
  36371. setTexturePath: function ( path ) {
  36372. console.warn( 'THREE.MTLLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  36373. return this.setResourcePath( path );
  36374. },
  36375. setCrossOrigin: function ( value ) {
  36376. this.crossOrigin = value;
  36377. return this;
  36378. },
  36379. setMaterialOptions: function ( value ) {
  36380. this.materialOptions = value;
  36381. return this;
  36382. },
  36383. /**
  36384. * Parses a MTL file.
  36385. *
  36386. * @param {String} text - Content of MTL file
  36387. * @return {THREE.MTLLoader.MaterialCreator}
  36388. *
  36389. * @see setPath setResourcePath
  36390. *
  36391. * @note In order for relative texture references to resolve correctly
  36392. * you must call setResourcePath() explicitly prior to parse.
  36393. */
  36394. parse: function ( text, path ) {
  36395. var lines = text.split( '\n' );
  36396. var info = {};
  36397. var delimiter_pattern = /\s+/;
  36398. var materialsInfo = {};
  36399. for ( var i = 0; i < lines.length; i ++ ) {
  36400. var line = lines[ i ];
  36401. line = line.trim();
  36402. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  36403. // Blank line or comment ignore
  36404. continue;
  36405. }
  36406. var pos = line.indexOf( ' ' );
  36407. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  36408. key = key.toLowerCase();
  36409. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  36410. value = value.trim();
  36411. if ( key === 'newmtl' ) {
  36412. // New material
  36413. info = { name: value };
  36414. materialsInfo[ value ] = info;
  36415. } else {
  36416. if ( key === 'ka' || key === 'kd' || key === 'ks' || key ==='ke' ) {
  36417. var ss = value.split( delimiter_pattern, 3 );
  36418. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  36419. } else {
  36420. info[ key ] = value;
  36421. }
  36422. }
  36423. }
  36424. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  36425. materialCreator.setCrossOrigin( this.crossOrigin );
  36426. materialCreator.setManager( this.manager );
  36427. materialCreator.setMaterials( materialsInfo );
  36428. return materialCreator;
  36429. }
  36430. };
  36431. /**
  36432. * Create a new THREE-MTLLoader.MaterialCreator
  36433. * @param baseUrl - Url relative to which textures are loaded
  36434. * @param options - Set of options on how to construct the materials
  36435. * side: Which side to apply the material
  36436. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  36437. * wrap: What type of wrapping to apply for textures
  36438. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  36439. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  36440. * Default: false, assumed to be already normalized
  36441. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  36442. * Default: false
  36443. * @constructor
  36444. */
  36445. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  36446. this.baseUrl = baseUrl || '';
  36447. this.options = options;
  36448. this.materialsInfo = {};
  36449. this.materials = {};
  36450. this.materialsArray = [];
  36451. this.nameLookup = {};
  36452. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  36453. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  36454. };
  36455. THREE.MTLLoader.MaterialCreator.prototype = {
  36456. constructor: THREE.MTLLoader.MaterialCreator,
  36457. crossOrigin: 'anonymous',
  36458. setCrossOrigin: function ( value ) {
  36459. this.crossOrigin = value;
  36460. return this;
  36461. },
  36462. setManager: function ( value ) {
  36463. this.manager = value;
  36464. },
  36465. setMaterials: function ( materialsInfo ) {
  36466. this.materialsInfo = this.convert( materialsInfo );
  36467. this.materials = {};
  36468. this.materialsArray = [];
  36469. this.nameLookup = {};
  36470. },
  36471. convert: function ( materialsInfo ) {
  36472. if ( ! this.options ) return materialsInfo;
  36473. var converted = {};
  36474. for ( var mn in materialsInfo ) {
  36475. // Convert materials info into normalized form based on options
  36476. var mat = materialsInfo[ mn ];
  36477. var covmat = {};
  36478. converted[ mn ] = covmat;
  36479. for ( var prop in mat ) {
  36480. var save = true;
  36481. var value = mat[ prop ];
  36482. var lprop = prop.toLowerCase();
  36483. switch ( lprop ) {
  36484. case 'kd':
  36485. case 'ka':
  36486. case 'ks':
  36487. // Diffuse color (color under white light) using RGB values
  36488. if ( this.options && this.options.normalizeRGB ) {
  36489. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  36490. }
  36491. if ( this.options && this.options.ignoreZeroRGBs ) {
  36492. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  36493. // ignore
  36494. save = false;
  36495. }
  36496. }
  36497. break;
  36498. default:
  36499. break;
  36500. }
  36501. if ( save ) {
  36502. covmat[ lprop ] = value;
  36503. }
  36504. }
  36505. }
  36506. return converted;
  36507. },
  36508. preload: function () {
  36509. for ( var mn in this.materialsInfo ) {
  36510. this.create( mn );
  36511. }
  36512. },
  36513. getIndex: function ( materialName ) {
  36514. return this.nameLookup[ materialName ];
  36515. },
  36516. getAsArray: function () {
  36517. var index = 0;
  36518. for ( var mn in this.materialsInfo ) {
  36519. this.materialsArray[ index ] = this.create( mn );
  36520. this.nameLookup[ mn ] = index;
  36521. index ++;
  36522. }
  36523. return this.materialsArray;
  36524. },
  36525. create: function ( materialName ) {
  36526. if ( this.materials[ materialName ] === undefined ) {
  36527. this.createMaterial_( materialName );
  36528. }
  36529. return this.materials[ materialName ];
  36530. },
  36531. createMaterial_: function ( materialName ) {
  36532. // Create material
  36533. var scope = this;
  36534. var mat = this.materialsInfo[ materialName ];
  36535. var params = {
  36536. name: materialName,
  36537. side: this.side
  36538. };
  36539. function resolveURL( baseUrl, url ) {
  36540. if ( typeof url !== 'string' || url === '' )
  36541. return '';
  36542. // Absolute URL
  36543. if ( /^https?:\/\//i.test( url ) ) return url;
  36544. return baseUrl + url;
  36545. }
  36546. function setMapForType( mapType, value ) {
  36547. if ( params[ mapType ] ) return; // Keep the first encountered texture
  36548. var texParams = scope.getTextureParams( value, params );
  36549. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  36550. map.repeat.copy( texParams.scale );
  36551. map.offset.copy( texParams.offset );
  36552. map.wrapS = scope.wrap;
  36553. map.wrapT = scope.wrap;
  36554. params[ mapType ] = map;
  36555. }
  36556. for ( var prop in mat ) {
  36557. var value = mat[ prop ];
  36558. var n;
  36559. if ( value === '' ) continue;
  36560. switch ( prop.toLowerCase() ) {
  36561. // Ns is material specular exponent
  36562. case 'kd':
  36563. // Diffuse color (color under white light) using RGB values
  36564. params.color = new THREE.Color().fromArray( value );
  36565. break;
  36566. case 'ks':
  36567. // Specular color (color when light is reflected from shiny surface) using RGB values
  36568. params.specular = new THREE.Color().fromArray( value );
  36569. break;
  36570. case 'ke':
  36571. // Emissive using RGB values
  36572. params.emissive = new THREE.Color().fromArray( value );
  36573. break;
  36574. case 'map_kd':
  36575. // Diffuse texture map
  36576. setMapForType( "map", value );
  36577. break;
  36578. case 'map_ks':
  36579. // Specular map
  36580. setMapForType( "specularMap", value );
  36581. break;
  36582. case 'map_ke':
  36583. // Emissive map
  36584. setMapForType( "emissiveMap", value );
  36585. break;
  36586. case 'norm':
  36587. setMapForType( "normalMap", value );
  36588. break;
  36589. case 'map_bump':
  36590. case 'bump':
  36591. // Bump texture map
  36592. setMapForType( "bumpMap", value );
  36593. break;
  36594. case 'map_d':
  36595. // Alpha map
  36596. setMapForType( "alphaMap", value );
  36597. params.transparent = true;
  36598. break;
  36599. case 'ns':
  36600. // The specular exponent (defines the focus of the specular highlight)
  36601. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  36602. params.shininess = parseFloat( value );
  36603. break;
  36604. case 'd':
  36605. n = parseFloat( value );
  36606. if ( n < 1 ) {
  36607. params.opacity = n;
  36608. params.transparent = true;
  36609. }
  36610. break;
  36611. case 'tr':
  36612. n = parseFloat( value );
  36613. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  36614. if ( n > 0 ) {
  36615. params.opacity = 1 - n;
  36616. params.transparent = true;
  36617. }
  36618. break;
  36619. default:
  36620. break;
  36621. }
  36622. }
  36623. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  36624. return this.materials[ materialName ];
  36625. },
  36626. getTextureParams: function ( value, matParams ) {
  36627. var texParams = {
  36628. scale: new THREE.Vector2( 1, 1 ),
  36629. offset: new THREE.Vector2( 0, 0 )
  36630. };
  36631. var items = value.split( /\s+/ );
  36632. var pos;
  36633. pos = items.indexOf( '-bm' );
  36634. if ( pos >= 0 ) {
  36635. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  36636. items.splice( pos, 2 );
  36637. }
  36638. pos = items.indexOf( '-s' );
  36639. if ( pos >= 0 ) {
  36640. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36641. items.splice( pos, 4 ); // we expect 3 parameters here!
  36642. }
  36643. pos = items.indexOf( '-o' );
  36644. if ( pos >= 0 ) {
  36645. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36646. items.splice( pos, 4 ); // we expect 3 parameters here!
  36647. }
  36648. texParams.url = items.join( ' ' ).trim();
  36649. return texParams;
  36650. },
  36651. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  36652. var texture;
  36653. var loader = THREE.Loader.Handlers.get( url );
  36654. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  36655. if ( loader === null ) {
  36656. loader = new THREE.TextureLoader( manager );
  36657. }
  36658. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  36659. texture = loader.load( url, onLoad, onProgress, onError );
  36660. if ( mapping !== undefined ) texture.mapping = mapping;
  36661. return texture;
  36662. }
  36663. };
  36664. },{}],40:[function(_dereq_,module,exports){
  36665. /**
  36666. * @author mrdoob / http://mrdoob.com/
  36667. */
  36668. THREE.OBJLoader = ( function () {
  36669. // o object_name | g group_name
  36670. var object_pattern = /^[og]\s*(.+)?/;
  36671. // mtllib file_reference
  36672. var material_library_pattern = /^mtllib /;
  36673. // usemtl material_name
  36674. var material_use_pattern = /^usemtl /;
  36675. function ParserState() {
  36676. var state = {
  36677. objects: [],
  36678. object: {},
  36679. vertices: [],
  36680. normals: [],
  36681. colors: [],
  36682. uvs: [],
  36683. materialLibraries: [],
  36684. startObject: function ( name, fromDeclaration ) {
  36685. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  36686. // file. We need to use it for the first parsed g/o to keep things in sync.
  36687. if ( this.object && this.object.fromDeclaration === false ) {
  36688. this.object.name = name;
  36689. this.object.fromDeclaration = ( fromDeclaration !== false );
  36690. return;
  36691. }
  36692. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  36693. if ( this.object && typeof this.object._finalize === 'function' ) {
  36694. this.object._finalize( true );
  36695. }
  36696. this.object = {
  36697. name: name || '',
  36698. fromDeclaration: ( fromDeclaration !== false ),
  36699. geometry: {
  36700. vertices: [],
  36701. normals: [],
  36702. colors: [],
  36703. uvs: []
  36704. },
  36705. materials: [],
  36706. smooth: true,
  36707. startMaterial: function ( name, libraries ) {
  36708. var previous = this._finalize( false );
  36709. // New usemtl declaration overwrites an inherited material, except if faces were declared
  36710. // after the material, then it must be preserved for proper MultiMaterial continuation.
  36711. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  36712. this.materials.splice( previous.index, 1 );
  36713. }
  36714. var material = {
  36715. index: this.materials.length,
  36716. name: name || '',
  36717. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  36718. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  36719. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  36720. groupEnd: - 1,
  36721. groupCount: - 1,
  36722. inherited: false,
  36723. clone: function ( index ) {
  36724. var cloned = {
  36725. index: ( typeof index === 'number' ? index : this.index ),
  36726. name: this.name,
  36727. mtllib: this.mtllib,
  36728. smooth: this.smooth,
  36729. groupStart: 0,
  36730. groupEnd: - 1,
  36731. groupCount: - 1,
  36732. inherited: false
  36733. };
  36734. cloned.clone = this.clone.bind( cloned );
  36735. return cloned;
  36736. }
  36737. };
  36738. this.materials.push( material );
  36739. return material;
  36740. },
  36741. currentMaterial: function () {
  36742. if ( this.materials.length > 0 ) {
  36743. return this.materials[ this.materials.length - 1 ];
  36744. }
  36745. return undefined;
  36746. },
  36747. _finalize: function ( end ) {
  36748. var lastMultiMaterial = this.currentMaterial();
  36749. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  36750. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  36751. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  36752. lastMultiMaterial.inherited = false;
  36753. }
  36754. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  36755. if ( end && this.materials.length > 1 ) {
  36756. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  36757. if ( this.materials[ mi ].groupCount <= 0 ) {
  36758. this.materials.splice( mi, 1 );
  36759. }
  36760. }
  36761. }
  36762. // Guarantee at least one empty material, this makes the creation later more straight forward.
  36763. if ( end && this.materials.length === 0 ) {
  36764. this.materials.push( {
  36765. name: '',
  36766. smooth: this.smooth
  36767. } );
  36768. }
  36769. return lastMultiMaterial;
  36770. }
  36771. };
  36772. // Inherit previous objects material.
  36773. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  36774. // If a usemtl declaration is encountered while this new object is being parsed, it will
  36775. // overwrite the inherited material. Exception being that there was already face declarations
  36776. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  36777. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  36778. var declared = previousMaterial.clone( 0 );
  36779. declared.inherited = true;
  36780. this.object.materials.push( declared );
  36781. }
  36782. this.objects.push( this.object );
  36783. },
  36784. finalize: function () {
  36785. if ( this.object && typeof this.object._finalize === 'function' ) {
  36786. this.object._finalize( true );
  36787. }
  36788. },
  36789. parseVertexIndex: function ( value, len ) {
  36790. var index = parseInt( value, 10 );
  36791. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36792. },
  36793. parseNormalIndex: function ( value, len ) {
  36794. var index = parseInt( value, 10 );
  36795. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36796. },
  36797. parseUVIndex: function ( value, len ) {
  36798. var index = parseInt( value, 10 );
  36799. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  36800. },
  36801. addVertex: function ( a, b, c ) {
  36802. var src = this.vertices;
  36803. var dst = this.object.geometry.vertices;
  36804. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36805. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36806. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36807. },
  36808. addVertexPoint: function ( a ) {
  36809. var src = this.vertices;
  36810. var dst = this.object.geometry.vertices;
  36811. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36812. },
  36813. addVertexLine: function ( a ) {
  36814. var src = this.vertices;
  36815. var dst = this.object.geometry.vertices;
  36816. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36817. },
  36818. addNormal: function ( a, b, c ) {
  36819. var src = this.normals;
  36820. var dst = this.object.geometry.normals;
  36821. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36822. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36823. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36824. },
  36825. addColor: function ( a, b, c ) {
  36826. var src = this.colors;
  36827. var dst = this.object.geometry.colors;
  36828. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36829. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36830. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36831. },
  36832. addUV: function ( a, b, c ) {
  36833. var src = this.uvs;
  36834. var dst = this.object.geometry.uvs;
  36835. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36836. dst.push( src[ b + 0 ], src[ b + 1 ] );
  36837. dst.push( src[ c + 0 ], src[ c + 1 ] );
  36838. },
  36839. addUVLine: function ( a ) {
  36840. var src = this.uvs;
  36841. var dst = this.object.geometry.uvs;
  36842. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36843. },
  36844. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  36845. var vLen = this.vertices.length;
  36846. var ia = this.parseVertexIndex( a, vLen );
  36847. var ib = this.parseVertexIndex( b, vLen );
  36848. var ic = this.parseVertexIndex( c, vLen );
  36849. this.addVertex( ia, ib, ic );
  36850. if ( ua !== undefined && ua !== '' ) {
  36851. var uvLen = this.uvs.length;
  36852. ia = this.parseUVIndex( ua, uvLen );
  36853. ib = this.parseUVIndex( ub, uvLen );
  36854. ic = this.parseUVIndex( uc, uvLen );
  36855. this.addUV( ia, ib, ic );
  36856. }
  36857. if ( na !== undefined && na !== '' ) {
  36858. // Normals are many times the same. If so, skip function call and parseInt.
  36859. var nLen = this.normals.length;
  36860. ia = this.parseNormalIndex( na, nLen );
  36861. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  36862. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  36863. this.addNormal( ia, ib, ic );
  36864. }
  36865. if ( this.colors.length > 0 ) {
  36866. this.addColor( ia, ib, ic );
  36867. }
  36868. },
  36869. addPointGeometry: function ( vertices ) {
  36870. this.object.geometry.type = 'Points';
  36871. var vLen = this.vertices.length;
  36872. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36873. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36874. }
  36875. },
  36876. addLineGeometry: function ( vertices, uvs ) {
  36877. this.object.geometry.type = 'Line';
  36878. var vLen = this.vertices.length;
  36879. var uvLen = this.uvs.length;
  36880. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36881. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36882. }
  36883. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  36884. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  36885. }
  36886. }
  36887. };
  36888. state.startObject( '', false );
  36889. return state;
  36890. }
  36891. //
  36892. function OBJLoader( manager ) {
  36893. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36894. this.materials = null;
  36895. }
  36896. OBJLoader.prototype = {
  36897. constructor: OBJLoader,
  36898. load: function ( url, onLoad, onProgress, onError ) {
  36899. var scope = this;
  36900. var loader = new THREE.FileLoader( scope.manager );
  36901. loader.setPath( this.path );
  36902. loader.load( url, function ( text ) {
  36903. onLoad( scope.parse( text ) );
  36904. }, onProgress, onError );
  36905. },
  36906. setPath: function ( value ) {
  36907. this.path = value;
  36908. return this;
  36909. },
  36910. setMaterials: function ( materials ) {
  36911. this.materials = materials;
  36912. return this;
  36913. },
  36914. parse: function ( text ) {
  36915. console.time( 'OBJLoader' );
  36916. var state = new ParserState();
  36917. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  36918. // This is faster than String.split with regex that splits on both
  36919. text = text.replace( /\r\n/g, '\n' );
  36920. }
  36921. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  36922. // join lines separated by a line continuation character (\)
  36923. text = text.replace( /\\\n/g, '' );
  36924. }
  36925. var lines = text.split( '\n' );
  36926. var line = '', lineFirstChar = '';
  36927. var lineLength = 0;
  36928. var result = [];
  36929. // Faster to just trim left side of the line. Use if available.
  36930. var trimLeft = ( typeof ''.trimLeft === 'function' );
  36931. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  36932. line = lines[ i ];
  36933. line = trimLeft ? line.trimLeft() : line.trim();
  36934. lineLength = line.length;
  36935. if ( lineLength === 0 ) continue;
  36936. lineFirstChar = line.charAt( 0 );
  36937. // @todo invoke passed in handler if any
  36938. if ( lineFirstChar === '#' ) continue;
  36939. if ( lineFirstChar === 'v' ) {
  36940. var data = line.split( /\s+/ );
  36941. switch ( data[ 0 ] ) {
  36942. case 'v':
  36943. state.vertices.push(
  36944. parseFloat( data[ 1 ] ),
  36945. parseFloat( data[ 2 ] ),
  36946. parseFloat( data[ 3 ] )
  36947. );
  36948. if ( data.length === 8 ) {
  36949. state.colors.push(
  36950. parseFloat( data[ 4 ] ),
  36951. parseFloat( data[ 5 ] ),
  36952. parseFloat( data[ 6 ] )
  36953. );
  36954. }
  36955. break;
  36956. case 'vn':
  36957. state.normals.push(
  36958. parseFloat( data[ 1 ] ),
  36959. parseFloat( data[ 2 ] ),
  36960. parseFloat( data[ 3 ] )
  36961. );
  36962. break;
  36963. case 'vt':
  36964. state.uvs.push(
  36965. parseFloat( data[ 1 ] ),
  36966. parseFloat( data[ 2 ] )
  36967. );
  36968. break;
  36969. }
  36970. } else if ( lineFirstChar === 'f' ) {
  36971. var lineData = line.substr( 1 ).trim();
  36972. var vertexData = lineData.split( /\s+/ );
  36973. var faceVertices = [];
  36974. // Parse the face vertex data into an easy to work with format
  36975. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  36976. var vertex = vertexData[ j ];
  36977. if ( vertex.length > 0 ) {
  36978. var vertexParts = vertex.split( '/' );
  36979. faceVertices.push( vertexParts );
  36980. }
  36981. }
  36982. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  36983. var v1 = faceVertices[ 0 ];
  36984. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  36985. var v2 = faceVertices[ j ];
  36986. var v3 = faceVertices[ j + 1 ];
  36987. state.addFace(
  36988. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  36989. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  36990. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  36991. );
  36992. }
  36993. } else if ( lineFirstChar === 'l' ) {
  36994. var lineParts = line.substring( 1 ).trim().split( " " );
  36995. var lineVertices = [], lineUVs = [];
  36996. if ( line.indexOf( "/" ) === - 1 ) {
  36997. lineVertices = lineParts;
  36998. } else {
  36999. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  37000. var parts = lineParts[ li ].split( "/" );
  37001. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  37002. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  37003. }
  37004. }
  37005. state.addLineGeometry( lineVertices, lineUVs );
  37006. } else if ( lineFirstChar === 'p' ) {
  37007. var lineData = line.substr( 1 ).trim();
  37008. var pointData = lineData.split( " " );
  37009. state.addPointGeometry( pointData );
  37010. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  37011. // o object_name
  37012. // or
  37013. // g group_name
  37014. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  37015. // var name = result[ 0 ].substr( 1 ).trim();
  37016. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  37017. state.startObject( name );
  37018. } else if ( material_use_pattern.test( line ) ) {
  37019. // material
  37020. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  37021. } else if ( material_library_pattern.test( line ) ) {
  37022. // mtl file
  37023. state.materialLibraries.push( line.substring( 7 ).trim() );
  37024. } else if ( lineFirstChar === 's' ) {
  37025. result = line.split( ' ' );
  37026. // smooth shading
  37027. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  37028. // but does not define a usemtl for each face set.
  37029. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  37030. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  37031. // where explicit usemtl defines geometry groups.
  37032. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  37033. /*
  37034. * http://paulbourke.net/dataformats/obj/
  37035. * or
  37036. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  37037. *
  37038. * From chapter "Grouping" Syntax explanation "s group_number":
  37039. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  37040. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  37041. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  37042. * than 0."
  37043. */
  37044. if ( result.length > 1 ) {
  37045. var value = result[ 1 ].trim().toLowerCase();
  37046. state.object.smooth = ( value !== '0' && value !== 'off' );
  37047. } else {
  37048. // ZBrush can produce "s" lines #11707
  37049. state.object.smooth = true;
  37050. }
  37051. var material = state.object.currentMaterial();
  37052. if ( material ) material.smooth = state.object.smooth;
  37053. } else {
  37054. // Handle null terminated files without exception
  37055. if ( line === '\0' ) continue;
  37056. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  37057. }
  37058. }
  37059. state.finalize();
  37060. var container = new THREE.Group();
  37061. container.materialLibraries = [].concat( state.materialLibraries );
  37062. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  37063. var object = state.objects[ i ];
  37064. var geometry = object.geometry;
  37065. var materials = object.materials;
  37066. var isLine = ( geometry.type === 'Line' );
  37067. var isPoints = ( geometry.type === 'Points' );
  37068. var hasVertexColors = false;
  37069. // Skip o/g line declarations that did not follow with any faces
  37070. if ( geometry.vertices.length === 0 ) continue;
  37071. var buffergeometry = new THREE.BufferGeometry();
  37072. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  37073. if ( geometry.normals.length > 0 ) {
  37074. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  37075. } else {
  37076. buffergeometry.computeVertexNormals();
  37077. }
  37078. if ( geometry.colors.length > 0 ) {
  37079. hasVertexColors = true;
  37080. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  37081. }
  37082. if ( geometry.uvs.length > 0 ) {
  37083. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  37084. }
  37085. // Create materials
  37086. var createdMaterials = [];
  37087. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37088. var sourceMaterial = materials[ mi ];
  37089. var material = undefined;
  37090. if ( this.materials !== null ) {
  37091. material = this.materials.create( sourceMaterial.name );
  37092. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  37093. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  37094. var materialLine = new THREE.LineBasicMaterial();
  37095. THREE.Material.prototype.copy.call( materialLine, material );
  37096. materialLine.color.copy( material.color );
  37097. materialLine.lights = false;
  37098. material = materialLine;
  37099. } else if ( isPoints && material && ! ( material instanceof THREE.PointsMaterial ) ) {
  37100. var materialPoints = new THREE.PointsMaterial( { size: 10, sizeAttenuation: false } );
  37101. THREE.Material.prototype.copy.call( materialPoints, material );
  37102. materialPoints.color.copy( material.color );
  37103. materialPoints.map = material.map;
  37104. materialPoints.lights = false;
  37105. material = materialPoints;
  37106. }
  37107. }
  37108. if ( ! material ) {
  37109. if ( isLine ) {
  37110. material = new THREE.LineBasicMaterial();
  37111. } else if ( isPoints ) {
  37112. material = new THREE.PointsMaterial( { size: 1, sizeAttenuation: false } );
  37113. } else {
  37114. material = new THREE.MeshPhongMaterial();
  37115. }
  37116. material.name = sourceMaterial.name;
  37117. }
  37118. material.flatShading = sourceMaterial.smooth ? false : true;
  37119. material.vertexColors = hasVertexColors ? THREE.VertexColors : THREE.NoColors;
  37120. createdMaterials.push( material );
  37121. }
  37122. // Create mesh
  37123. var mesh;
  37124. if ( createdMaterials.length > 1 ) {
  37125. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  37126. var sourceMaterial = materials[ mi ];
  37127. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  37128. }
  37129. if ( isLine ) {
  37130. mesh = new THREE.LineSegments( buffergeometry, createdMaterials );
  37131. } else if ( isPoints ) {
  37132. mesh = new THREE.Points( buffergeometry, createdMaterials );
  37133. } else {
  37134. mesh = new THREE.Mesh( buffergeometry, createdMaterials );
  37135. }
  37136. } else {
  37137. if ( isLine ) {
  37138. mesh = new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] );
  37139. } else if ( isPoints ) {
  37140. mesh = new THREE.Points( buffergeometry, createdMaterials[ 0 ] );
  37141. } else {
  37142. mesh = new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] );
  37143. }
  37144. }
  37145. mesh.name = object.name;
  37146. container.add( mesh );
  37147. }
  37148. console.timeEnd( 'OBJLoader' );
  37149. return container;
  37150. }
  37151. };
  37152. return OBJLoader;
  37153. } )();
  37154. },{}],41:[function(_dereq_,module,exports){
  37155. var createLayout = _dereq_('layout-bmfont-text')
  37156. var inherits = _dereq_('inherits')
  37157. var createIndices = _dereq_('quad-indices')
  37158. var buffer = _dereq_('three-buffer-vertex-data')
  37159. var assign = _dereq_('object-assign')
  37160. var vertices = _dereq_('./lib/vertices')
  37161. var utils = _dereq_('./lib/utils')
  37162. var Base = THREE.BufferGeometry
  37163. module.exports = function createTextGeometry (opt) {
  37164. return new TextGeometry(opt)
  37165. }
  37166. function TextGeometry (opt) {
  37167. Base.call(this)
  37168. if (typeof opt === 'string') {
  37169. opt = { text: opt }
  37170. }
  37171. // use these as default values for any subsequent
  37172. // calls to update()
  37173. this._opt = assign({}, opt)
  37174. // also do an initial setup...
  37175. if (opt) this.update(opt)
  37176. }
  37177. inherits(TextGeometry, Base)
  37178. TextGeometry.prototype.update = function (opt) {
  37179. if (typeof opt === 'string') {
  37180. opt = { text: opt }
  37181. }
  37182. // use constructor defaults
  37183. opt = assign({}, this._opt, opt)
  37184. if (!opt.font) {
  37185. throw new TypeError('must specify a { font } in options')
  37186. }
  37187. this.layout = createLayout(opt)
  37188. // get vec2 texcoords
  37189. var flipY = opt.flipY !== false
  37190. // the desired BMFont data
  37191. var font = opt.font
  37192. // determine texture size from font file
  37193. var texWidth = font.common.scaleW
  37194. var texHeight = font.common.scaleH
  37195. // get visible glyphs
  37196. var glyphs = this.layout.glyphs.filter(function (glyph) {
  37197. var bitmap = glyph.data
  37198. return bitmap.width * bitmap.height > 0
  37199. })
  37200. // provide visible glyphs for convenience
  37201. this.visibleGlyphs = glyphs
  37202. // get common vertex data
  37203. var positions = vertices.positions(glyphs)
  37204. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  37205. var indices = createIndices({
  37206. clockwise: true,
  37207. type: 'uint16',
  37208. count: glyphs.length
  37209. })
  37210. // update vertex data
  37211. buffer.index(this, indices, 1, 'uint16')
  37212. buffer.attr(this, 'position', positions, 2)
  37213. buffer.attr(this, 'uv', uvs, 2)
  37214. // update multipage data
  37215. if (!opt.multipage && 'page' in this.attributes) {
  37216. // disable multipage rendering
  37217. this.removeAttribute('page')
  37218. } else if (opt.multipage) {
  37219. var pages = vertices.pages(glyphs)
  37220. // enable multipage rendering
  37221. buffer.attr(this, 'page', pages, 1)
  37222. }
  37223. }
  37224. TextGeometry.prototype.computeBoundingSphere = function () {
  37225. if (this.boundingSphere === null) {
  37226. this.boundingSphere = new THREE.Sphere()
  37227. }
  37228. var positions = this.attributes.position.array
  37229. var itemSize = this.attributes.position.itemSize
  37230. if (!positions || !itemSize || positions.length < 2) {
  37231. this.boundingSphere.radius = 0
  37232. this.boundingSphere.center.set(0, 0, 0)
  37233. return
  37234. }
  37235. utils.computeSphere(positions, this.boundingSphere)
  37236. if (isNaN(this.boundingSphere.radius)) {
  37237. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  37238. 'Computed radius is NaN. The ' +
  37239. '"position" attribute is likely to have NaN values.')
  37240. }
  37241. }
  37242. TextGeometry.prototype.computeBoundingBox = function () {
  37243. if (this.boundingBox === null) {
  37244. this.boundingBox = new THREE.Box3()
  37245. }
  37246. var bbox = this.boundingBox
  37247. var positions = this.attributes.position.array
  37248. var itemSize = this.attributes.position.itemSize
  37249. if (!positions || !itemSize || positions.length < 2) {
  37250. bbox.makeEmpty()
  37251. return
  37252. }
  37253. utils.computeBox(positions, bbox)
  37254. }
  37255. },{"./lib/utils":42,"./lib/vertices":43,"inherits":17,"layout-bmfont-text":22,"object-assign":25,"quad-indices":34,"three-buffer-vertex-data":44}],42:[function(_dereq_,module,exports){
  37256. var itemSize = 2
  37257. var box = { min: [0, 0], max: [0, 0] }
  37258. function bounds (positions) {
  37259. var count = positions.length / itemSize
  37260. box.min[0] = positions[0]
  37261. box.min[1] = positions[1]
  37262. box.max[0] = positions[0]
  37263. box.max[1] = positions[1]
  37264. for (var i = 0; i < count; i++) {
  37265. var x = positions[i * itemSize + 0]
  37266. var y = positions[i * itemSize + 1]
  37267. box.min[0] = Math.min(x, box.min[0])
  37268. box.min[1] = Math.min(y, box.min[1])
  37269. box.max[0] = Math.max(x, box.max[0])
  37270. box.max[1] = Math.max(y, box.max[1])
  37271. }
  37272. }
  37273. module.exports.computeBox = function (positions, output) {
  37274. bounds(positions)
  37275. output.min.set(box.min[0], box.min[1], 0)
  37276. output.max.set(box.max[0], box.max[1], 0)
  37277. }
  37278. module.exports.computeSphere = function (positions, output) {
  37279. bounds(positions)
  37280. var minX = box.min[0]
  37281. var minY = box.min[1]
  37282. var maxX = box.max[0]
  37283. var maxY = box.max[1]
  37284. var width = maxX - minX
  37285. var height = maxY - minY
  37286. var length = Math.sqrt(width * width + height * height)
  37287. output.center.set(minX + width / 2, minY + height / 2, 0)
  37288. output.radius = length / 2
  37289. }
  37290. },{}],43:[function(_dereq_,module,exports){
  37291. module.exports.pages = function pages (glyphs) {
  37292. var pages = new Float32Array(glyphs.length * 4 * 1)
  37293. var i = 0
  37294. glyphs.forEach(function (glyph) {
  37295. var id = glyph.data.page || 0
  37296. pages[i++] = id
  37297. pages[i++] = id
  37298. pages[i++] = id
  37299. pages[i++] = id
  37300. })
  37301. return pages
  37302. }
  37303. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  37304. var uvs = new Float32Array(glyphs.length * 4 * 2)
  37305. var i = 0
  37306. glyphs.forEach(function (glyph) {
  37307. var bitmap = glyph.data
  37308. var bw = (bitmap.x + bitmap.width)
  37309. var bh = (bitmap.y + bitmap.height)
  37310. // top left position
  37311. var u0 = bitmap.x / texWidth
  37312. var v1 = bitmap.y / texHeight
  37313. var u1 = bw / texWidth
  37314. var v0 = bh / texHeight
  37315. if (flipY) {
  37316. v1 = (texHeight - bitmap.y) / texHeight
  37317. v0 = (texHeight - bh) / texHeight
  37318. }
  37319. // BL
  37320. uvs[i++] = u0
  37321. uvs[i++] = v1
  37322. // TL
  37323. uvs[i++] = u0
  37324. uvs[i++] = v0
  37325. // TR
  37326. uvs[i++] = u1
  37327. uvs[i++] = v0
  37328. // BR
  37329. uvs[i++] = u1
  37330. uvs[i++] = v1
  37331. })
  37332. return uvs
  37333. }
  37334. module.exports.positions = function positions (glyphs) {
  37335. var positions = new Float32Array(glyphs.length * 4 * 2)
  37336. var i = 0
  37337. glyphs.forEach(function (glyph) {
  37338. var bitmap = glyph.data
  37339. // bottom left position
  37340. var x = glyph.position[0] + bitmap.xoffset
  37341. var y = glyph.position[1] + bitmap.yoffset
  37342. // quad size
  37343. var w = bitmap.width
  37344. var h = bitmap.height
  37345. // BL
  37346. positions[i++] = x
  37347. positions[i++] = y
  37348. // TL
  37349. positions[i++] = x
  37350. positions[i++] = y + h
  37351. // TR
  37352. positions[i++] = x + w
  37353. positions[i++] = y + h
  37354. // BR
  37355. positions[i++] = x + w
  37356. positions[i++] = y
  37357. })
  37358. return positions
  37359. }
  37360. },{}],44:[function(_dereq_,module,exports){
  37361. var flatten = _dereq_('flatten-vertex-data')
  37362. var warned = false;
  37363. module.exports.attr = setAttribute
  37364. module.exports.index = setIndex
  37365. function setIndex (geometry, data, itemSize, dtype) {
  37366. if (typeof itemSize !== 'number') itemSize = 1
  37367. if (typeof dtype !== 'string') dtype = 'uint16'
  37368. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  37369. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  37370. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  37371. if (newAttrib) {
  37372. if (isR69) geometry.addAttribute('index', newAttrib)
  37373. else geometry.index = newAttrib
  37374. }
  37375. }
  37376. function setAttribute (geometry, key, data, itemSize, dtype) {
  37377. if (typeof itemSize !== 'number') itemSize = 3
  37378. if (typeof dtype !== 'string') dtype = 'float32'
  37379. if (Array.isArray(data) &&
  37380. Array.isArray(data[0]) &&
  37381. data[0].length !== itemSize) {
  37382. throw new Error('Nested vertex array has unexpected size; expected ' +
  37383. itemSize + ' but found ' + data[0].length)
  37384. }
  37385. var attrib = geometry.getAttribute(key)
  37386. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  37387. if (newAttrib) {
  37388. geometry.addAttribute(key, newAttrib)
  37389. }
  37390. }
  37391. function updateAttribute (attrib, data, itemSize, dtype) {
  37392. data = data || []
  37393. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  37394. // create a new array with desired type
  37395. data = flatten(data, dtype)
  37396. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  37397. if (!attrib || needsNewBuffer) {
  37398. // We are on an old version of ThreeJS which can't
  37399. // support growing / shrinking buffers, so we need
  37400. // to build a new buffer
  37401. if (needsNewBuffer && !warned) {
  37402. warned = true
  37403. console.warn([
  37404. 'A WebGL buffer is being updated with a new size or itemSize, ',
  37405. 'however this version of ThreeJS only supports fixed-size buffers.',
  37406. '\nThe old buffer may still be kept in memory.\n',
  37407. 'To avoid memory leaks, it is recommended that you dispose ',
  37408. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  37409. 'See here for discussion:\n',
  37410. 'https://github.com/mrdoob/three.js/pull/9631'
  37411. ].join(''))
  37412. }
  37413. // Build a new attribute
  37414. attrib = new THREE.BufferAttribute(data, itemSize);
  37415. }
  37416. attrib.itemSize = itemSize
  37417. attrib.needsUpdate = true
  37418. // New versions of ThreeJS suggest using setArray
  37419. // to change the data. It will use bufferData internally,
  37420. // so you can change the array size without any issues
  37421. if (typeof attrib.setArray === 'function') {
  37422. attrib.setArray(data)
  37423. }
  37424. return attrib
  37425. } else {
  37426. // copy data into the existing array
  37427. flatten(data, attrib.array)
  37428. attrib.needsUpdate = true
  37429. return null
  37430. }
  37431. }
  37432. // Test whether the attribute needs to be re-created,
  37433. // returns false if we can re-use it as-is.
  37434. function rebuildAttribute (attrib, data, itemSize) {
  37435. if (attrib.itemSize !== itemSize) return true
  37436. if (!attrib.array) return true
  37437. var attribLength = attrib.array.length
  37438. if (Array.isArray(data) && Array.isArray(data[0])) {
  37439. // [ [ x, y, z ] ]
  37440. return attribLength !== data.length * itemSize
  37441. } else {
  37442. // [ x, y, z ]
  37443. return attribLength !== data.length
  37444. }
  37445. return false
  37446. }
  37447. },{"flatten-vertex-data":13}],45:[function(_dereq_,module,exports){
  37448. exports = module.exports = trim;
  37449. function trim(str){
  37450. return str.replace(/^\s*|\s*$/g, '');
  37451. }
  37452. exports.left = function(str){
  37453. return str.replace(/^\s*/, '');
  37454. };
  37455. exports.right = function(str){
  37456. return str.replace(/\s*$/, '');
  37457. };
  37458. },{}],46:[function(_dereq_,module,exports){
  37459. (function (global){
  37460. /**
  37461. * @license
  37462. * webvr-polyfill
  37463. * Copyright (c) 2015-2017 Google
  37464. * Licensed under the Apache License, Version 2.0 (the "License");
  37465. * you may not use this file except in compliance with the License.
  37466. * You may obtain a copy of the License at
  37467. *
  37468. * http://www.apache.org/licenses/LICENSE-2.0
  37469. *
  37470. * Unless required by applicable law or agreed to in writing, software
  37471. * distributed under the License is distributed on an "AS IS" BASIS,
  37472. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37473. * See the License for the specific language governing permissions and
  37474. * limitations under the License.
  37475. */
  37476. /**
  37477. * @license
  37478. * cardboard-vr-display
  37479. * Copyright (c) 2015-2017 Google
  37480. * Licensed under the Apache License, Version 2.0 (the "License");
  37481. * you may not use this file except in compliance with the License.
  37482. * You may obtain a copy of the License at
  37483. *
  37484. * http://www.apache.org/licenses/LICENSE-2.0
  37485. *
  37486. * Unless required by applicable law or agreed to in writing, software
  37487. * distributed under the License is distributed on an "AS IS" BASIS,
  37488. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37489. * See the License for the specific language governing permissions and
  37490. * limitations under the License.
  37491. */
  37492. /**
  37493. * @license
  37494. * webvr-polyfill-dpdb
  37495. * Copyright (c) 2017 Google
  37496. * Licensed under the Apache License, Version 2.0 (the "License");
  37497. * you may not use this file except in compliance with the License.
  37498. * You may obtain a copy of the License at
  37499. *
  37500. * http://www.apache.org/licenses/LICENSE-2.0
  37501. *
  37502. * Unless required by applicable law or agreed to in writing, software
  37503. * distributed under the License is distributed on an "AS IS" BASIS,
  37504. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37505. * See the License for the specific language governing permissions and
  37506. * limitations under the License.
  37507. */
  37508. /**
  37509. * @license
  37510. * wglu-preserve-state
  37511. * Copyright (c) 2016, Brandon Jones.
  37512. *
  37513. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37514. * of this software and associated documentation files (the "Software"), to deal
  37515. * in the Software without restriction, including without limitation the rights
  37516. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37517. * copies of the Software, and to permit persons to whom the Software is
  37518. * furnished to do so, subject to the following conditions:
  37519. *
  37520. * The above copyright notice and this permission notice shall be included in
  37521. * all copies or substantial portions of the Software.
  37522. *
  37523. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37524. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37525. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37526. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37527. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37528. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37529. * THE SOFTWARE.
  37530. */
  37531. /**
  37532. * @license
  37533. * nosleep.js
  37534. * Copyright (c) 2017, Rich Tibbett
  37535. *
  37536. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37537. * of this software and associated documentation files (the "Software"), to deal
  37538. * in the Software without restriction, including without limitation the rights
  37539. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37540. * copies of the Software, and to permit persons to whom the Software is
  37541. * furnished to do so, subject to the following conditions:
  37542. *
  37543. * The above copyright notice and this permission notice shall be included in
  37544. * all copies or substantial portions of the Software.
  37545. *
  37546. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37547. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37548. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37549. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37550. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37551. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37552. * THE SOFTWARE.
  37553. */
  37554. (function (global, factory) {
  37555. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  37556. typeof define === 'function' && define.amd ? define(factory) :
  37557. (global.WebVRPolyfill = factory());
  37558. }(this, (function () { 'use strict';
  37559. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  37560. function unwrapExports (x) {
  37561. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  37562. }
  37563. function createCommonjsModule(fn, module) {
  37564. return module = { exports: {} }, fn(module, module.exports), module.exports;
  37565. }
  37566. var isMobile = function isMobile() {
  37567. return (/Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent)
  37568. );
  37569. };
  37570. var copyArray = function copyArray(source, dest) {
  37571. for (var i = 0, n = source.length; i < n; i++) {
  37572. dest[i] = source[i];
  37573. }
  37574. };
  37575. var extend = function extend(dest, src) {
  37576. for (var key in src) {
  37577. if (src.hasOwnProperty(key)) {
  37578. dest[key] = src[key];
  37579. }
  37580. }
  37581. return dest;
  37582. };
  37583. var cardboardVrDisplay = createCommonjsModule(function (module, exports) {
  37584. /**
  37585. * @license
  37586. * cardboard-vr-display
  37587. * Copyright (c) 2015-2017 Google
  37588. * Licensed under the Apache License, Version 2.0 (the "License");
  37589. * you may not use this file except in compliance with the License.
  37590. * You may obtain a copy of the License at
  37591. *
  37592. * http://www.apache.org/licenses/LICENSE-2.0
  37593. *
  37594. * Unless required by applicable law or agreed to in writing, software
  37595. * distributed under the License is distributed on an "AS IS" BASIS,
  37596. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37597. * See the License for the specific language governing permissions and
  37598. * limitations under the License.
  37599. */
  37600. /**
  37601. * @license
  37602. * gl-preserve-state
  37603. * Copyright (c) 2016, Brandon Jones.
  37604. *
  37605. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37606. * of this software and associated documentation files (the "Software"), to deal
  37607. * in the Software without restriction, including without limitation the rights
  37608. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37609. * copies of the Software, and to permit persons to whom the Software is
  37610. * furnished to do so, subject to the following conditions:
  37611. *
  37612. * The above copyright notice and this permission notice shall be included in
  37613. * all copies or substantial portions of the Software.
  37614. *
  37615. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37616. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37617. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37618. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37619. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37620. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37621. * THE SOFTWARE.
  37622. */
  37623. /**
  37624. * @license
  37625. * webvr-polyfill-dpdb
  37626. * Copyright (c) 2015-2017 Google
  37627. * Licensed under the Apache License, Version 2.0 (the "License");
  37628. * you may not use this file except in compliance with the License.
  37629. * You may obtain a copy of the License at
  37630. *
  37631. * http://www.apache.org/licenses/LICENSE-2.0
  37632. *
  37633. * Unless required by applicable law or agreed to in writing, software
  37634. * distributed under the License is distributed on an "AS IS" BASIS,
  37635. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37636. * See the License for the specific language governing permissions and
  37637. * limitations under the License.
  37638. */
  37639. /**
  37640. * @license
  37641. * nosleep.js
  37642. * Copyright (c) 2017, Rich Tibbett
  37643. *
  37644. * Permission is hereby granted, free of charge, to any person obtaining a copy
  37645. * of this software and associated documentation files (the "Software"), to deal
  37646. * in the Software without restriction, including without limitation the rights
  37647. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37648. * copies of the Software, and to permit persons to whom the Software is
  37649. * furnished to do so, subject to the following conditions:
  37650. *
  37651. * The above copyright notice and this permission notice shall be included in
  37652. * all copies or substantial portions of the Software.
  37653. *
  37654. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37655. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37656. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37657. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37658. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37659. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37660. * THE SOFTWARE.
  37661. */
  37662. (function (global, factory) {
  37663. module.exports = factory();
  37664. }(commonjsGlobal, (function () { var classCallCheck = function (instance, Constructor) {
  37665. if (!(instance instanceof Constructor)) {
  37666. throw new TypeError("Cannot call a class as a function");
  37667. }
  37668. };
  37669. var createClass = function () {
  37670. function defineProperties(target, props) {
  37671. for (var i = 0; i < props.length; i++) {
  37672. var descriptor = props[i];
  37673. descriptor.enumerable = descriptor.enumerable || false;
  37674. descriptor.configurable = true;
  37675. if ("value" in descriptor) descriptor.writable = true;
  37676. Object.defineProperty(target, descriptor.key, descriptor);
  37677. }
  37678. }
  37679. return function (Constructor, protoProps, staticProps) {
  37680. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  37681. if (staticProps) defineProperties(Constructor, staticProps);
  37682. return Constructor;
  37683. };
  37684. }();
  37685. var slicedToArray = function () {
  37686. function sliceIterator(arr, i) {
  37687. var _arr = [];
  37688. var _n = true;
  37689. var _d = false;
  37690. var _e = undefined;
  37691. try {
  37692. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  37693. _arr.push(_s.value);
  37694. if (i && _arr.length === i) break;
  37695. }
  37696. } catch (err) {
  37697. _d = true;
  37698. _e = err;
  37699. } finally {
  37700. try {
  37701. if (!_n && _i["return"]) _i["return"]();
  37702. } finally {
  37703. if (_d) throw _e;
  37704. }
  37705. }
  37706. return _arr;
  37707. }
  37708. return function (arr, i) {
  37709. if (Array.isArray(arr)) {
  37710. return arr;
  37711. } else if (Symbol.iterator in Object(arr)) {
  37712. return sliceIterator(arr, i);
  37713. } else {
  37714. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  37715. }
  37716. };
  37717. }();
  37718. var MIN_TIMESTEP = 0.001;
  37719. var MAX_TIMESTEP = 1;
  37720. var dataUri = function dataUri(mimeType, svg) {
  37721. return 'data:' + mimeType + ',' + encodeURIComponent(svg);
  37722. };
  37723. var lerp = function lerp(a, b, t) {
  37724. return a + (b - a) * t;
  37725. };
  37726. var isIOS = function () {
  37727. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  37728. return function () {
  37729. return isIOS;
  37730. };
  37731. }();
  37732. var isWebViewAndroid = function () {
  37733. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 && navigator.userAgent.indexOf('Android') !== -1 && navigator.userAgent.indexOf('Chrome') !== -1;
  37734. return function () {
  37735. return isWebViewAndroid;
  37736. };
  37737. }();
  37738. var isSafari = function () {
  37739. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  37740. return function () {
  37741. return isSafari;
  37742. };
  37743. }();
  37744. var isFirefoxAndroid = function () {
  37745. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  37746. return function () {
  37747. return isFirefoxAndroid;
  37748. };
  37749. }();
  37750. var getChromeVersion = function () {
  37751. var match = navigator.userAgent.match(/.*Chrome\/([0-9]+)/);
  37752. var value = match ? parseInt(match[1], 10) : null;
  37753. return function () {
  37754. return value;
  37755. };
  37756. }();
  37757. var isChromeWithoutDeviceMotion = function () {
  37758. var value = false;
  37759. if (getChromeVersion() === 65) {
  37760. var match = navigator.userAgent.match(/.*Chrome\/([0-9\.]*)/);
  37761. if (match) {
  37762. var _match$1$split = match[1].split('.'),
  37763. _match$1$split2 = slicedToArray(_match$1$split, 4),
  37764. major = _match$1$split2[0],
  37765. minor = _match$1$split2[1],
  37766. branch = _match$1$split2[2],
  37767. build = _match$1$split2[3];
  37768. value = parseInt(branch, 10) === 3325 && parseInt(build, 10) < 148;
  37769. }
  37770. }
  37771. return function () {
  37772. return value;
  37773. };
  37774. }();
  37775. var isR7 = function () {
  37776. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  37777. return function () {
  37778. return isR7;
  37779. };
  37780. }();
  37781. var isLandscapeMode = function isLandscapeMode() {
  37782. var rtn = window.orientation == 90 || window.orientation == -90;
  37783. return isR7() ? !rtn : rtn;
  37784. };
  37785. var isTimestampDeltaValid = function isTimestampDeltaValid(timestampDeltaS) {
  37786. if (isNaN(timestampDeltaS)) {
  37787. return false;
  37788. }
  37789. if (timestampDeltaS <= MIN_TIMESTEP) {
  37790. return false;
  37791. }
  37792. if (timestampDeltaS > MAX_TIMESTEP) {
  37793. return false;
  37794. }
  37795. return true;
  37796. };
  37797. var getScreenWidth = function getScreenWidth() {
  37798. return Math.max(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37799. };
  37800. var getScreenHeight = function getScreenHeight() {
  37801. return Math.min(window.screen.width, window.screen.height) * window.devicePixelRatio;
  37802. };
  37803. var requestFullscreen = function requestFullscreen(element) {
  37804. if (isWebViewAndroid()) {
  37805. return false;
  37806. }
  37807. if (element.requestFullscreen) {
  37808. element.requestFullscreen();
  37809. } else if (element.webkitRequestFullscreen) {
  37810. element.webkitRequestFullscreen();
  37811. } else if (element.mozRequestFullScreen) {
  37812. element.mozRequestFullScreen();
  37813. } else if (element.msRequestFullscreen) {
  37814. element.msRequestFullscreen();
  37815. } else {
  37816. return false;
  37817. }
  37818. return true;
  37819. };
  37820. var exitFullscreen = function exitFullscreen() {
  37821. if (document.exitFullscreen) {
  37822. document.exitFullscreen();
  37823. } else if (document.webkitExitFullscreen) {
  37824. document.webkitExitFullscreen();
  37825. } else if (document.mozCancelFullScreen) {
  37826. document.mozCancelFullScreen();
  37827. } else if (document.msExitFullscreen) {
  37828. document.msExitFullscreen();
  37829. } else {
  37830. return false;
  37831. }
  37832. return true;
  37833. };
  37834. var getFullscreenElement = function getFullscreenElement() {
  37835. return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  37836. };
  37837. var linkProgram = function linkProgram(gl, vertexSource, fragmentSource, attribLocationMap) {
  37838. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  37839. gl.shaderSource(vertexShader, vertexSource);
  37840. gl.compileShader(vertexShader);
  37841. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  37842. gl.shaderSource(fragmentShader, fragmentSource);
  37843. gl.compileShader(fragmentShader);
  37844. var program = gl.createProgram();
  37845. gl.attachShader(program, vertexShader);
  37846. gl.attachShader(program, fragmentShader);
  37847. for (var attribName in attribLocationMap) {
  37848. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  37849. }gl.linkProgram(program);
  37850. gl.deleteShader(vertexShader);
  37851. gl.deleteShader(fragmentShader);
  37852. return program;
  37853. };
  37854. var getProgramUniforms = function getProgramUniforms(gl, program) {
  37855. var uniforms = {};
  37856. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  37857. var uniformName = '';
  37858. for (var i = 0; i < uniformCount; i++) {
  37859. var uniformInfo = gl.getActiveUniform(program, i);
  37860. uniformName = uniformInfo.name.replace('[0]', '');
  37861. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  37862. }
  37863. return uniforms;
  37864. };
  37865. var orthoMatrix = function orthoMatrix(out, left, right, bottom, top, near, far) {
  37866. var lr = 1 / (left - right),
  37867. bt = 1 / (bottom - top),
  37868. nf = 1 / (near - far);
  37869. out[0] = -2 * lr;
  37870. out[1] = 0;
  37871. out[2] = 0;
  37872. out[3] = 0;
  37873. out[4] = 0;
  37874. out[5] = -2 * bt;
  37875. out[6] = 0;
  37876. out[7] = 0;
  37877. out[8] = 0;
  37878. out[9] = 0;
  37879. out[10] = 2 * nf;
  37880. out[11] = 0;
  37881. out[12] = (left + right) * lr;
  37882. out[13] = (top + bottom) * bt;
  37883. out[14] = (far + near) * nf;
  37884. out[15] = 1;
  37885. return out;
  37886. };
  37887. var isMobile = function isMobile() {
  37888. var check = false;
  37889. (function (a) {
  37890. 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;
  37891. })(navigator.userAgent || navigator.vendor || window.opera);
  37892. return check;
  37893. };
  37894. var extend = function extend(dest, src) {
  37895. for (var key in src) {
  37896. if (src.hasOwnProperty(key)) {
  37897. dest[key] = src[key];
  37898. }
  37899. }
  37900. return dest;
  37901. };
  37902. var safariCssSizeWorkaround = function safariCssSizeWorkaround(canvas) {
  37903. if (isIOS()) {
  37904. var width = canvas.style.width;
  37905. var height = canvas.style.height;
  37906. canvas.style.width = parseInt(width) + 1 + 'px';
  37907. canvas.style.height = parseInt(height) + 'px';
  37908. setTimeout(function () {
  37909. canvas.style.width = width;
  37910. canvas.style.height = height;
  37911. }, 100);
  37912. }
  37913. window.canvas = canvas;
  37914. };
  37915. var frameDataFromPose = function () {
  37916. var piOver180 = Math.PI / 180.0;
  37917. var rad45 = Math.PI * 0.25;
  37918. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  37919. var upTan = Math.tan(fov ? fov.upDegrees * piOver180 : rad45),
  37920. downTan = Math.tan(fov ? fov.downDegrees * piOver180 : rad45),
  37921. leftTan = Math.tan(fov ? fov.leftDegrees * piOver180 : rad45),
  37922. rightTan = Math.tan(fov ? fov.rightDegrees * piOver180 : rad45),
  37923. xScale = 2.0 / (leftTan + rightTan),
  37924. yScale = 2.0 / (upTan + downTan);
  37925. out[0] = xScale;
  37926. out[1] = 0.0;
  37927. out[2] = 0.0;
  37928. out[3] = 0.0;
  37929. out[4] = 0.0;
  37930. out[5] = yScale;
  37931. out[6] = 0.0;
  37932. out[7] = 0.0;
  37933. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  37934. out[9] = (upTan - downTan) * yScale * 0.5;
  37935. out[10] = far / (near - far);
  37936. out[11] = -1.0;
  37937. out[12] = 0.0;
  37938. out[13] = 0.0;
  37939. out[14] = far * near / (near - far);
  37940. out[15] = 0.0;
  37941. return out;
  37942. }
  37943. function mat4_fromRotationTranslation(out, q, v) {
  37944. var x = q[0],
  37945. y = q[1],
  37946. z = q[2],
  37947. w = q[3],
  37948. x2 = x + x,
  37949. y2 = y + y,
  37950. z2 = z + z,
  37951. xx = x * x2,
  37952. xy = x * y2,
  37953. xz = x * z2,
  37954. yy = y * y2,
  37955. yz = y * z2,
  37956. zz = z * z2,
  37957. wx = w * x2,
  37958. wy = w * y2,
  37959. wz = w * z2;
  37960. out[0] = 1 - (yy + zz);
  37961. out[1] = xy + wz;
  37962. out[2] = xz - wy;
  37963. out[3] = 0;
  37964. out[4] = xy - wz;
  37965. out[5] = 1 - (xx + zz);
  37966. out[6] = yz + wx;
  37967. out[7] = 0;
  37968. out[8] = xz + wy;
  37969. out[9] = yz - wx;
  37970. out[10] = 1 - (xx + yy);
  37971. out[11] = 0;
  37972. out[12] = v[0];
  37973. out[13] = v[1];
  37974. out[14] = v[2];
  37975. out[15] = 1;
  37976. return out;
  37977. }
  37978. function mat4_translate(out, a, v) {
  37979. var x = v[0],
  37980. y = v[1],
  37981. z = v[2],
  37982. a00,
  37983. a01,
  37984. a02,
  37985. a03,
  37986. a10,
  37987. a11,
  37988. a12,
  37989. a13,
  37990. a20,
  37991. a21,
  37992. a22,
  37993. a23;
  37994. if (a === out) {
  37995. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  37996. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  37997. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  37998. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  37999. } else {
  38000. a00 = a[0];a01 = a[1];a02 = a[2];a03 = a[3];
  38001. a10 = a[4];a11 = a[5];a12 = a[6];a13 = a[7];
  38002. a20 = a[8];a21 = a[9];a22 = a[10];a23 = a[11];
  38003. out[0] = a00;out[1] = a01;out[2] = a02;out[3] = a03;
  38004. out[4] = a10;out[5] = a11;out[6] = a12;out[7] = a13;
  38005. out[8] = a20;out[9] = a21;out[10] = a22;out[11] = a23;
  38006. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  38007. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  38008. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  38009. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  38010. }
  38011. return out;
  38012. }
  38013. function mat4_invert(out, a) {
  38014. var a00 = a[0],
  38015. a01 = a[1],
  38016. a02 = a[2],
  38017. a03 = a[3],
  38018. a10 = a[4],
  38019. a11 = a[5],
  38020. a12 = a[6],
  38021. a13 = a[7],
  38022. a20 = a[8],
  38023. a21 = a[9],
  38024. a22 = a[10],
  38025. a23 = a[11],
  38026. a30 = a[12],
  38027. a31 = a[13],
  38028. a32 = a[14],
  38029. a33 = a[15],
  38030. b00 = a00 * a11 - a01 * a10,
  38031. b01 = a00 * a12 - a02 * a10,
  38032. b02 = a00 * a13 - a03 * a10,
  38033. b03 = a01 * a12 - a02 * a11,
  38034. b04 = a01 * a13 - a03 * a11,
  38035. b05 = a02 * a13 - a03 * a12,
  38036. b06 = a20 * a31 - a21 * a30,
  38037. b07 = a20 * a32 - a22 * a30,
  38038. b08 = a20 * a33 - a23 * a30,
  38039. b09 = a21 * a32 - a22 * a31,
  38040. b10 = a21 * a33 - a23 * a31,
  38041. b11 = a22 * a33 - a23 * a32,
  38042. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  38043. if (!det) {
  38044. return null;
  38045. }
  38046. det = 1.0 / det;
  38047. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  38048. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  38049. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  38050. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  38051. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  38052. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  38053. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  38054. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  38055. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  38056. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  38057. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  38058. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  38059. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  38060. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  38061. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  38062. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  38063. return out;
  38064. }
  38065. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  38066. var defaultPosition = new Float32Array([0, 0, 0]);
  38067. function updateEyeMatrices(projection, view, pose, fov, offset, vrDisplay) {
  38068. mat4_perspectiveFromFieldOfView(projection, fov || null, vrDisplay.depthNear, vrDisplay.depthFar);
  38069. var orientation = pose.orientation || defaultOrientation;
  38070. var position = pose.position || defaultPosition;
  38071. mat4_fromRotationTranslation(view, orientation, position);
  38072. if (offset) mat4_translate(view, view, offset);
  38073. mat4_invert(view, view);
  38074. }
  38075. return function (frameData, pose, vrDisplay) {
  38076. if (!frameData || !pose) return false;
  38077. frameData.pose = pose;
  38078. frameData.timestamp = pose.timestamp;
  38079. updateEyeMatrices(frameData.leftProjectionMatrix, frameData.leftViewMatrix, pose, vrDisplay._getFieldOfView("left"), vrDisplay._getEyeOffset("left"), vrDisplay);
  38080. updateEyeMatrices(frameData.rightProjectionMatrix, frameData.rightViewMatrix, pose, vrDisplay._getFieldOfView("right"), vrDisplay._getEyeOffset("right"), vrDisplay);
  38081. return true;
  38082. };
  38083. }();
  38084. var isInsideCrossOriginIFrame = function isInsideCrossOriginIFrame() {
  38085. var isFramed = window.self !== window.top;
  38086. var refOrigin = getOriginFromUrl(document.referrer);
  38087. var thisOrigin = getOriginFromUrl(window.location.href);
  38088. return isFramed && refOrigin !== thisOrigin;
  38089. };
  38090. var getOriginFromUrl = function getOriginFromUrl(url) {
  38091. var domainIdx;
  38092. var protoSepIdx = url.indexOf("://");
  38093. if (protoSepIdx !== -1) {
  38094. domainIdx = protoSepIdx + 3;
  38095. } else {
  38096. domainIdx = 0;
  38097. }
  38098. var domainEndIdx = url.indexOf('/', domainIdx);
  38099. if (domainEndIdx === -1) {
  38100. domainEndIdx = url.length;
  38101. }
  38102. return url.substring(0, domainEndIdx);
  38103. };
  38104. var getQuaternionAngle = function getQuaternionAngle(quat) {
  38105. if (quat.w > 1) {
  38106. console.warn('getQuaternionAngle: w > 1');
  38107. return 0;
  38108. }
  38109. var angle = 2 * Math.acos(quat.w);
  38110. return angle;
  38111. };
  38112. var warnOnce = function () {
  38113. var observedWarnings = {};
  38114. return function (key, message) {
  38115. if (observedWarnings[key] === undefined) {
  38116. console.warn('webvr-polyfill: ' + message);
  38117. observedWarnings[key] = true;
  38118. }
  38119. };
  38120. }();
  38121. var deprecateWarning = function deprecateWarning(deprecated, suggested) {
  38122. var alternative = suggested ? 'Please use ' + suggested + ' instead.' : '';
  38123. warnOnce(deprecated, deprecated + ' has been deprecated. ' + 'This may not work on native WebVR displays. ' + alternative);
  38124. };
  38125. function WGLUPreserveGLState(gl, bindings, callback) {
  38126. if (!bindings) {
  38127. callback(gl);
  38128. return;
  38129. }
  38130. var boundValues = [];
  38131. var activeTexture = null;
  38132. for (var i = 0; i < bindings.length; ++i) {
  38133. var binding = bindings[i];
  38134. switch (binding) {
  38135. case gl.TEXTURE_BINDING_2D:
  38136. case gl.TEXTURE_BINDING_CUBE_MAP:
  38137. var textureUnit = bindings[++i];
  38138. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  38139. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  38140. boundValues.push(null, null);
  38141. break;
  38142. }
  38143. if (!activeTexture) {
  38144. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38145. }
  38146. gl.activeTexture(textureUnit);
  38147. boundValues.push(gl.getParameter(binding), null);
  38148. break;
  38149. case gl.ACTIVE_TEXTURE:
  38150. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38151. boundValues.push(null);
  38152. break;
  38153. default:
  38154. boundValues.push(gl.getParameter(binding));
  38155. break;
  38156. }
  38157. }
  38158. callback(gl);
  38159. for (var i = 0; i < bindings.length; ++i) {
  38160. var binding = bindings[i];
  38161. var boundValue = boundValues[i];
  38162. switch (binding) {
  38163. case gl.ACTIVE_TEXTURE:
  38164. break;
  38165. case gl.ARRAY_BUFFER_BINDING:
  38166. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  38167. break;
  38168. case gl.COLOR_CLEAR_VALUE:
  38169. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38170. break;
  38171. case gl.COLOR_WRITEMASK:
  38172. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38173. break;
  38174. case gl.CURRENT_PROGRAM:
  38175. gl.useProgram(boundValue);
  38176. break;
  38177. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  38178. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  38179. break;
  38180. case gl.FRAMEBUFFER_BINDING:
  38181. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  38182. break;
  38183. case gl.RENDERBUFFER_BINDING:
  38184. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  38185. break;
  38186. case gl.TEXTURE_BINDING_2D:
  38187. var textureUnit = bindings[++i];
  38188. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38189. break;
  38190. gl.activeTexture(textureUnit);
  38191. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  38192. break;
  38193. case gl.TEXTURE_BINDING_CUBE_MAP:
  38194. var textureUnit = bindings[++i];
  38195. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38196. break;
  38197. gl.activeTexture(textureUnit);
  38198. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  38199. break;
  38200. case gl.VIEWPORT:
  38201. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38202. break;
  38203. case gl.BLEND:
  38204. case gl.CULL_FACE:
  38205. case gl.DEPTH_TEST:
  38206. case gl.SCISSOR_TEST:
  38207. case gl.STENCIL_TEST:
  38208. if (boundValue) {
  38209. gl.enable(binding);
  38210. } else {
  38211. gl.disable(binding);
  38212. }
  38213. break;
  38214. default:
  38215. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38216. break;
  38217. }
  38218. if (activeTexture) {
  38219. gl.activeTexture(activeTexture);
  38220. }
  38221. }
  38222. }
  38223. var glPreserveState = WGLUPreserveGLState;
  38224. 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');
  38225. var distortionFS = ['precision mediump float;', 'uniform sampler2D diffuse;', 'varying vec2 vTexCoord;', 'void main() {', ' gl_FragColor = texture2D(diffuse, vTexCoord);', '}'].join('\n');
  38226. function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) {
  38227. this.gl = gl;
  38228. this.cardboardUI = cardboardUI;
  38229. this.bufferScale = bufferScale;
  38230. this.dirtySubmitFrameBindings = dirtySubmitFrameBindings;
  38231. this.ctxAttribs = gl.getContextAttributes();
  38232. this.meshWidth = 20;
  38233. this.meshHeight = 20;
  38234. this.bufferWidth = gl.drawingBufferWidth;
  38235. this.bufferHeight = gl.drawingBufferHeight;
  38236. this.realBindFramebuffer = gl.bindFramebuffer;
  38237. this.realEnable = gl.enable;
  38238. this.realDisable = gl.disable;
  38239. this.realColorMask = gl.colorMask;
  38240. this.realClearColor = gl.clearColor;
  38241. this.realViewport = gl.viewport;
  38242. if (!isIOS()) {
  38243. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  38244. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  38245. }
  38246. this.isPatched = false;
  38247. this.lastBoundFramebuffer = null;
  38248. this.cullFace = false;
  38249. this.depthTest = false;
  38250. this.blend = false;
  38251. this.scissorTest = false;
  38252. this.stencilTest = false;
  38253. this.viewport = [0, 0, 0, 0];
  38254. this.colorMask = [true, true, true, true];
  38255. this.clearColor = [0, 0, 0, 0];
  38256. this.attribs = {
  38257. position: 0,
  38258. texCoord: 1
  38259. };
  38260. this.program = linkProgram(gl, distortionVS, distortionFS, this.attribs);
  38261. this.uniforms = getProgramUniforms(gl, this.program);
  38262. this.viewportOffsetScale = new Float32Array(8);
  38263. this.setTextureBounds();
  38264. this.vertexBuffer = gl.createBuffer();
  38265. this.indexBuffer = gl.createBuffer();
  38266. this.indexCount = 0;
  38267. this.renderTarget = gl.createTexture();
  38268. this.framebuffer = gl.createFramebuffer();
  38269. this.depthStencilBuffer = null;
  38270. this.depthBuffer = null;
  38271. this.stencilBuffer = null;
  38272. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  38273. this.depthStencilBuffer = gl.createRenderbuffer();
  38274. } else if (this.ctxAttribs.depth) {
  38275. this.depthBuffer = gl.createRenderbuffer();
  38276. } else if (this.ctxAttribs.stencil) {
  38277. this.stencilBuffer = gl.createRenderbuffer();
  38278. }
  38279. this.patch();
  38280. this.onResize();
  38281. }
  38282. CardboardDistorter.prototype.destroy = function () {
  38283. var gl = this.gl;
  38284. this.unpatch();
  38285. gl.deleteProgram(this.program);
  38286. gl.deleteBuffer(this.vertexBuffer);
  38287. gl.deleteBuffer(this.indexBuffer);
  38288. gl.deleteTexture(this.renderTarget);
  38289. gl.deleteFramebuffer(this.framebuffer);
  38290. if (this.depthStencilBuffer) {
  38291. gl.deleteRenderbuffer(this.depthStencilBuffer);
  38292. }
  38293. if (this.depthBuffer) {
  38294. gl.deleteRenderbuffer(this.depthBuffer);
  38295. }
  38296. if (this.stencilBuffer) {
  38297. gl.deleteRenderbuffer(this.stencilBuffer);
  38298. }
  38299. if (this.cardboardUI) {
  38300. this.cardboardUI.destroy();
  38301. }
  38302. };
  38303. CardboardDistorter.prototype.onResize = function () {
  38304. var gl = this.gl;
  38305. var self = this;
  38306. var glState = [gl.RENDERBUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0];
  38307. glPreserveState(gl, glState, function (gl) {
  38308. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38309. if (self.scissorTest) {
  38310. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38311. }
  38312. self.realColorMask.call(gl, true, true, true, true);
  38313. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38314. self.realClearColor.call(gl, 0, 0, 0, 1);
  38315. gl.clear(gl.COLOR_BUFFER_BIT);
  38316. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  38317. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38318. 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);
  38319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  38320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  38321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  38322. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  38323. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  38324. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  38325. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  38326. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, self.bufferWidth, self.bufferHeight);
  38327. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.depthStencilBuffer);
  38328. } else if (self.ctxAttribs.depth) {
  38329. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  38330. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, self.bufferWidth, self.bufferHeight);
  38331. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, self.depthBuffer);
  38332. } else if (self.ctxAttribs.stencil) {
  38333. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  38334. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, self.bufferWidth, self.bufferHeight);
  38335. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, self.stencilBuffer);
  38336. }
  38337. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  38338. console.error('Framebuffer incomplete!');
  38339. }
  38340. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38341. if (self.scissorTest) {
  38342. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38343. }
  38344. self.realColorMask.apply(gl, self.colorMask);
  38345. self.realViewport.apply(gl, self.viewport);
  38346. self.realClearColor.apply(gl, self.clearColor);
  38347. });
  38348. if (this.cardboardUI) {
  38349. this.cardboardUI.onResize();
  38350. }
  38351. };
  38352. CardboardDistorter.prototype.patch = function () {
  38353. if (this.isPatched) {
  38354. return;
  38355. }
  38356. var self = this;
  38357. var canvas = this.gl.canvas;
  38358. var gl = this.gl;
  38359. if (!isIOS()) {
  38360. canvas.width = getScreenWidth() * this.bufferScale;
  38361. canvas.height = getScreenHeight() * this.bufferScale;
  38362. Object.defineProperty(canvas, 'width', {
  38363. configurable: true,
  38364. enumerable: true,
  38365. get: function get() {
  38366. return self.bufferWidth;
  38367. },
  38368. set: function set(value) {
  38369. self.bufferWidth = value;
  38370. self.realCanvasWidth.set.call(canvas, value);
  38371. self.onResize();
  38372. }
  38373. });
  38374. Object.defineProperty(canvas, 'height', {
  38375. configurable: true,
  38376. enumerable: true,
  38377. get: function get() {
  38378. return self.bufferHeight;
  38379. },
  38380. set: function set(value) {
  38381. self.bufferHeight = value;
  38382. self.realCanvasHeight.set.call(canvas, value);
  38383. self.onResize();
  38384. }
  38385. });
  38386. }
  38387. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  38388. if (this.lastBoundFramebuffer == null) {
  38389. this.lastBoundFramebuffer = this.framebuffer;
  38390. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  38391. }
  38392. this.gl.bindFramebuffer = function (target, framebuffer) {
  38393. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  38394. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  38395. };
  38396. this.cullFace = gl.getParameter(gl.CULL_FACE);
  38397. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  38398. this.blend = gl.getParameter(gl.BLEND);
  38399. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  38400. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  38401. gl.enable = function (pname) {
  38402. switch (pname) {
  38403. case gl.CULL_FACE:
  38404. self.cullFace = true;break;
  38405. case gl.DEPTH_TEST:
  38406. self.depthTest = true;break;
  38407. case gl.BLEND:
  38408. self.blend = true;break;
  38409. case gl.SCISSOR_TEST:
  38410. self.scissorTest = true;break;
  38411. case gl.STENCIL_TEST:
  38412. self.stencilTest = true;break;
  38413. }
  38414. self.realEnable.call(gl, pname);
  38415. };
  38416. gl.disable = function (pname) {
  38417. switch (pname) {
  38418. case gl.CULL_FACE:
  38419. self.cullFace = false;break;
  38420. case gl.DEPTH_TEST:
  38421. self.depthTest = false;break;
  38422. case gl.BLEND:
  38423. self.blend = false;break;
  38424. case gl.SCISSOR_TEST:
  38425. self.scissorTest = false;break;
  38426. case gl.STENCIL_TEST:
  38427. self.stencilTest = false;break;
  38428. }
  38429. self.realDisable.call(gl, pname);
  38430. };
  38431. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  38432. gl.colorMask = function (r, g, b, a) {
  38433. self.colorMask[0] = r;
  38434. self.colorMask[1] = g;
  38435. self.colorMask[2] = b;
  38436. self.colorMask[3] = a;
  38437. self.realColorMask.call(gl, r, g, b, a);
  38438. };
  38439. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  38440. gl.clearColor = function (r, g, b, a) {
  38441. self.clearColor[0] = r;
  38442. self.clearColor[1] = g;
  38443. self.clearColor[2] = b;
  38444. self.clearColor[3] = a;
  38445. self.realClearColor.call(gl, r, g, b, a);
  38446. };
  38447. this.viewport = gl.getParameter(gl.VIEWPORT);
  38448. gl.viewport = function (x, y, w, h) {
  38449. self.viewport[0] = x;
  38450. self.viewport[1] = y;
  38451. self.viewport[2] = w;
  38452. self.viewport[3] = h;
  38453. self.realViewport.call(gl, x, y, w, h);
  38454. };
  38455. this.isPatched = true;
  38456. safariCssSizeWorkaround(canvas);
  38457. };
  38458. CardboardDistorter.prototype.unpatch = function () {
  38459. if (!this.isPatched) {
  38460. return;
  38461. }
  38462. var gl = this.gl;
  38463. var canvas = this.gl.canvas;
  38464. if (!isIOS()) {
  38465. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  38466. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  38467. }
  38468. canvas.width = this.bufferWidth;
  38469. canvas.height = this.bufferHeight;
  38470. gl.bindFramebuffer = this.realBindFramebuffer;
  38471. gl.enable = this.realEnable;
  38472. gl.disable = this.realDisable;
  38473. gl.colorMask = this.realColorMask;
  38474. gl.clearColor = this.realClearColor;
  38475. gl.viewport = this.realViewport;
  38476. if (this.lastBoundFramebuffer == this.framebuffer) {
  38477. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  38478. }
  38479. this.isPatched = false;
  38480. setTimeout(function () {
  38481. safariCssSizeWorkaround(canvas);
  38482. }, 1);
  38483. };
  38484. CardboardDistorter.prototype.setTextureBounds = function (leftBounds, rightBounds) {
  38485. if (!leftBounds) {
  38486. leftBounds = [0, 0, 0.5, 1];
  38487. }
  38488. if (!rightBounds) {
  38489. rightBounds = [0.5, 0, 0.5, 1];
  38490. }
  38491. this.viewportOffsetScale[0] = leftBounds[0];
  38492. this.viewportOffsetScale[1] = leftBounds[1];
  38493. this.viewportOffsetScale[2] = leftBounds[2];
  38494. this.viewportOffsetScale[3] = leftBounds[3];
  38495. this.viewportOffsetScale[4] = rightBounds[0];
  38496. this.viewportOffsetScale[5] = rightBounds[1];
  38497. this.viewportOffsetScale[6] = rightBounds[2];
  38498. this.viewportOffsetScale[7] = rightBounds[3];
  38499. };
  38500. CardboardDistorter.prototype.submitFrame = function () {
  38501. var gl = this.gl;
  38502. var self = this;
  38503. var glState = [];
  38504. if (!this.dirtySubmitFrameBindings) {
  38505. glState.push(gl.CURRENT_PROGRAM, gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING, gl.TEXTURE_BINDING_2D, gl.TEXTURE0);
  38506. }
  38507. glPreserveState(gl, glState, function (gl) {
  38508. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  38509. if (self.cullFace) {
  38510. self.realDisable.call(gl, gl.CULL_FACE);
  38511. }
  38512. if (self.depthTest) {
  38513. self.realDisable.call(gl, gl.DEPTH_TEST);
  38514. }
  38515. if (self.blend) {
  38516. self.realDisable.call(gl, gl.BLEND);
  38517. }
  38518. if (self.scissorTest) {
  38519. self.realDisable.call(gl, gl.SCISSOR_TEST);
  38520. }
  38521. if (self.stencilTest) {
  38522. self.realDisable.call(gl, gl.STENCIL_TEST);
  38523. }
  38524. self.realColorMask.call(gl, true, true, true, true);
  38525. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38526. if (self.ctxAttribs.alpha || isIOS()) {
  38527. self.realClearColor.call(gl, 0, 0, 0, 1);
  38528. gl.clear(gl.COLOR_BUFFER_BIT);
  38529. }
  38530. gl.useProgram(self.program);
  38531. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38532. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38533. gl.enableVertexAttribArray(self.attribs.position);
  38534. gl.enableVertexAttribArray(self.attribs.texCoord);
  38535. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  38536. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  38537. gl.activeTexture(gl.TEXTURE0);
  38538. gl.uniform1i(self.uniforms.diffuse, 0);
  38539. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  38540. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  38541. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  38542. if (self.cardboardUI) {
  38543. self.cardboardUI.renderNoState();
  38544. }
  38545. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  38546. if (!self.ctxAttribs.preserveDrawingBuffer) {
  38547. self.realClearColor.call(gl, 0, 0, 0, 0);
  38548. gl.clear(gl.COLOR_BUFFER_BIT);
  38549. }
  38550. if (!self.dirtySubmitFrameBindings) {
  38551. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  38552. }
  38553. if (self.cullFace) {
  38554. self.realEnable.call(gl, gl.CULL_FACE);
  38555. }
  38556. if (self.depthTest) {
  38557. self.realEnable.call(gl, gl.DEPTH_TEST);
  38558. }
  38559. if (self.blend) {
  38560. self.realEnable.call(gl, gl.BLEND);
  38561. }
  38562. if (self.scissorTest) {
  38563. self.realEnable.call(gl, gl.SCISSOR_TEST);
  38564. }
  38565. if (self.stencilTest) {
  38566. self.realEnable.call(gl, gl.STENCIL_TEST);
  38567. }
  38568. self.realColorMask.apply(gl, self.colorMask);
  38569. self.realViewport.apply(gl, self.viewport);
  38570. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  38571. self.realClearColor.apply(gl, self.clearColor);
  38572. }
  38573. });
  38574. if (isIOS()) {
  38575. var canvas = gl.canvas;
  38576. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  38577. self.bufferWidth = canvas.width;
  38578. self.bufferHeight = canvas.height;
  38579. self.onResize();
  38580. }
  38581. }
  38582. };
  38583. CardboardDistorter.prototype.updateDeviceInfo = function (deviceInfo) {
  38584. var gl = this.gl;
  38585. var self = this;
  38586. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  38587. glPreserveState(gl, glState, function (gl) {
  38588. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  38589. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38590. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  38591. if (!self.indexCount) {
  38592. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  38593. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  38594. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  38595. self.indexCount = indices.length;
  38596. }
  38597. });
  38598. };
  38599. CardboardDistorter.prototype.computeMeshVertices_ = function (width, height, deviceInfo) {
  38600. var vertices = new Float32Array(2 * width * height * 5);
  38601. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  38602. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  38603. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  38604. var vidx = 0;
  38605. for (var e = 0; e < 2; e++) {
  38606. for (var j = 0; j < height; j++) {
  38607. for (var i = 0; i < width; i++, vidx++) {
  38608. var u = i / (width - 1);
  38609. var v = j / (height - 1);
  38610. var s = u;
  38611. var t = v;
  38612. var x = lerp(lensFrustum[0], lensFrustum[2], u);
  38613. var y = lerp(lensFrustum[3], lensFrustum[1], v);
  38614. var d = Math.sqrt(x * x + y * y);
  38615. var r = deviceInfo.distortion.distortInverse(d);
  38616. var p = x * r / d;
  38617. var q = y * r / d;
  38618. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  38619. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  38620. u = (viewport.x + u * viewport.width - 0.5) * 2.0;
  38621. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  38622. vertices[vidx * 5 + 0] = u;
  38623. vertices[vidx * 5 + 1] = v;
  38624. vertices[vidx * 5 + 2] = s;
  38625. vertices[vidx * 5 + 3] = t;
  38626. vertices[vidx * 5 + 4] = e;
  38627. }
  38628. }
  38629. var w = lensFrustum[2] - lensFrustum[0];
  38630. lensFrustum[0] = -(w + lensFrustum[0]);
  38631. lensFrustum[2] = w - lensFrustum[2];
  38632. w = noLensFrustum[2] - noLensFrustum[0];
  38633. noLensFrustum[0] = -(w + noLensFrustum[0]);
  38634. noLensFrustum[2] = w - noLensFrustum[2];
  38635. viewport.x = 1 - (viewport.x + viewport.width);
  38636. }
  38637. return vertices;
  38638. };
  38639. CardboardDistorter.prototype.computeMeshIndices_ = function (width, height) {
  38640. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  38641. var halfwidth = width / 2;
  38642. var halfheight = height / 2;
  38643. var vidx = 0;
  38644. var iidx = 0;
  38645. for (var e = 0; e < 2; e++) {
  38646. for (var j = 0; j < height; j++) {
  38647. for (var i = 0; i < width; i++, vidx++) {
  38648. if (i == 0 || j == 0) continue;
  38649. if (i <= halfwidth == j <= halfheight) {
  38650. indices[iidx++] = vidx;
  38651. indices[iidx++] = vidx - width - 1;
  38652. indices[iidx++] = vidx - width;
  38653. indices[iidx++] = vidx - width - 1;
  38654. indices[iidx++] = vidx;
  38655. indices[iidx++] = vidx - 1;
  38656. } else {
  38657. indices[iidx++] = vidx - 1;
  38658. indices[iidx++] = vidx - width;
  38659. indices[iidx++] = vidx;
  38660. indices[iidx++] = vidx - width;
  38661. indices[iidx++] = vidx - 1;
  38662. indices[iidx++] = vidx - width - 1;
  38663. }
  38664. }
  38665. }
  38666. }
  38667. return indices;
  38668. };
  38669. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function (proto, attrName) {
  38670. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  38671. if (descriptor.get === undefined || descriptor.set === undefined) {
  38672. descriptor.configurable = true;
  38673. descriptor.enumerable = true;
  38674. descriptor.get = function () {
  38675. return this.getAttribute(attrName);
  38676. };
  38677. descriptor.set = function (val) {
  38678. this.setAttribute(attrName, val);
  38679. };
  38680. }
  38681. return descriptor;
  38682. };
  38683. var uiVS = ['attribute vec2 position;', 'uniform mat4 projectionMat;', 'void main() {', ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );', '}'].join('\n');
  38684. var uiFS = ['precision mediump float;', 'uniform vec4 color;', 'void main() {', ' gl_FragColor = color;', '}'].join('\n');
  38685. var DEG2RAD = Math.PI / 180.0;
  38686. var kAnglePerGearSection = 60;
  38687. var kOuterRimEndAngle = 12;
  38688. var kInnerRimBeginAngle = 20;
  38689. var kOuterRadius = 1;
  38690. var kMiddleRadius = 0.75;
  38691. var kInnerRadius = 0.3125;
  38692. var kCenterLineThicknessDp = 4;
  38693. var kButtonWidthDp = 28;
  38694. var kTouchSlopFactor = 1.5;
  38695. function CardboardUI(gl) {
  38696. this.gl = gl;
  38697. this.attribs = {
  38698. position: 0
  38699. };
  38700. this.program = linkProgram(gl, uiVS, uiFS, this.attribs);
  38701. this.uniforms = getProgramUniforms(gl, this.program);
  38702. this.vertexBuffer = gl.createBuffer();
  38703. this.gearOffset = 0;
  38704. this.gearVertexCount = 0;
  38705. this.arrowOffset = 0;
  38706. this.arrowVertexCount = 0;
  38707. this.projMat = new Float32Array(16);
  38708. this.listener = null;
  38709. this.onResize();
  38710. }
  38711. CardboardUI.prototype.destroy = function () {
  38712. var gl = this.gl;
  38713. if (this.listener) {
  38714. gl.canvas.removeEventListener('click', this.listener, false);
  38715. }
  38716. gl.deleteProgram(this.program);
  38717. gl.deleteBuffer(this.vertexBuffer);
  38718. };
  38719. CardboardUI.prototype.listen = function (optionsCallback, backCallback) {
  38720. var canvas = this.gl.canvas;
  38721. this.listener = function (event) {
  38722. var midline = canvas.clientWidth / 2;
  38723. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  38724. if (event.clientX > midline - buttonSize && event.clientX < midline + buttonSize && event.clientY > canvas.clientHeight - buttonSize) {
  38725. optionsCallback(event);
  38726. }
  38727. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  38728. backCallback(event);
  38729. }
  38730. };
  38731. canvas.addEventListener('click', this.listener, false);
  38732. };
  38733. CardboardUI.prototype.onResize = function () {
  38734. var gl = this.gl;
  38735. var self = this;
  38736. var glState = [gl.ARRAY_BUFFER_BINDING];
  38737. glPreserveState(gl, glState, function (gl) {
  38738. var vertices = [];
  38739. var midline = gl.drawingBufferWidth / 2;
  38740. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  38741. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  38742. var dps = scalingRatio * window.devicePixelRatio;
  38743. var lineWidth = kCenterLineThicknessDp * dps / 2;
  38744. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  38745. var buttonScale = kButtonWidthDp * dps / 2;
  38746. var buttonBorder = (kButtonWidthDp * kTouchSlopFactor - kButtonWidthDp) * dps;
  38747. vertices.push(midline - lineWidth, buttonSize);
  38748. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  38749. vertices.push(midline + lineWidth, buttonSize);
  38750. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  38751. self.gearOffset = vertices.length / 2;
  38752. function addGearSegment(theta, r) {
  38753. var angle = (90 - theta) * DEG2RAD;
  38754. var x = Math.cos(angle);
  38755. var y = Math.sin(angle);
  38756. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  38757. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  38758. }
  38759. for (var i = 0; i <= 6; i++) {
  38760. var segmentTheta = i * kAnglePerGearSection;
  38761. addGearSegment(segmentTheta, kOuterRadius);
  38762. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  38763. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  38764. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  38765. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  38766. }
  38767. self.gearVertexCount = vertices.length / 2 - self.gearOffset;
  38768. self.arrowOffset = vertices.length / 2;
  38769. function addArrowVertex(x, y) {
  38770. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  38771. }
  38772. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  38773. addArrowVertex(0, buttonScale);
  38774. addArrowVertex(buttonScale, 0);
  38775. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  38776. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  38777. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38778. addArrowVertex(0, buttonScale);
  38779. addArrowVertex(buttonScale, buttonScale * 2);
  38780. addArrowVertex(buttonScale + angledLineWidth, buttonScale * 2 - angledLineWidth);
  38781. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  38782. addArrowVertex(0, buttonScale);
  38783. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  38784. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  38785. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  38786. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  38787. self.arrowVertexCount = vertices.length / 2 - self.arrowOffset;
  38788. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  38789. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  38790. });
  38791. };
  38792. CardboardUI.prototype.render = function () {
  38793. var gl = this.gl;
  38794. var self = this;
  38795. 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];
  38796. glPreserveState(gl, glState, function (gl) {
  38797. gl.disable(gl.CULL_FACE);
  38798. gl.disable(gl.DEPTH_TEST);
  38799. gl.disable(gl.BLEND);
  38800. gl.disable(gl.SCISSOR_TEST);
  38801. gl.disable(gl.STENCIL_TEST);
  38802. gl.colorMask(true, true, true, true);
  38803. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  38804. self.renderNoState();
  38805. });
  38806. };
  38807. CardboardUI.prototype.renderNoState = function () {
  38808. var gl = this.gl;
  38809. gl.useProgram(this.program);
  38810. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  38811. gl.enableVertexAttribArray(this.attribs.position);
  38812. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  38813. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  38814. orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  38815. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  38816. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  38817. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  38818. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  38819. };
  38820. function Distortion(coefficients) {
  38821. this.coefficients = coefficients;
  38822. }
  38823. Distortion.prototype.distortInverse = function (radius) {
  38824. var r0 = 0;
  38825. var r1 = 1;
  38826. var dr0 = radius - this.distort(r0);
  38827. while (Math.abs(r1 - r0) > 0.0001 ) {
  38828. var dr1 = radius - this.distort(r1);
  38829. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38830. r0 = r1;
  38831. r1 = r2;
  38832. dr0 = dr1;
  38833. }
  38834. return r1;
  38835. };
  38836. Distortion.prototype.distort = function (radius) {
  38837. var r2 = radius * radius;
  38838. var ret = 0;
  38839. for (var i = 0; i < this.coefficients.length; i++) {
  38840. ret = r2 * (ret + this.coefficients[i]);
  38841. }
  38842. return (ret + 1) * radius;
  38843. };
  38844. var degToRad = Math.PI / 180;
  38845. var radToDeg = 180 / Math.PI;
  38846. var Vector3 = function Vector3(x, y, z) {
  38847. this.x = x || 0;
  38848. this.y = y || 0;
  38849. this.z = z || 0;
  38850. };
  38851. Vector3.prototype = {
  38852. constructor: Vector3,
  38853. set: function set(x, y, z) {
  38854. this.x = x;
  38855. this.y = y;
  38856. this.z = z;
  38857. return this;
  38858. },
  38859. copy: function copy(v) {
  38860. this.x = v.x;
  38861. this.y = v.y;
  38862. this.z = v.z;
  38863. return this;
  38864. },
  38865. length: function length() {
  38866. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  38867. },
  38868. normalize: function normalize() {
  38869. var scalar = this.length();
  38870. if (scalar !== 0) {
  38871. var invScalar = 1 / scalar;
  38872. this.multiplyScalar(invScalar);
  38873. } else {
  38874. this.x = 0;
  38875. this.y = 0;
  38876. this.z = 0;
  38877. }
  38878. return this;
  38879. },
  38880. multiplyScalar: function multiplyScalar(scalar) {
  38881. this.x *= scalar;
  38882. this.y *= scalar;
  38883. this.z *= scalar;
  38884. },
  38885. applyQuaternion: function applyQuaternion(q) {
  38886. var x = this.x;
  38887. var y = this.y;
  38888. var z = this.z;
  38889. var qx = q.x;
  38890. var qy = q.y;
  38891. var qz = q.z;
  38892. var qw = q.w;
  38893. var ix = qw * x + qy * z - qz * y;
  38894. var iy = qw * y + qz * x - qx * z;
  38895. var iz = qw * z + qx * y - qy * x;
  38896. var iw = -qx * x - qy * y - qz * z;
  38897. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  38898. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  38899. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  38900. return this;
  38901. },
  38902. dot: function dot(v) {
  38903. return this.x * v.x + this.y * v.y + this.z * v.z;
  38904. },
  38905. crossVectors: function crossVectors(a, b) {
  38906. var ax = a.x,
  38907. ay = a.y,
  38908. az = a.z;
  38909. var bx = b.x,
  38910. by = b.y,
  38911. bz = b.z;
  38912. this.x = ay * bz - az * by;
  38913. this.y = az * bx - ax * bz;
  38914. this.z = ax * by - ay * bx;
  38915. return this;
  38916. }
  38917. };
  38918. var Quaternion = function Quaternion(x, y, z, w) {
  38919. this.x = x || 0;
  38920. this.y = y || 0;
  38921. this.z = z || 0;
  38922. this.w = w !== undefined ? w : 1;
  38923. };
  38924. Quaternion.prototype = {
  38925. constructor: Quaternion,
  38926. set: function set(x, y, z, w) {
  38927. this.x = x;
  38928. this.y = y;
  38929. this.z = z;
  38930. this.w = w;
  38931. return this;
  38932. },
  38933. copy: function copy(quaternion) {
  38934. this.x = quaternion.x;
  38935. this.y = quaternion.y;
  38936. this.z = quaternion.z;
  38937. this.w = quaternion.w;
  38938. return this;
  38939. },
  38940. setFromEulerXYZ: function setFromEulerXYZ(x, y, z) {
  38941. var c1 = Math.cos(x / 2);
  38942. var c2 = Math.cos(y / 2);
  38943. var c3 = Math.cos(z / 2);
  38944. var s1 = Math.sin(x / 2);
  38945. var s2 = Math.sin(y / 2);
  38946. var s3 = Math.sin(z / 2);
  38947. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38948. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38949. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  38950. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  38951. return this;
  38952. },
  38953. setFromEulerYXZ: function setFromEulerYXZ(x, y, z) {
  38954. var c1 = Math.cos(x / 2);
  38955. var c2 = Math.cos(y / 2);
  38956. var c3 = Math.cos(z / 2);
  38957. var s1 = Math.sin(x / 2);
  38958. var s2 = Math.sin(y / 2);
  38959. var s3 = Math.sin(z / 2);
  38960. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  38961. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  38962. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  38963. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  38964. return this;
  38965. },
  38966. setFromAxisAngle: function setFromAxisAngle(axis, angle) {
  38967. var halfAngle = angle / 2,
  38968. s = Math.sin(halfAngle);
  38969. this.x = axis.x * s;
  38970. this.y = axis.y * s;
  38971. this.z = axis.z * s;
  38972. this.w = Math.cos(halfAngle);
  38973. return this;
  38974. },
  38975. multiply: function multiply(q) {
  38976. return this.multiplyQuaternions(this, q);
  38977. },
  38978. multiplyQuaternions: function multiplyQuaternions(a, b) {
  38979. var qax = a.x,
  38980. qay = a.y,
  38981. qaz = a.z,
  38982. qaw = a.w;
  38983. var qbx = b.x,
  38984. qby = b.y,
  38985. qbz = b.z,
  38986. qbw = b.w;
  38987. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  38988. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  38989. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  38990. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  38991. return this;
  38992. },
  38993. inverse: function inverse() {
  38994. this.x *= -1;
  38995. this.y *= -1;
  38996. this.z *= -1;
  38997. this.normalize();
  38998. return this;
  38999. },
  39000. normalize: function normalize() {
  39001. var l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  39002. if (l === 0) {
  39003. this.x = 0;
  39004. this.y = 0;
  39005. this.z = 0;
  39006. this.w = 1;
  39007. } else {
  39008. l = 1 / l;
  39009. this.x = this.x * l;
  39010. this.y = this.y * l;
  39011. this.z = this.z * l;
  39012. this.w = this.w * l;
  39013. }
  39014. return this;
  39015. },
  39016. slerp: function slerp(qb, t) {
  39017. if (t === 0) return this;
  39018. if (t === 1) return this.copy(qb);
  39019. var x = this.x,
  39020. y = this.y,
  39021. z = this.z,
  39022. w = this.w;
  39023. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  39024. if (cosHalfTheta < 0) {
  39025. this.w = -qb.w;
  39026. this.x = -qb.x;
  39027. this.y = -qb.y;
  39028. this.z = -qb.z;
  39029. cosHalfTheta = -cosHalfTheta;
  39030. } else {
  39031. this.copy(qb);
  39032. }
  39033. if (cosHalfTheta >= 1.0) {
  39034. this.w = w;
  39035. this.x = x;
  39036. this.y = y;
  39037. this.z = z;
  39038. return this;
  39039. }
  39040. var halfTheta = Math.acos(cosHalfTheta);
  39041. var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
  39042. if (Math.abs(sinHalfTheta) < 0.001) {
  39043. this.w = 0.5 * (w + this.w);
  39044. this.x = 0.5 * (x + this.x);
  39045. this.y = 0.5 * (y + this.y);
  39046. this.z = 0.5 * (z + this.z);
  39047. return this;
  39048. }
  39049. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  39050. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  39051. this.w = w * ratioA + this.w * ratioB;
  39052. this.x = x * ratioA + this.x * ratioB;
  39053. this.y = y * ratioA + this.y * ratioB;
  39054. this.z = z * ratioA + this.z * ratioB;
  39055. return this;
  39056. },
  39057. setFromUnitVectors: function () {
  39058. var v1, r;
  39059. var EPS = 0.000001;
  39060. return function (vFrom, vTo) {
  39061. if (v1 === undefined) v1 = new Vector3();
  39062. r = vFrom.dot(vTo) + 1;
  39063. if (r < EPS) {
  39064. r = 0;
  39065. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  39066. v1.set(-vFrom.y, vFrom.x, 0);
  39067. } else {
  39068. v1.set(0, -vFrom.z, vFrom.y);
  39069. }
  39070. } else {
  39071. v1.crossVectors(vFrom, vTo);
  39072. }
  39073. this.x = v1.x;
  39074. this.y = v1.y;
  39075. this.z = v1.z;
  39076. this.w = r;
  39077. this.normalize();
  39078. return this;
  39079. };
  39080. }()
  39081. };
  39082. function Device(params) {
  39083. this.width = params.width || getScreenWidth();
  39084. this.height = params.height || getScreenHeight();
  39085. this.widthMeters = params.widthMeters;
  39086. this.heightMeters = params.heightMeters;
  39087. this.bevelMeters = params.bevelMeters;
  39088. }
  39089. var DEFAULT_ANDROID = new Device({
  39090. widthMeters: 0.110,
  39091. heightMeters: 0.062,
  39092. bevelMeters: 0.004
  39093. });
  39094. var DEFAULT_IOS = new Device({
  39095. widthMeters: 0.1038,
  39096. heightMeters: 0.0584,
  39097. bevelMeters: 0.004
  39098. });
  39099. var Viewers = {
  39100. CardboardV1: new CardboardViewer({
  39101. id: 'CardboardV1',
  39102. label: 'Cardboard I/O 2014',
  39103. fov: 40,
  39104. interLensDistance: 0.060,
  39105. baselineLensDistance: 0.035,
  39106. screenLensDistance: 0.042,
  39107. distortionCoefficients: [0.441, 0.156],
  39108. 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]
  39109. }),
  39110. CardboardV2: new CardboardViewer({
  39111. id: 'CardboardV2',
  39112. label: 'Cardboard I/O 2015',
  39113. fov: 60,
  39114. interLensDistance: 0.064,
  39115. baselineLensDistance: 0.035,
  39116. screenLensDistance: 0.039,
  39117. distortionCoefficients: [0.34, 0.55],
  39118. 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]
  39119. })
  39120. };
  39121. function DeviceInfo(deviceParams, additionalViewers) {
  39122. this.viewer = Viewers.CardboardV2;
  39123. this.updateDeviceParams(deviceParams);
  39124. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  39125. for (var i = 0; i < additionalViewers.length; i++) {
  39126. var viewer = additionalViewers[i];
  39127. Viewers[viewer.id] = new CardboardViewer(viewer);
  39128. }
  39129. }
  39130. DeviceInfo.prototype.updateDeviceParams = function (deviceParams) {
  39131. this.device = this.determineDevice_(deviceParams) || this.device;
  39132. };
  39133. DeviceInfo.prototype.getDevice = function () {
  39134. return this.device;
  39135. };
  39136. DeviceInfo.prototype.setViewer = function (viewer) {
  39137. this.viewer = viewer;
  39138. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  39139. };
  39140. DeviceInfo.prototype.determineDevice_ = function (deviceParams) {
  39141. if (!deviceParams) {
  39142. if (isIOS()) {
  39143. console.warn('Using fallback iOS device measurements.');
  39144. return DEFAULT_IOS;
  39145. } else {
  39146. console.warn('Using fallback Android device measurements.');
  39147. return DEFAULT_ANDROID;
  39148. }
  39149. }
  39150. var METERS_PER_INCH = 0.0254;
  39151. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  39152. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  39153. var width = getScreenWidth();
  39154. var height = getScreenHeight();
  39155. return new Device({
  39156. widthMeters: metersPerPixelX * width,
  39157. heightMeters: metersPerPixelY * height,
  39158. bevelMeters: deviceParams.bevelMm * 0.001
  39159. });
  39160. };
  39161. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function () {
  39162. var viewer = this.viewer;
  39163. var device = this.device;
  39164. var distortion = this.distortion;
  39165. var eyeToScreenDistance = viewer.screenLensDistance;
  39166. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  39167. var innerDist = viewer.interLensDistance / 2;
  39168. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  39169. var topDist = device.heightMeters - bottomDist;
  39170. var outerAngle = radToDeg * Math.atan(distortion.distort(outerDist / eyeToScreenDistance));
  39171. var innerAngle = radToDeg * Math.atan(distortion.distort(innerDist / eyeToScreenDistance));
  39172. var bottomAngle = radToDeg * Math.atan(distortion.distort(bottomDist / eyeToScreenDistance));
  39173. var topAngle = radToDeg * Math.atan(distortion.distort(topDist / eyeToScreenDistance));
  39174. return {
  39175. leftDegrees: Math.min(outerAngle, viewer.fov),
  39176. rightDegrees: Math.min(innerAngle, viewer.fov),
  39177. downDegrees: Math.min(bottomAngle, viewer.fov),
  39178. upDegrees: Math.min(topAngle, viewer.fov)
  39179. };
  39180. };
  39181. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function () {
  39182. var viewer = this.viewer;
  39183. var device = this.device;
  39184. var distortion = this.distortion;
  39185. var fovLeft = Math.tan(-degToRad * viewer.fov);
  39186. var fovTop = Math.tan(degToRad * viewer.fov);
  39187. var fovRight = Math.tan(degToRad * viewer.fov);
  39188. var fovBottom = Math.tan(-degToRad * viewer.fov);
  39189. var halfWidth = device.widthMeters / 4;
  39190. var halfHeight = device.heightMeters / 2;
  39191. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  39192. var centerX = viewer.interLensDistance / 2 - halfWidth;
  39193. var centerY = -verticalLensOffset;
  39194. var centerZ = viewer.screenLensDistance;
  39195. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  39196. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  39197. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  39198. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  39199. var result = new Float32Array(4);
  39200. result[0] = Math.max(fovLeft, screenLeft);
  39201. result[1] = Math.min(fovTop, screenTop);
  39202. result[2] = Math.min(fovRight, screenRight);
  39203. result[3] = Math.max(fovBottom, screenBottom);
  39204. return result;
  39205. };
  39206. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function () {
  39207. var viewer = this.viewer;
  39208. var device = this.device;
  39209. var distortion = this.distortion;
  39210. var result = new Float32Array(4);
  39211. var fovLeft = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  39212. var fovTop = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  39213. var fovRight = distortion.distortInverse(Math.tan(degToRad * viewer.fov));
  39214. var fovBottom = distortion.distortInverse(Math.tan(-degToRad * viewer.fov));
  39215. var halfWidth = device.widthMeters / 4;
  39216. var halfHeight = device.heightMeters / 2;
  39217. var verticalLensOffset = viewer.baselineLensDistance - device.bevelMeters - halfHeight;
  39218. var centerX = viewer.interLensDistance / 2 - halfWidth;
  39219. var centerY = -verticalLensOffset;
  39220. var centerZ = viewer.screenLensDistance;
  39221. var screenLeft = (centerX - halfWidth) / centerZ;
  39222. var screenTop = (centerY + halfHeight) / centerZ;
  39223. var screenRight = (centerX + halfWidth) / centerZ;
  39224. var screenBottom = (centerY - halfHeight) / centerZ;
  39225. result[0] = Math.max(fovLeft, screenLeft);
  39226. result[1] = Math.min(fovTop, screenTop);
  39227. result[2] = Math.min(fovRight, screenRight);
  39228. result[3] = Math.max(fovBottom, screenBottom);
  39229. return result;
  39230. };
  39231. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function (undistortedFrustum) {
  39232. var viewer = this.viewer;
  39233. var device = this.device;
  39234. var dist = viewer.screenLensDistance;
  39235. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  39236. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  39237. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  39238. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  39239. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  39240. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  39241. return {
  39242. x: left,
  39243. y: bottom,
  39244. width: right - left,
  39245. height: top - bottom
  39246. };
  39247. };
  39248. DeviceInfo.prototype.getFieldOfViewLeftEye = function (opt_isUndistorted) {
  39249. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() : this.getDistortedFieldOfViewLeftEye();
  39250. };
  39251. DeviceInfo.prototype.getFieldOfViewRightEye = function (opt_isUndistorted) {
  39252. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  39253. return {
  39254. leftDegrees: fov.rightDegrees,
  39255. rightDegrees: fov.leftDegrees,
  39256. upDegrees: fov.upDegrees,
  39257. downDegrees: fov.downDegrees
  39258. };
  39259. };
  39260. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function () {
  39261. var p = this.getUndistortedParams_();
  39262. return {
  39263. leftDegrees: radToDeg * Math.atan(p.outerDist),
  39264. rightDegrees: radToDeg * Math.atan(p.innerDist),
  39265. downDegrees: radToDeg * Math.atan(p.bottomDist),
  39266. upDegrees: radToDeg * Math.atan(p.topDist)
  39267. };
  39268. };
  39269. DeviceInfo.prototype.getUndistortedViewportLeftEye = function () {
  39270. var p = this.getUndistortedParams_();
  39271. var viewer = this.viewer;
  39272. var device = this.device;
  39273. var eyeToScreenDistance = viewer.screenLensDistance;
  39274. var screenWidth = device.widthMeters / eyeToScreenDistance;
  39275. var screenHeight = device.heightMeters / eyeToScreenDistance;
  39276. var xPxPerTanAngle = device.width / screenWidth;
  39277. var yPxPerTanAngle = device.height / screenHeight;
  39278. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  39279. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  39280. return {
  39281. x: x,
  39282. y: y,
  39283. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  39284. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  39285. };
  39286. };
  39287. DeviceInfo.prototype.getUndistortedParams_ = function () {
  39288. var viewer = this.viewer;
  39289. var device = this.device;
  39290. var distortion = this.distortion;
  39291. var eyeToScreenDistance = viewer.screenLensDistance;
  39292. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  39293. var screenWidth = device.widthMeters / eyeToScreenDistance;
  39294. var screenHeight = device.heightMeters / eyeToScreenDistance;
  39295. var eyePosX = screenWidth / 2 - halfLensDistance;
  39296. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  39297. var maxFov = viewer.fov;
  39298. var viewerMax = distortion.distortInverse(Math.tan(degToRad * maxFov));
  39299. var outerDist = Math.min(eyePosX, viewerMax);
  39300. var innerDist = Math.min(halfLensDistance, viewerMax);
  39301. var bottomDist = Math.min(eyePosY, viewerMax);
  39302. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  39303. return {
  39304. outerDist: outerDist,
  39305. innerDist: innerDist,
  39306. topDist: topDist,
  39307. bottomDist: bottomDist,
  39308. eyePosX: eyePosX,
  39309. eyePosY: eyePosY
  39310. };
  39311. };
  39312. function CardboardViewer(params) {
  39313. this.id = params.id;
  39314. this.label = params.label;
  39315. this.fov = params.fov;
  39316. this.interLensDistance = params.interLensDistance;
  39317. this.baselineLensDistance = params.baselineLensDistance;
  39318. this.screenLensDistance = params.screenLensDistance;
  39319. this.distortionCoefficients = params.distortionCoefficients;
  39320. this.inverseCoefficients = params.inverseCoefficients;
  39321. }
  39322. DeviceInfo.Viewers = Viewers;
  39323. var format = 1;
  39324. var last_updated = "2018-12-10T17:01:42Z";
  39325. 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}];
  39326. var DPDB_CACHE = {
  39327. format: format,
  39328. last_updated: last_updated,
  39329. devices: devices
  39330. };
  39331. function Dpdb(url, onDeviceParamsUpdated) {
  39332. this.dpdb = DPDB_CACHE;
  39333. this.recalculateDeviceParams_();
  39334. if (url) {
  39335. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  39336. var xhr = new XMLHttpRequest();
  39337. var obj = this;
  39338. xhr.open('GET', url, true);
  39339. xhr.addEventListener('load', function () {
  39340. obj.loading = false;
  39341. if (xhr.status >= 200 && xhr.status <= 299) {
  39342. obj.dpdb = JSON.parse(xhr.response);
  39343. obj.recalculateDeviceParams_();
  39344. } else {
  39345. console.error('Error loading online DPDB!');
  39346. }
  39347. });
  39348. xhr.send();
  39349. }
  39350. }
  39351. Dpdb.prototype.getDeviceParams = function () {
  39352. return this.deviceParams;
  39353. };
  39354. Dpdb.prototype.recalculateDeviceParams_ = function () {
  39355. var newDeviceParams = this.calcDeviceParams_();
  39356. if (newDeviceParams) {
  39357. this.deviceParams = newDeviceParams;
  39358. if (this.onDeviceParamsUpdated) {
  39359. this.onDeviceParamsUpdated(this.deviceParams);
  39360. }
  39361. } else {
  39362. console.error('Failed to recalculate device parameters.');
  39363. }
  39364. };
  39365. Dpdb.prototype.calcDeviceParams_ = function () {
  39366. var db = this.dpdb;
  39367. if (!db) {
  39368. console.error('DPDB not available.');
  39369. return null;
  39370. }
  39371. if (db.format != 1) {
  39372. console.error('DPDB has unexpected format version.');
  39373. return null;
  39374. }
  39375. if (!db.devices || !db.devices.length) {
  39376. console.error('DPDB does not have a devices section.');
  39377. return null;
  39378. }
  39379. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  39380. var width = getScreenWidth();
  39381. var height = getScreenHeight();
  39382. if (!db.devices) {
  39383. console.error('DPDB has no devices section.');
  39384. return null;
  39385. }
  39386. for (var i = 0; i < db.devices.length; i++) {
  39387. var device = db.devices[i];
  39388. if (!device.rules) {
  39389. console.warn('Device[' + i + '] has no rules section.');
  39390. continue;
  39391. }
  39392. if (device.type != 'ios' && device.type != 'android') {
  39393. console.warn('Device[' + i + '] has invalid type.');
  39394. continue;
  39395. }
  39396. if (isIOS() != (device.type == 'ios')) continue;
  39397. var matched = false;
  39398. for (var j = 0; j < device.rules.length; j++) {
  39399. var rule = device.rules[j];
  39400. if (this.ruleMatches_(rule, userAgent, width, height)) {
  39401. matched = true;
  39402. break;
  39403. }
  39404. }
  39405. if (!matched) continue;
  39406. var xdpi = device.dpi[0] || device.dpi;
  39407. var ydpi = device.dpi[1] || device.dpi;
  39408. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  39409. }
  39410. console.warn('No DPDB device match.');
  39411. return null;
  39412. };
  39413. Dpdb.prototype.ruleMatches_ = function (rule, ua, screenWidth, screenHeight) {
  39414. if (!rule.ua && !rule.res) return false;
  39415. if (rule.ua && rule.ua.substring(0, 2) === 'SM') rule.ua = rule.ua.substring(0, 7);
  39416. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  39417. if (rule.res) {
  39418. if (!rule.res[0] || !rule.res[1]) return false;
  39419. var resX = rule.res[0];
  39420. var resY = rule.res[1];
  39421. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) || Math.max(screenWidth, screenHeight) != Math.max(resX, resY)) {
  39422. return false;
  39423. }
  39424. }
  39425. return true;
  39426. };
  39427. function DeviceParams(params) {
  39428. this.xdpi = params.xdpi;
  39429. this.ydpi = params.ydpi;
  39430. this.bevelMm = params.bevelMm;
  39431. }
  39432. function SensorSample(sample, timestampS) {
  39433. this.set(sample, timestampS);
  39434. }
  39435. SensorSample.prototype.set = function (sample, timestampS) {
  39436. this.sample = sample;
  39437. this.timestampS = timestampS;
  39438. };
  39439. SensorSample.prototype.copy = function (sensorSample) {
  39440. this.set(sensorSample.sample, sensorSample.timestampS);
  39441. };
  39442. function ComplementaryFilter(kFilter, isDebug) {
  39443. this.kFilter = kFilter;
  39444. this.isDebug = isDebug;
  39445. this.currentAccelMeasurement = new SensorSample();
  39446. this.currentGyroMeasurement = new SensorSample();
  39447. this.previousGyroMeasurement = new SensorSample();
  39448. if (isIOS()) {
  39449. this.filterQ = new Quaternion(-1, 0, 0, 1);
  39450. } else {
  39451. this.filterQ = new Quaternion(1, 0, 0, 1);
  39452. }
  39453. this.previousFilterQ = new Quaternion();
  39454. this.previousFilterQ.copy(this.filterQ);
  39455. this.accelQ = new Quaternion();
  39456. this.isOrientationInitialized = false;
  39457. this.estimatedGravity = new Vector3();
  39458. this.measuredGravity = new Vector3();
  39459. this.gyroIntegralQ = new Quaternion();
  39460. }
  39461. ComplementaryFilter.prototype.addAccelMeasurement = function (vector, timestampS) {
  39462. this.currentAccelMeasurement.set(vector, timestampS);
  39463. };
  39464. ComplementaryFilter.prototype.addGyroMeasurement = function (vector, timestampS) {
  39465. this.currentGyroMeasurement.set(vector, timestampS);
  39466. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  39467. if (isTimestampDeltaValid(deltaT)) {
  39468. this.run_();
  39469. }
  39470. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  39471. };
  39472. ComplementaryFilter.prototype.run_ = function () {
  39473. if (!this.isOrientationInitialized) {
  39474. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  39475. this.previousFilterQ.copy(this.accelQ);
  39476. this.isOrientationInitialized = true;
  39477. return;
  39478. }
  39479. var deltaT = this.currentGyroMeasurement.timestampS - this.previousGyroMeasurement.timestampS;
  39480. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  39481. this.gyroIntegralQ.multiply(gyroDeltaQ);
  39482. this.filterQ.copy(this.previousFilterQ);
  39483. this.filterQ.multiply(gyroDeltaQ);
  39484. var invFilterQ = new Quaternion();
  39485. invFilterQ.copy(this.filterQ);
  39486. invFilterQ.inverse();
  39487. this.estimatedGravity.set(0, 0, -1);
  39488. this.estimatedGravity.applyQuaternion(invFilterQ);
  39489. this.estimatedGravity.normalize();
  39490. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  39491. this.measuredGravity.normalize();
  39492. var deltaQ = new Quaternion();
  39493. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  39494. deltaQ.inverse();
  39495. if (this.isDebug) {
  39496. 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));
  39497. }
  39498. var targetQ = new Quaternion();
  39499. targetQ.copy(this.filterQ);
  39500. targetQ.multiply(deltaQ);
  39501. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  39502. this.previousFilterQ.copy(this.filterQ);
  39503. };
  39504. ComplementaryFilter.prototype.getOrientation = function () {
  39505. return this.filterQ;
  39506. };
  39507. ComplementaryFilter.prototype.accelToQuaternion_ = function (accel) {
  39508. var normAccel = new Vector3();
  39509. normAccel.copy(accel);
  39510. normAccel.normalize();
  39511. var quat = new Quaternion();
  39512. quat.setFromUnitVectors(new Vector3(0, 0, -1), normAccel);
  39513. quat.inverse();
  39514. return quat;
  39515. };
  39516. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function (gyro, dt) {
  39517. var quat = new Quaternion();
  39518. var axis = new Vector3();
  39519. axis.copy(gyro);
  39520. axis.normalize();
  39521. quat.setFromAxisAngle(axis, gyro.length() * dt);
  39522. return quat;
  39523. };
  39524. function PosePredictor(predictionTimeS, isDebug) {
  39525. this.predictionTimeS = predictionTimeS;
  39526. this.isDebug = isDebug;
  39527. this.previousQ = new Quaternion();
  39528. this.previousTimestampS = null;
  39529. this.deltaQ = new Quaternion();
  39530. this.outQ = new Quaternion();
  39531. }
  39532. PosePredictor.prototype.getPrediction = function (currentQ, gyro, timestampS) {
  39533. if (!this.previousTimestampS) {
  39534. this.previousQ.copy(currentQ);
  39535. this.previousTimestampS = timestampS;
  39536. return currentQ;
  39537. }
  39538. var axis = new Vector3();
  39539. axis.copy(gyro);
  39540. axis.normalize();
  39541. var angularSpeed = gyro.length();
  39542. if (angularSpeed < degToRad * 20) {
  39543. if (this.isDebug) {
  39544. console.log('Moving slowly, at %s deg/s: no prediction', (radToDeg * angularSpeed).toFixed(1));
  39545. }
  39546. this.outQ.copy(currentQ);
  39547. this.previousQ.copy(currentQ);
  39548. return this.outQ;
  39549. }
  39550. var predictAngle = angularSpeed * this.predictionTimeS;
  39551. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  39552. this.outQ.copy(this.previousQ);
  39553. this.outQ.multiply(this.deltaQ);
  39554. this.previousQ.copy(currentQ);
  39555. this.previousTimestampS = timestampS;
  39556. return this.outQ;
  39557. };
  39558. function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) {
  39559. this.yawOnly = yawOnly;
  39560. this.accelerometer = new Vector3();
  39561. this.gyroscope = new Vector3();
  39562. this.filter = new ComplementaryFilter(kFilter, isDebug);
  39563. this.posePredictor = new PosePredictor(predictionTime, isDebug);
  39564. this.isFirefoxAndroid = isFirefoxAndroid();
  39565. this.isIOS = isIOS();
  39566. var chromeVersion = getChromeVersion();
  39567. this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66;
  39568. this.isWithoutDeviceMotion = isChromeWithoutDeviceMotion();
  39569. this.filterToWorldQ = new Quaternion();
  39570. if (isIOS()) {
  39571. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  39572. } else {
  39573. this.filterToWorldQ.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39574. }
  39575. this.inverseWorldToScreenQ = new Quaternion();
  39576. this.worldToScreenQ = new Quaternion();
  39577. this.originalPoseAdjustQ = new Quaternion();
  39578. this.originalPoseAdjustQ.setFromAxisAngle(new Vector3(0, 0, 1), -window.orientation * Math.PI / 180);
  39579. this.setScreenTransform_();
  39580. if (isLandscapeMode()) {
  39581. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  39582. }
  39583. this.resetQ = new Quaternion();
  39584. this.orientationOut_ = new Float32Array(4);
  39585. this.start();
  39586. }
  39587. FusionPoseSensor.prototype.getPosition = function () {
  39588. return null;
  39589. };
  39590. FusionPoseSensor.prototype.getOrientation = function () {
  39591. var orientation = void 0;
  39592. if (this.isWithoutDeviceMotion && this._deviceOrientationQ) {
  39593. this.deviceOrientationFixQ = this.deviceOrientationFixQ || function () {
  39594. var z = new Quaternion().setFromAxisAngle(new Vector3(0, 0, -1), 0);
  39595. var y = new Quaternion();
  39596. if (window.orientation === -90) {
  39597. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / -2);
  39598. } else {
  39599. y.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);
  39600. }
  39601. return z.multiply(y);
  39602. }();
  39603. this.deviceOrientationFilterToWorldQ = this.deviceOrientationFilterToWorldQ || function () {
  39604. var q = new Quaternion();
  39605. q.setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  39606. return q;
  39607. }();
  39608. orientation = this._deviceOrientationQ;
  39609. var out = new Quaternion();
  39610. out.copy(orientation);
  39611. out.multiply(this.deviceOrientationFilterToWorldQ);
  39612. out.multiply(this.resetQ);
  39613. out.multiply(this.worldToScreenQ);
  39614. out.multiplyQuaternions(this.deviceOrientationFixQ, out);
  39615. if (this.yawOnly) {
  39616. out.x = 0;
  39617. out.z = 0;
  39618. out.normalize();
  39619. }
  39620. this.orientationOut_[0] = out.x;
  39621. this.orientationOut_[1] = out.y;
  39622. this.orientationOut_[2] = out.z;
  39623. this.orientationOut_[3] = out.w;
  39624. return this.orientationOut_;
  39625. } else {
  39626. var filterOrientation = this.filter.getOrientation();
  39627. orientation = this.posePredictor.getPrediction(filterOrientation, this.gyroscope, this.previousTimestampS);
  39628. }
  39629. var out = new Quaternion();
  39630. out.copy(this.filterToWorldQ);
  39631. out.multiply(this.resetQ);
  39632. out.multiply(orientation);
  39633. out.multiply(this.worldToScreenQ);
  39634. if (this.yawOnly) {
  39635. out.x = 0;
  39636. out.z = 0;
  39637. out.normalize();
  39638. }
  39639. this.orientationOut_[0] = out.x;
  39640. this.orientationOut_[1] = out.y;
  39641. this.orientationOut_[2] = out.z;
  39642. this.orientationOut_[3] = out.w;
  39643. return this.orientationOut_;
  39644. };
  39645. FusionPoseSensor.prototype.resetPose = function () {
  39646. this.resetQ.copy(this.filter.getOrientation());
  39647. this.resetQ.x = 0;
  39648. this.resetQ.y = 0;
  39649. this.resetQ.z *= -1;
  39650. this.resetQ.normalize();
  39651. if (isLandscapeMode()) {
  39652. this.resetQ.multiply(this.inverseWorldToScreenQ);
  39653. }
  39654. this.resetQ.multiply(this.originalPoseAdjustQ);
  39655. };
  39656. FusionPoseSensor.prototype.onDeviceOrientation_ = function (e) {
  39657. this._deviceOrientationQ = this._deviceOrientationQ || new Quaternion();
  39658. var alpha = e.alpha,
  39659. beta = e.beta,
  39660. gamma = e.gamma;
  39661. alpha = (alpha || 0) * Math.PI / 180;
  39662. beta = (beta || 0) * Math.PI / 180;
  39663. gamma = (gamma || 0) * Math.PI / 180;
  39664. this._deviceOrientationQ.setFromEulerYXZ(beta, alpha, -gamma);
  39665. };
  39666. FusionPoseSensor.prototype.onDeviceMotion_ = function (deviceMotion) {
  39667. this.updateDeviceMotion_(deviceMotion);
  39668. };
  39669. FusionPoseSensor.prototype.updateDeviceMotion_ = function (deviceMotion) {
  39670. var accGravity = deviceMotion.accelerationIncludingGravity;
  39671. var rotRate = deviceMotion.rotationRate;
  39672. var timestampS = deviceMotion.timeStamp / 1000;
  39673. var deltaS = timestampS - this.previousTimestampS;
  39674. if (deltaS < 0) {
  39675. warnOnce('fusion-pose-sensor:invalid:non-monotonic', 'Invalid timestamps detected: non-monotonic timestamp from devicemotion');
  39676. this.previousTimestampS = timestampS;
  39677. return;
  39678. } else if (deltaS <= MIN_TIMESTEP || deltaS > MAX_TIMESTEP) {
  39679. warnOnce('fusion-pose-sensor:invalid:outside-threshold', 'Invalid timestamps detected: Timestamp from devicemotion outside expected range.');
  39680. this.previousTimestampS = timestampS;
  39681. return;
  39682. }
  39683. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  39684. if (isR7()) {
  39685. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  39686. } else {
  39687. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  39688. }
  39689. if (!this.isDeviceMotionInRadians) {
  39690. this.gyroscope.multiplyScalar(Math.PI / 180);
  39691. }
  39692. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  39693. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  39694. this.previousTimestampS = timestampS;
  39695. };
  39696. FusionPoseSensor.prototype.onOrientationChange_ = function (screenOrientation) {
  39697. this.setScreenTransform_();
  39698. };
  39699. FusionPoseSensor.prototype.onMessage_ = function (event) {
  39700. var message = event.data;
  39701. if (!message || !message.type) {
  39702. return;
  39703. }
  39704. var type = message.type.toLowerCase();
  39705. if (type !== 'devicemotion') {
  39706. return;
  39707. }
  39708. this.updateDeviceMotion_(message.deviceMotionEvent);
  39709. };
  39710. FusionPoseSensor.prototype.setScreenTransform_ = function () {
  39711. this.worldToScreenQ.set(0, 0, 0, 1);
  39712. switch (window.orientation) {
  39713. case 0:
  39714. break;
  39715. case 90:
  39716. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), -Math.PI / 2);
  39717. break;
  39718. case -90:
  39719. this.worldToScreenQ.setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2);
  39720. break;
  39721. case 180:
  39722. break;
  39723. }
  39724. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  39725. this.inverseWorldToScreenQ.inverse();
  39726. };
  39727. FusionPoseSensor.prototype.start = function () {
  39728. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  39729. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  39730. this.onMessageCallback_ = this.onMessage_.bind(this);
  39731. this.onDeviceOrientationCallback_ = this.onDeviceOrientation_.bind(this);
  39732. if (isIOS() && isInsideCrossOriginIFrame()) {
  39733. window.addEventListener('message', this.onMessageCallback_);
  39734. }
  39735. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  39736. if (this.isWithoutDeviceMotion) {
  39737. window.addEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39738. } else {
  39739. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  39740. }
  39741. };
  39742. FusionPoseSensor.prototype.stop = function () {
  39743. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  39744. window.removeEventListener('deviceorientation', this.onDeviceOrientationCallback_);
  39745. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  39746. window.removeEventListener('message', this.onMessageCallback_);
  39747. };
  39748. var SENSOR_FREQUENCY = 60;
  39749. var X_AXIS = new Vector3(1, 0, 0);
  39750. var Z_AXIS = new Vector3(0, 0, 1);
  39751. var SENSOR_TO_VR = new Quaternion();
  39752. SENSOR_TO_VR.setFromAxisAngle(X_AXIS, -Math.PI / 2);
  39753. SENSOR_TO_VR.multiply(new Quaternion().setFromAxisAngle(Z_AXIS, Math.PI / 2));
  39754. var PoseSensor = function () {
  39755. function PoseSensor(config) {
  39756. classCallCheck(this, PoseSensor);
  39757. this.config = config;
  39758. this.sensor = null;
  39759. this.fusionSensor = null;
  39760. this._out = new Float32Array(4);
  39761. this.api = null;
  39762. this.errors = [];
  39763. this._sensorQ = new Quaternion();
  39764. this._outQ = new Quaternion();
  39765. this._onSensorRead = this._onSensorRead.bind(this);
  39766. this._onSensorError = this._onSensorError.bind(this);
  39767. this.init();
  39768. }
  39769. createClass(PoseSensor, [{
  39770. key: 'init',
  39771. value: function init() {
  39772. var sensor = null;
  39773. try {
  39774. sensor = new RelativeOrientationSensor({
  39775. frequency: SENSOR_FREQUENCY,
  39776. referenceFrame: 'screen'
  39777. });
  39778. sensor.addEventListener('error', this._onSensorError);
  39779. } catch (error) {
  39780. this.errors.push(error);
  39781. if (error.name === 'SecurityError') {
  39782. console.error('Cannot construct sensors due to the Feature Policy');
  39783. console.warn('Attempting to fall back using "devicemotion"; however this will ' + 'fail in the future without correct permissions.');
  39784. this.useDeviceMotion();
  39785. } else if (error.name === 'ReferenceError') {
  39786. this.useDeviceMotion();
  39787. } else {
  39788. console.error(error);
  39789. }
  39790. }
  39791. if (sensor) {
  39792. this.api = 'sensor';
  39793. this.sensor = sensor;
  39794. this.sensor.addEventListener('reading', this._onSensorRead);
  39795. this.sensor.start();
  39796. }
  39797. }
  39798. }, {
  39799. key: 'useDeviceMotion',
  39800. value: function useDeviceMotion() {
  39801. this.api = 'devicemotion';
  39802. this.fusionSensor = new FusionPoseSensor(this.config.K_FILTER, this.config.PREDICTION_TIME_S, this.config.YAW_ONLY, this.config.DEBUG);
  39803. if (this.sensor) {
  39804. this.sensor.removeEventListener('reading', this._onSensorRead);
  39805. this.sensor.removeEventListener('error', this._onSensorError);
  39806. this.sensor = null;
  39807. }
  39808. }
  39809. }, {
  39810. key: 'getOrientation',
  39811. value: function getOrientation() {
  39812. if (this.fusionSensor) {
  39813. return this.fusionSensor.getOrientation();
  39814. }
  39815. if (!this.sensor || !this.sensor.quaternion) {
  39816. this._out[0] = this._out[1] = this._out[2] = 0;
  39817. this._out[3] = 1;
  39818. return this._out;
  39819. }
  39820. var q = this.sensor.quaternion;
  39821. this._sensorQ.set(q[0], q[1], q[2], q[3]);
  39822. var out = this._outQ;
  39823. out.copy(SENSOR_TO_VR);
  39824. out.multiply(this._sensorQ);
  39825. if (this.config.YAW_ONLY) {
  39826. out.x = out.z = 0;
  39827. out.normalize();
  39828. }
  39829. this._out[0] = out.x;
  39830. this._out[1] = out.y;
  39831. this._out[2] = out.z;
  39832. this._out[3] = out.w;
  39833. return this._out;
  39834. }
  39835. }, {
  39836. key: '_onSensorError',
  39837. value: function _onSensorError(event) {
  39838. this.errors.push(event.error);
  39839. if (event.error.name === 'NotAllowedError') {
  39840. console.error('Permission to access sensor was denied');
  39841. } else if (event.error.name === 'NotReadableError') {
  39842. console.error('Sensor could not be read');
  39843. } else {
  39844. console.error(event.error);
  39845. }
  39846. this.useDeviceMotion();
  39847. }
  39848. }, {
  39849. key: '_onSensorRead',
  39850. value: function _onSensorRead() {}
  39851. }]);
  39852. return PoseSensor;
  39853. }();
  39854. 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>";
  39855. function RotateInstructions() {
  39856. this.loadIcon_();
  39857. var overlay = document.createElement('div');
  39858. var s = overlay.style;
  39859. s.position = 'fixed';
  39860. s.top = 0;
  39861. s.right = 0;
  39862. s.bottom = 0;
  39863. s.left = 0;
  39864. s.backgroundColor = 'gray';
  39865. s.fontFamily = 'sans-serif';
  39866. s.zIndex = 1000000;
  39867. var img = document.createElement('img');
  39868. img.src = this.icon;
  39869. var s = img.style;
  39870. s.marginLeft = '25%';
  39871. s.marginTop = '25%';
  39872. s.width = '50%';
  39873. overlay.appendChild(img);
  39874. var text = document.createElement('div');
  39875. var s = text.style;
  39876. s.textAlign = 'center';
  39877. s.fontSize = '16px';
  39878. s.lineHeight = '24px';
  39879. s.margin = '24px 25%';
  39880. s.width = '50%';
  39881. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  39882. overlay.appendChild(text);
  39883. var snackbar = document.createElement('div');
  39884. var s = snackbar.style;
  39885. s.backgroundColor = '#CFD8DC';
  39886. s.position = 'fixed';
  39887. s.bottom = 0;
  39888. s.width = '100%';
  39889. s.height = '48px';
  39890. s.padding = '14px 24px';
  39891. s.boxSizing = 'border-box';
  39892. s.color = '#656A6B';
  39893. overlay.appendChild(snackbar);
  39894. var snackbarText = document.createElement('div');
  39895. snackbarText.style.float = 'left';
  39896. snackbarText.innerHTML = 'No Cardboard viewer?';
  39897. var snackbarButton = document.createElement('a');
  39898. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  39899. snackbarButton.innerHTML = 'get one';
  39900. snackbarButton.target = '_blank';
  39901. var s = snackbarButton.style;
  39902. s.float = 'right';
  39903. s.fontWeight = 600;
  39904. s.textTransform = 'uppercase';
  39905. s.borderLeft = '1px solid gray';
  39906. s.paddingLeft = '24px';
  39907. s.textDecoration = 'none';
  39908. s.color = '#656A6B';
  39909. snackbar.appendChild(snackbarText);
  39910. snackbar.appendChild(snackbarButton);
  39911. this.overlay = overlay;
  39912. this.text = text;
  39913. this.hide();
  39914. }
  39915. RotateInstructions.prototype.show = function (parent) {
  39916. if (!parent && !this.overlay.parentElement) {
  39917. document.body.appendChild(this.overlay);
  39918. } else if (parent) {
  39919. if (this.overlay.parentElement && this.overlay.parentElement != parent) this.overlay.parentElement.removeChild(this.overlay);
  39920. parent.appendChild(this.overlay);
  39921. }
  39922. this.overlay.style.display = 'block';
  39923. var img = this.overlay.querySelector('img');
  39924. var s = img.style;
  39925. if (isLandscapeMode()) {
  39926. s.width = '20%';
  39927. s.marginLeft = '40%';
  39928. s.marginTop = '3%';
  39929. } else {
  39930. s.width = '50%';
  39931. s.marginLeft = '25%';
  39932. s.marginTop = '25%';
  39933. }
  39934. };
  39935. RotateInstructions.prototype.hide = function () {
  39936. this.overlay.style.display = 'none';
  39937. };
  39938. RotateInstructions.prototype.showTemporarily = function (ms, parent) {
  39939. this.show(parent);
  39940. this.timer = setTimeout(this.hide.bind(this), ms);
  39941. };
  39942. RotateInstructions.prototype.disableShowTemporarily = function () {
  39943. clearTimeout(this.timer);
  39944. };
  39945. RotateInstructions.prototype.update = function () {
  39946. this.disableShowTemporarily();
  39947. if (!isLandscapeMode() && isMobile()) {
  39948. this.show();
  39949. } else {
  39950. this.hide();
  39951. }
  39952. };
  39953. RotateInstructions.prototype.loadIcon_ = function () {
  39954. this.icon = dataUri('image/svg+xml', rotateInstructionsAsset);
  39955. };
  39956. var DEFAULT_VIEWER = 'CardboardV1';
  39957. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  39958. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  39959. function ViewerSelector(defaultViewer) {
  39960. try {
  39961. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  39962. } catch (error) {
  39963. console.error('Failed to load viewer profile: %s', error);
  39964. }
  39965. if (!this.selectedKey) {
  39966. this.selectedKey = defaultViewer || DEFAULT_VIEWER;
  39967. }
  39968. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  39969. this.root = null;
  39970. this.onChangeCallbacks_ = [];
  39971. }
  39972. ViewerSelector.prototype.show = function (root) {
  39973. this.root = root;
  39974. root.appendChild(this.dialog);
  39975. var selected = this.dialog.querySelector('#' + this.selectedKey);
  39976. selected.checked = true;
  39977. this.dialog.style.display = 'block';
  39978. };
  39979. ViewerSelector.prototype.hide = function () {
  39980. if (this.root && this.root.contains(this.dialog)) {
  39981. this.root.removeChild(this.dialog);
  39982. }
  39983. this.dialog.style.display = 'none';
  39984. };
  39985. ViewerSelector.prototype.getCurrentViewer = function () {
  39986. return DeviceInfo.Viewers[this.selectedKey];
  39987. };
  39988. ViewerSelector.prototype.getSelectedKey_ = function () {
  39989. var input = this.dialog.querySelector('input[name=field]:checked');
  39990. if (input) {
  39991. return input.id;
  39992. }
  39993. return null;
  39994. };
  39995. ViewerSelector.prototype.onChange = function (cb) {
  39996. this.onChangeCallbacks_.push(cb);
  39997. };
  39998. ViewerSelector.prototype.fireOnChange_ = function (viewer) {
  39999. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  40000. this.onChangeCallbacks_[i](viewer);
  40001. }
  40002. };
  40003. ViewerSelector.prototype.onSave_ = function () {
  40004. this.selectedKey = this.getSelectedKey_();
  40005. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  40006. console.error('ViewerSelector.onSave_: this should never happen!');
  40007. return;
  40008. }
  40009. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  40010. try {
  40011. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  40012. } catch (error) {
  40013. console.error('Failed to save viewer profile: %s', error);
  40014. }
  40015. this.hide();
  40016. };
  40017. ViewerSelector.prototype.createDialog_ = function (options) {
  40018. var container = document.createElement('div');
  40019. container.classList.add(CLASS_NAME);
  40020. container.style.display = 'none';
  40021. var overlay = document.createElement('div');
  40022. var s = overlay.style;
  40023. s.position = 'fixed';
  40024. s.left = 0;
  40025. s.top = 0;
  40026. s.width = '100%';
  40027. s.height = '100%';
  40028. s.background = 'rgba(0, 0, 0, 0.3)';
  40029. overlay.addEventListener('click', this.hide.bind(this));
  40030. var width = 280;
  40031. var dialog = document.createElement('div');
  40032. var s = dialog.style;
  40033. s.boxSizing = 'border-box';
  40034. s.position = 'fixed';
  40035. s.top = '24px';
  40036. s.left = '50%';
  40037. s.marginLeft = -width / 2 + 'px';
  40038. s.width = width + 'px';
  40039. s.padding = '24px';
  40040. s.overflow = 'hidden';
  40041. s.background = '#fafafa';
  40042. s.fontFamily = "'Roboto', sans-serif";
  40043. s.boxShadow = '0px 5px 20px #666';
  40044. dialog.appendChild(this.createH1_('Select your viewer'));
  40045. for (var id in options) {
  40046. dialog.appendChild(this.createChoice_(id, options[id].label));
  40047. }
  40048. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  40049. container.appendChild(overlay);
  40050. container.appendChild(dialog);
  40051. return container;
  40052. };
  40053. ViewerSelector.prototype.createH1_ = function (name) {
  40054. var h1 = document.createElement('h1');
  40055. var s = h1.style;
  40056. s.color = 'black';
  40057. s.fontSize = '20px';
  40058. s.fontWeight = 'bold';
  40059. s.marginTop = 0;
  40060. s.marginBottom = '24px';
  40061. h1.innerHTML = name;
  40062. return h1;
  40063. };
  40064. ViewerSelector.prototype.createChoice_ = function (id, name) {
  40065. var div = document.createElement('div');
  40066. div.style.marginTop = '8px';
  40067. div.style.color = 'black';
  40068. var input = document.createElement('input');
  40069. input.style.fontSize = '30px';
  40070. input.setAttribute('id', id);
  40071. input.setAttribute('type', 'radio');
  40072. input.setAttribute('value', id);
  40073. input.setAttribute('name', 'field');
  40074. var label = document.createElement('label');
  40075. label.style.marginLeft = '4px';
  40076. label.setAttribute('for', id);
  40077. label.innerHTML = name;
  40078. div.appendChild(input);
  40079. div.appendChild(label);
  40080. return div;
  40081. };
  40082. ViewerSelector.prototype.createButton_ = function (label, onclick) {
  40083. var button = document.createElement('button');
  40084. button.innerHTML = label;
  40085. var s = button.style;
  40086. s.float = 'right';
  40087. s.textTransform = 'uppercase';
  40088. s.color = '#1094f7';
  40089. s.fontSize = '14px';
  40090. s.letterSpacing = 0;
  40091. s.border = 0;
  40092. s.background = 'none';
  40093. s.marginTop = '16px';
  40094. button.addEventListener('click', onclick);
  40095. return button;
  40096. };
  40097. var commonjsGlobal$$1 = typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof self !== 'undefined' ? self : {};
  40098. function unwrapExports$$1 (x) {
  40099. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  40100. }
  40101. function createCommonjsModule$$1(fn, module) {
  40102. return module = { exports: {} }, fn(module, module.exports), module.exports;
  40103. }
  40104. var NoSleep = createCommonjsModule$$1(function (module, exports) {
  40105. (function webpackUniversalModuleDefinition(root, factory) {
  40106. module.exports = factory();
  40107. })(commonjsGlobal$$1, function() {
  40108. return (function(modules) {
  40109. var installedModules = {};
  40110. function __webpack_require__(moduleId) {
  40111. if(installedModules[moduleId]) {
  40112. return installedModules[moduleId].exports;
  40113. }
  40114. var module = installedModules[moduleId] = {
  40115. i: moduleId,
  40116. l: false,
  40117. exports: {}
  40118. };
  40119. modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  40120. module.l = true;
  40121. return module.exports;
  40122. }
  40123. __webpack_require__.m = modules;
  40124. __webpack_require__.c = installedModules;
  40125. __webpack_require__.d = function(exports, name, getter) {
  40126. if(!__webpack_require__.o(exports, name)) {
  40127. Object.defineProperty(exports, name, {
  40128. configurable: false,
  40129. enumerable: true,
  40130. get: getter
  40131. });
  40132. }
  40133. };
  40134. __webpack_require__.n = function(module) {
  40135. var getter = module && module.__esModule ?
  40136. function getDefault() { return module['default']; } :
  40137. function getModuleExports() { return module; };
  40138. __webpack_require__.d(getter, 'a', getter);
  40139. return getter;
  40140. };
  40141. __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  40142. __webpack_require__.p = "";
  40143. return __webpack_require__(__webpack_require__.s = 0);
  40144. })
  40145. ([
  40146. (function(module, exports, __webpack_require__) {
  40147. 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; }; }();
  40148. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  40149. var mediaFile = __webpack_require__(1);
  40150. 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;
  40151. var NoSleep = function () {
  40152. function NoSleep() {
  40153. _classCallCheck(this, NoSleep);
  40154. if (oldIOS) {
  40155. this.noSleepTimer = null;
  40156. } else {
  40157. this.noSleepVideo = document.createElement('video');
  40158. this.noSleepVideo.setAttribute('playsinline', '');
  40159. this.noSleepVideo.setAttribute('src', mediaFile);
  40160. this.noSleepVideo.addEventListener('timeupdate', function (e) {
  40161. if (this.noSleepVideo.currentTime > 0.5) {
  40162. this.noSleepVideo.currentTime = Math.random();
  40163. }
  40164. }.bind(this));
  40165. }
  40166. }
  40167. _createClass(NoSleep, [{
  40168. key: 'enable',
  40169. value: function enable() {
  40170. if (oldIOS) {
  40171. this.disable();
  40172. this.noSleepTimer = window.setInterval(function () {
  40173. window.location.href = '/';
  40174. window.setTimeout(window.stop, 0);
  40175. }, 15000);
  40176. } else {
  40177. this.noSleepVideo.play();
  40178. }
  40179. }
  40180. }, {
  40181. key: 'disable',
  40182. value: function disable() {
  40183. if (oldIOS) {
  40184. if (this.noSleepTimer) {
  40185. window.clearInterval(this.noSleepTimer);
  40186. this.noSleepTimer = null;
  40187. }
  40188. } else {
  40189. this.noSleepVideo.pause();
  40190. }
  40191. }
  40192. }]);
  40193. return NoSleep;
  40194. }();
  40195. module.exports = NoSleep;
  40196. }),
  40197. (function(module, exports, __webpack_require__) {
  40198. 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=';
  40199. })
  40200. ]);
  40201. });
  40202. });
  40203. var NoSleep$1 = unwrapExports$$1(NoSleep);
  40204. var nextDisplayId = 1000;
  40205. var defaultLeftBounds = [0, 0, 0.5, 1];
  40206. var defaultRightBounds = [0.5, 0, 0.5, 1];
  40207. var raf = window.requestAnimationFrame;
  40208. var caf = window.cancelAnimationFrame;
  40209. function VRFrameData() {
  40210. this.leftProjectionMatrix = new Float32Array(16);
  40211. this.leftViewMatrix = new Float32Array(16);
  40212. this.rightProjectionMatrix = new Float32Array(16);
  40213. this.rightViewMatrix = new Float32Array(16);
  40214. this.pose = null;
  40215. }
  40216. function VRDisplayCapabilities(config) {
  40217. Object.defineProperties(this, {
  40218. hasPosition: {
  40219. writable: false, enumerable: true, value: config.hasPosition
  40220. },
  40221. hasExternalDisplay: {
  40222. writable: false, enumerable: true, value: config.hasExternalDisplay
  40223. },
  40224. canPresent: {
  40225. writable: false, enumerable: true, value: config.canPresent
  40226. },
  40227. maxLayers: {
  40228. writable: false, enumerable: true, value: config.maxLayers
  40229. },
  40230. hasOrientation: {
  40231. enumerable: true, get: function get() {
  40232. deprecateWarning('VRDisplayCapabilities.prototype.hasOrientation', 'VRDisplay.prototype.getFrameData');
  40233. return config.hasOrientation;
  40234. }
  40235. }
  40236. });
  40237. }
  40238. function VRDisplay(config) {
  40239. config = config || {};
  40240. var USE_WAKELOCK = 'wakelock' in config ? config.wakelock : true;
  40241. this.isPolyfilled = true;
  40242. this.displayId = nextDisplayId++;
  40243. this.displayName = '';
  40244. this.depthNear = 0.01;
  40245. this.depthFar = 10000.0;
  40246. this.isPresenting = false;
  40247. Object.defineProperty(this, 'isConnected', {
  40248. get: function get() {
  40249. deprecateWarning('VRDisplay.prototype.isConnected', 'VRDisplayCapabilities.prototype.hasExternalDisplay');
  40250. return false;
  40251. }
  40252. });
  40253. this.capabilities = new VRDisplayCapabilities({
  40254. hasPosition: false,
  40255. hasOrientation: false,
  40256. hasExternalDisplay: false,
  40257. canPresent: false,
  40258. maxLayers: 1
  40259. });
  40260. this.stageParameters = null;
  40261. this.waitingForPresent_ = false;
  40262. this.layer_ = null;
  40263. this.originalParent_ = null;
  40264. this.fullscreenElement_ = null;
  40265. this.fullscreenWrapper_ = null;
  40266. this.fullscreenElementCachedStyle_ = null;
  40267. this.fullscreenEventTarget_ = null;
  40268. this.fullscreenChangeHandler_ = null;
  40269. this.fullscreenErrorHandler_ = null;
  40270. if (USE_WAKELOCK && isMobile()) {
  40271. this.wakelock_ = new NoSleep$1();
  40272. }
  40273. }
  40274. VRDisplay.prototype.getFrameData = function (frameData) {
  40275. return frameDataFromPose(frameData, this._getPose(), this);
  40276. };
  40277. VRDisplay.prototype.getPose = function () {
  40278. deprecateWarning('VRDisplay.prototype.getPose', 'VRDisplay.prototype.getFrameData');
  40279. return this._getPose();
  40280. };
  40281. VRDisplay.prototype.resetPose = function () {
  40282. deprecateWarning('VRDisplay.prototype.resetPose');
  40283. return this._resetPose();
  40284. };
  40285. VRDisplay.prototype.getImmediatePose = function () {
  40286. deprecateWarning('VRDisplay.prototype.getImmediatePose', 'VRDisplay.prototype.getFrameData');
  40287. return this._getPose();
  40288. };
  40289. VRDisplay.prototype.requestAnimationFrame = function (callback) {
  40290. return raf(callback);
  40291. };
  40292. VRDisplay.prototype.cancelAnimationFrame = function (id) {
  40293. return caf(id);
  40294. };
  40295. VRDisplay.prototype.wrapForFullscreen = function (element) {
  40296. if (isIOS()) {
  40297. return element;
  40298. }
  40299. if (!this.fullscreenWrapper_) {
  40300. this.fullscreenWrapper_ = document.createElement('div');
  40301. 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'];
  40302. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  40303. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  40304. }
  40305. if (this.fullscreenElement_ == element) {
  40306. return this.fullscreenWrapper_;
  40307. }
  40308. if (this.fullscreenElement_) {
  40309. if (this.originalParent_) {
  40310. this.originalParent_.appendChild(this.fullscreenElement_);
  40311. } else {
  40312. this.fullscreenElement_.parentElement.removeChild(this.fullscreenElement_);
  40313. }
  40314. }
  40315. this.fullscreenElement_ = element;
  40316. this.originalParent_ = element.parentElement;
  40317. if (!this.originalParent_) {
  40318. document.body.appendChild(element);
  40319. }
  40320. if (!this.fullscreenWrapper_.parentElement) {
  40321. var parent = this.fullscreenElement_.parentElement;
  40322. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  40323. parent.removeChild(this.fullscreenElement_);
  40324. }
  40325. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  40326. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  40327. var self = this;
  40328. function applyFullscreenElementStyle() {
  40329. if (!self.fullscreenElement_) {
  40330. return;
  40331. }
  40332. 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'];
  40333. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  40334. }
  40335. applyFullscreenElementStyle();
  40336. return this.fullscreenWrapper_;
  40337. };
  40338. VRDisplay.prototype.removeFullscreenWrapper = function () {
  40339. if (!this.fullscreenElement_) {
  40340. return;
  40341. }
  40342. var element = this.fullscreenElement_;
  40343. if (this.fullscreenElementCachedStyle_) {
  40344. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  40345. } else {
  40346. element.removeAttribute('style');
  40347. }
  40348. this.fullscreenElement_ = null;
  40349. this.fullscreenElementCachedStyle_ = null;
  40350. var parent = this.fullscreenWrapper_.parentElement;
  40351. this.fullscreenWrapper_.removeChild(element);
  40352. if (this.originalParent_ === parent) {
  40353. parent.insertBefore(element, this.fullscreenWrapper_);
  40354. }
  40355. else if (this.originalParent_) {
  40356. this.originalParent_.appendChild(element);
  40357. }
  40358. parent.removeChild(this.fullscreenWrapper_);
  40359. return element;
  40360. };
  40361. VRDisplay.prototype.requestPresent = function (layers) {
  40362. var wasPresenting = this.isPresenting;
  40363. var self = this;
  40364. if (!(layers instanceof Array)) {
  40365. deprecateWarning('VRDisplay.prototype.requestPresent with non-array argument', 'an array of VRLayers as the first argument');
  40366. layers = [layers];
  40367. }
  40368. return new Promise(function (resolve, reject) {
  40369. if (!self.capabilities.canPresent) {
  40370. reject(new Error('VRDisplay is not capable of presenting.'));
  40371. return;
  40372. }
  40373. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  40374. reject(new Error('Invalid number of layers.'));
  40375. return;
  40376. }
  40377. var incomingLayer = layers[0];
  40378. if (!incomingLayer.source) {
  40379. resolve();
  40380. return;
  40381. }
  40382. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  40383. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  40384. if (wasPresenting) {
  40385. var layer = self.layer_;
  40386. if (layer.source !== incomingLayer.source) {
  40387. layer.source = incomingLayer.source;
  40388. }
  40389. for (var i = 0; i < 4; i++) {
  40390. layer.leftBounds[i] = leftBounds[i];
  40391. layer.rightBounds[i] = rightBounds[i];
  40392. }
  40393. self.wrapForFullscreen(self.layer_.source);
  40394. self.updatePresent_();
  40395. resolve();
  40396. return;
  40397. }
  40398. self.layer_ = {
  40399. predistorted: incomingLayer.predistorted,
  40400. source: incomingLayer.source,
  40401. leftBounds: leftBounds.slice(0),
  40402. rightBounds: rightBounds.slice(0)
  40403. };
  40404. self.waitingForPresent_ = false;
  40405. if (self.layer_ && self.layer_.source) {
  40406. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  40407. var onFullscreenChange = function onFullscreenChange() {
  40408. var actualFullscreenElement = getFullscreenElement();
  40409. self.isPresenting = fullscreenElement === actualFullscreenElement;
  40410. if (self.isPresenting) {
  40411. if (screen.orientation && screen.orientation.lock) {
  40412. screen.orientation.lock('landscape-primary').catch(function (error) {
  40413. console.error('screen.orientation.lock() failed due to', error.message);
  40414. });
  40415. }
  40416. self.waitingForPresent_ = false;
  40417. self.beginPresent_();
  40418. resolve();
  40419. } else {
  40420. if (screen.orientation && screen.orientation.unlock) {
  40421. screen.orientation.unlock();
  40422. }
  40423. self.removeFullscreenWrapper();
  40424. self.disableWakeLock();
  40425. self.endPresent_();
  40426. self.removeFullscreenListeners_();
  40427. }
  40428. self.fireVRDisplayPresentChange_();
  40429. };
  40430. var onFullscreenError = function onFullscreenError() {
  40431. if (!self.waitingForPresent_) {
  40432. return;
  40433. }
  40434. self.removeFullscreenWrapper();
  40435. self.removeFullscreenListeners_();
  40436. self.disableWakeLock();
  40437. self.waitingForPresent_ = false;
  40438. self.isPresenting = false;
  40439. reject(new Error('Unable to present.'));
  40440. };
  40441. self.addFullscreenListeners_(fullscreenElement, onFullscreenChange, onFullscreenError);
  40442. if (requestFullscreen(fullscreenElement)) {
  40443. self.enableWakeLock();
  40444. self.waitingForPresent_ = true;
  40445. } else if (isIOS() || isWebViewAndroid()) {
  40446. self.enableWakeLock();
  40447. self.isPresenting = true;
  40448. self.beginPresent_();
  40449. self.fireVRDisplayPresentChange_();
  40450. resolve();
  40451. }
  40452. }
  40453. if (!self.waitingForPresent_ && !isIOS()) {
  40454. exitFullscreen();
  40455. reject(new Error('Unable to present.'));
  40456. }
  40457. });
  40458. };
  40459. VRDisplay.prototype.exitPresent = function () {
  40460. var wasPresenting = this.isPresenting;
  40461. var self = this;
  40462. this.isPresenting = false;
  40463. this.layer_ = null;
  40464. this.disableWakeLock();
  40465. return new Promise(function (resolve, reject) {
  40466. if (wasPresenting) {
  40467. if (!exitFullscreen() && isIOS()) {
  40468. self.endPresent_();
  40469. self.fireVRDisplayPresentChange_();
  40470. }
  40471. if (isWebViewAndroid()) {
  40472. self.removeFullscreenWrapper();
  40473. self.removeFullscreenListeners_();
  40474. self.endPresent_();
  40475. self.fireVRDisplayPresentChange_();
  40476. }
  40477. resolve();
  40478. } else {
  40479. reject(new Error('Was not presenting to VRDisplay.'));
  40480. }
  40481. });
  40482. };
  40483. VRDisplay.prototype.getLayers = function () {
  40484. if (this.layer_) {
  40485. return [this.layer_];
  40486. }
  40487. return [];
  40488. };
  40489. VRDisplay.prototype.fireVRDisplayPresentChange_ = function () {
  40490. var event = new CustomEvent('vrdisplaypresentchange', { detail: { display: this } });
  40491. window.dispatchEvent(event);
  40492. };
  40493. VRDisplay.prototype.fireVRDisplayConnect_ = function () {
  40494. var event = new CustomEvent('vrdisplayconnect', { detail: { display: this } });
  40495. window.dispatchEvent(event);
  40496. };
  40497. VRDisplay.prototype.addFullscreenListeners_ = function (element, changeHandler, errorHandler) {
  40498. this.removeFullscreenListeners_();
  40499. this.fullscreenEventTarget_ = element;
  40500. this.fullscreenChangeHandler_ = changeHandler;
  40501. this.fullscreenErrorHandler_ = errorHandler;
  40502. if (changeHandler) {
  40503. if (document.fullscreenEnabled) {
  40504. element.addEventListener('fullscreenchange', changeHandler, false);
  40505. } else if (document.webkitFullscreenEnabled) {
  40506. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  40507. } else if (document.mozFullScreenEnabled) {
  40508. document.addEventListener('mozfullscreenchange', changeHandler, false);
  40509. } else if (document.msFullscreenEnabled) {
  40510. element.addEventListener('msfullscreenchange', changeHandler, false);
  40511. }
  40512. }
  40513. if (errorHandler) {
  40514. if (document.fullscreenEnabled) {
  40515. element.addEventListener('fullscreenerror', errorHandler, false);
  40516. } else if (document.webkitFullscreenEnabled) {
  40517. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  40518. } else if (document.mozFullScreenEnabled) {
  40519. document.addEventListener('mozfullscreenerror', errorHandler, false);
  40520. } else if (document.msFullscreenEnabled) {
  40521. element.addEventListener('msfullscreenerror', errorHandler, false);
  40522. }
  40523. }
  40524. };
  40525. VRDisplay.prototype.removeFullscreenListeners_ = function () {
  40526. if (!this.fullscreenEventTarget_) return;
  40527. var element = this.fullscreenEventTarget_;
  40528. if (this.fullscreenChangeHandler_) {
  40529. var changeHandler = this.fullscreenChangeHandler_;
  40530. element.removeEventListener('fullscreenchange', changeHandler, false);
  40531. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  40532. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  40533. element.removeEventListener('msfullscreenchange', changeHandler, false);
  40534. }
  40535. if (this.fullscreenErrorHandler_) {
  40536. var errorHandler = this.fullscreenErrorHandler_;
  40537. element.removeEventListener('fullscreenerror', errorHandler, false);
  40538. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  40539. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  40540. element.removeEventListener('msfullscreenerror', errorHandler, false);
  40541. }
  40542. this.fullscreenEventTarget_ = null;
  40543. this.fullscreenChangeHandler_ = null;
  40544. this.fullscreenErrorHandler_ = null;
  40545. };
  40546. VRDisplay.prototype.enableWakeLock = function () {
  40547. if (this.wakelock_) {
  40548. this.wakelock_.enable();
  40549. }
  40550. };
  40551. VRDisplay.prototype.disableWakeLock = function () {
  40552. if (this.wakelock_) {
  40553. this.wakelock_.disable();
  40554. }
  40555. };
  40556. VRDisplay.prototype.beginPresent_ = function () {
  40557. };
  40558. VRDisplay.prototype.endPresent_ = function () {
  40559. };
  40560. VRDisplay.prototype.submitFrame = function (pose) {
  40561. };
  40562. VRDisplay.prototype.getEyeParameters = function (whichEye) {
  40563. return null;
  40564. };
  40565. var config = {
  40566. ADDITIONAL_VIEWERS: [],
  40567. DEFAULT_VIEWER: '',
  40568. MOBILE_WAKE_LOCK: true,
  40569. DEBUG: false,
  40570. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40571. K_FILTER: 0.98,
  40572. PREDICTION_TIME_S: 0.040,
  40573. CARDBOARD_UI_DISABLED: false,
  40574. ROTATE_INSTRUCTIONS_DISABLED: false,
  40575. YAW_ONLY: false,
  40576. BUFFER_SCALE: 0.5,
  40577. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40578. };
  40579. var Eye = {
  40580. LEFT: 'left',
  40581. RIGHT: 'right'
  40582. };
  40583. function CardboardVRDisplay(config$$1) {
  40584. var defaults = extend({}, config);
  40585. config$$1 = extend(defaults, config$$1 || {});
  40586. VRDisplay.call(this, {
  40587. wakelock: config$$1.MOBILE_WAKE_LOCK
  40588. });
  40589. this.config = config$$1;
  40590. this.displayName = 'Cardboard VRDisplay';
  40591. this.capabilities = new VRDisplayCapabilities({
  40592. hasPosition: false,
  40593. hasOrientation: true,
  40594. hasExternalDisplay: false,
  40595. canPresent: true,
  40596. maxLayers: 1
  40597. });
  40598. this.stageParameters = null;
  40599. this.bufferScale_ = this.config.BUFFER_SCALE;
  40600. this.poseSensor_ = new PoseSensor(this.config);
  40601. this.distorter_ = null;
  40602. this.cardboardUI_ = null;
  40603. this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this));
  40604. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config$$1.ADDITIONAL_VIEWERS);
  40605. this.viewerSelector_ = new ViewerSelector(config$$1.DEFAULT_VIEWER);
  40606. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  40607. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  40608. if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) {
  40609. this.rotateInstructions_ = new RotateInstructions();
  40610. }
  40611. if (isIOS()) {
  40612. window.addEventListener('resize', this.onResize_.bind(this));
  40613. }
  40614. }
  40615. CardboardVRDisplay.prototype = Object.create(VRDisplay.prototype);
  40616. CardboardVRDisplay.prototype._getPose = function () {
  40617. return {
  40618. position: null,
  40619. orientation: this.poseSensor_.getOrientation(),
  40620. linearVelocity: null,
  40621. linearAcceleration: null,
  40622. angularVelocity: null,
  40623. angularAcceleration: null
  40624. };
  40625. };
  40626. CardboardVRDisplay.prototype._resetPose = function () {
  40627. if (this.poseSensor_.resetPose) {
  40628. this.poseSensor_.resetPose();
  40629. }
  40630. };
  40631. CardboardVRDisplay.prototype._getFieldOfView = function (whichEye) {
  40632. var fieldOfView;
  40633. if (whichEye == Eye.LEFT) {
  40634. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  40635. } else if (whichEye == Eye.RIGHT) {
  40636. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  40637. } else {
  40638. console.error('Invalid eye provided: %s', whichEye);
  40639. return null;
  40640. }
  40641. return fieldOfView;
  40642. };
  40643. CardboardVRDisplay.prototype._getEyeOffset = function (whichEye) {
  40644. var offset;
  40645. if (whichEye == Eye.LEFT) {
  40646. offset = [-this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40647. } else if (whichEye == Eye.RIGHT) {
  40648. offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  40649. } else {
  40650. console.error('Invalid eye provided: %s', whichEye);
  40651. return null;
  40652. }
  40653. return offset;
  40654. };
  40655. CardboardVRDisplay.prototype.getEyeParameters = function (whichEye) {
  40656. var offset = this._getEyeOffset(whichEye);
  40657. var fieldOfView = this._getFieldOfView(whichEye);
  40658. var eyeParams = {
  40659. offset: offset,
  40660. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  40661. renderHeight: this.deviceInfo_.device.height * this.bufferScale_
  40662. };
  40663. Object.defineProperty(eyeParams, 'fieldOfView', {
  40664. enumerable: true,
  40665. get: function get() {
  40666. deprecateWarning('VRFieldOfView', 'VRFrameData\'s projection matrices');
  40667. return fieldOfView;
  40668. }
  40669. });
  40670. return eyeParams;
  40671. };
  40672. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function (newParams) {
  40673. if (this.config.DEBUG) {
  40674. console.log('DPDB reported that device params were updated.');
  40675. }
  40676. this.deviceInfo_.updateDeviceParams(newParams);
  40677. if (this.distorter_) {
  40678. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40679. }
  40680. };
  40681. CardboardVRDisplay.prototype.updateBounds_ = function () {
  40682. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  40683. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  40684. }
  40685. };
  40686. CardboardVRDisplay.prototype.beginPresent_ = function () {
  40687. var gl = this.layer_.source.getContext('webgl');
  40688. if (!gl) gl = this.layer_.source.getContext('experimental-webgl');
  40689. if (!gl) gl = this.layer_.source.getContext('webgl2');
  40690. if (!gl) return;
  40691. if (this.layer_.predistorted) {
  40692. if (!this.config.CARDBOARD_UI_DISABLED) {
  40693. gl.canvas.width = getScreenWidth() * this.bufferScale_;
  40694. gl.canvas.height = getScreenHeight() * this.bufferScale_;
  40695. this.cardboardUI_ = new CardboardUI(gl);
  40696. }
  40697. } else {
  40698. if (!this.config.CARDBOARD_UI_DISABLED) {
  40699. this.cardboardUI_ = new CardboardUI(gl);
  40700. }
  40701. this.distorter_ = new CardboardDistorter(gl, this.cardboardUI_, this.config.BUFFER_SCALE, this.config.DIRTY_SUBMIT_FRAME_BINDINGS);
  40702. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40703. }
  40704. if (this.cardboardUI_) {
  40705. this.cardboardUI_.listen(function (e) {
  40706. this.viewerSelector_.show(this.layer_.source.parentElement);
  40707. e.stopPropagation();
  40708. e.preventDefault();
  40709. }.bind(this), function (e) {
  40710. this.exitPresent();
  40711. e.stopPropagation();
  40712. e.preventDefault();
  40713. }.bind(this));
  40714. }
  40715. if (this.rotateInstructions_) {
  40716. if (isLandscapeMode() && isMobile()) {
  40717. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  40718. } else {
  40719. this.rotateInstructions_.update();
  40720. }
  40721. }
  40722. this.orientationHandler = this.onOrientationChange_.bind(this);
  40723. window.addEventListener('orientationchange', this.orientationHandler);
  40724. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  40725. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40726. this.fireVRDisplayDeviceParamsChange_();
  40727. };
  40728. CardboardVRDisplay.prototype.endPresent_ = function () {
  40729. if (this.distorter_) {
  40730. this.distorter_.destroy();
  40731. this.distorter_ = null;
  40732. }
  40733. if (this.cardboardUI_) {
  40734. this.cardboardUI_.destroy();
  40735. this.cardboardUI_ = null;
  40736. }
  40737. if (this.rotateInstructions_) {
  40738. this.rotateInstructions_.hide();
  40739. }
  40740. this.viewerSelector_.hide();
  40741. window.removeEventListener('orientationchange', this.orientationHandler);
  40742. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  40743. };
  40744. CardboardVRDisplay.prototype.updatePresent_ = function () {
  40745. this.endPresent_();
  40746. this.beginPresent_();
  40747. };
  40748. CardboardVRDisplay.prototype.submitFrame = function (pose) {
  40749. if (this.distorter_) {
  40750. this.updateBounds_();
  40751. this.distorter_.submitFrame();
  40752. } else if (this.cardboardUI_ && this.layer_) {
  40753. var canvas = this.layer_.source.getContext('webgl').canvas;
  40754. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  40755. this.cardboardUI_.onResize();
  40756. }
  40757. this.lastWidth = canvas.width;
  40758. this.lastHeight = canvas.height;
  40759. this.cardboardUI_.render();
  40760. }
  40761. };
  40762. CardboardVRDisplay.prototype.onOrientationChange_ = function (e) {
  40763. this.viewerSelector_.hide();
  40764. if (this.rotateInstructions_) {
  40765. this.rotateInstructions_.update();
  40766. }
  40767. this.onResize_();
  40768. };
  40769. CardboardVRDisplay.prototype.onResize_ = function (e) {
  40770. if (this.layer_) {
  40771. var gl = this.layer_.source.getContext('webgl');
  40772. var cssProperties = ['position: absolute', 'top: 0', 'left: 0',
  40773. 'width: 100vw', 'height: 100vh', 'border: 0', 'margin: 0',
  40774. 'padding: 0px', 'box-sizing: content-box'];
  40775. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  40776. safariCssSizeWorkaround(gl.canvas);
  40777. }
  40778. };
  40779. CardboardVRDisplay.prototype.onViewerChanged_ = function (viewer) {
  40780. this.deviceInfo_.setViewer(viewer);
  40781. if (this.distorter_) {
  40782. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  40783. }
  40784. this.fireVRDisplayDeviceParamsChange_();
  40785. };
  40786. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function () {
  40787. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  40788. detail: {
  40789. vrdisplay: this,
  40790. deviceInfo: this.deviceInfo_
  40791. }
  40792. });
  40793. window.dispatchEvent(event);
  40794. };
  40795. CardboardVRDisplay.VRFrameData = VRFrameData;
  40796. CardboardVRDisplay.VRDisplay = VRDisplay;
  40797. return CardboardVRDisplay;
  40798. })));
  40799. });
  40800. var CardboardVRDisplay = unwrapExports(cardboardVrDisplay);
  40801. var version = "0.10.10";
  40802. var DefaultConfig = {
  40803. ADDITIONAL_VIEWERS: [],
  40804. DEFAULT_VIEWER: '',
  40805. PROVIDE_MOBILE_VRDISPLAY: true,
  40806. MOBILE_WAKE_LOCK: true,
  40807. DEBUG: false,
  40808. DPDB_URL: 'https://dpdb.webvr.rocks/dpdb.json',
  40809. K_FILTER: 0.98,
  40810. PREDICTION_TIME_S: 0.040,
  40811. CARDBOARD_UI_DISABLED: false,
  40812. ROTATE_INSTRUCTIONS_DISABLED: false,
  40813. YAW_ONLY: false,
  40814. BUFFER_SCALE: 0.5,
  40815. DIRTY_SUBMIT_FRAME_BINDINGS: false
  40816. };
  40817. function WebVRPolyfill(config) {
  40818. this.config = extend(extend({}, DefaultConfig), config);
  40819. this.polyfillDisplays = [];
  40820. this.enabled = false;
  40821. this.hasNative = 'getVRDisplays' in navigator;
  40822. this.native = {};
  40823. this.native.getVRDisplays = navigator.getVRDisplays;
  40824. this.native.VRFrameData = window.VRFrameData;
  40825. this.native.VRDisplay = window.VRDisplay;
  40826. if (!this.hasNative || this.config.PROVIDE_MOBILE_VRDISPLAY && isMobile()) {
  40827. this.enable();
  40828. this.getVRDisplays().then(function (displays) {
  40829. if (displays && displays[0] && displays[0].fireVRDisplayConnect_) {
  40830. displays[0].fireVRDisplayConnect_();
  40831. }
  40832. });
  40833. }
  40834. }
  40835. WebVRPolyfill.prototype.getPolyfillDisplays = function () {
  40836. if (this._polyfillDisplaysPopulated) {
  40837. return this.polyfillDisplays;
  40838. }
  40839. if (isMobile()) {
  40840. var vrDisplay = new CardboardVRDisplay({
  40841. ADDITIONAL_VIEWERS: this.config.ADDITIONAL_VIEWERS,
  40842. DEFAULT_VIEWER: this.config.DEFAULT_VIEWER,
  40843. MOBILE_WAKE_LOCK: this.config.MOBILE_WAKE_LOCK,
  40844. DEBUG: this.config.DEBUG,
  40845. DPDB_URL: this.config.DPDB_URL,
  40846. CARDBOARD_UI_DISABLED: this.config.CARDBOARD_UI_DISABLED,
  40847. K_FILTER: this.config.K_FILTER,
  40848. PREDICTION_TIME_S: this.config.PREDICTION_TIME_S,
  40849. ROTATE_INSTRUCTIONS_DISABLED: this.config.ROTATE_INSTRUCTIONS_DISABLED,
  40850. YAW_ONLY: this.config.YAW_ONLY,
  40851. BUFFER_SCALE: this.config.BUFFER_SCALE,
  40852. DIRTY_SUBMIT_FRAME_BINDINGS: this.config.DIRTY_SUBMIT_FRAME_BINDINGS
  40853. });
  40854. this.polyfillDisplays.push(vrDisplay);
  40855. }
  40856. this._polyfillDisplaysPopulated = true;
  40857. return this.polyfillDisplays;
  40858. };
  40859. WebVRPolyfill.prototype.enable = function () {
  40860. this.enabled = true;
  40861. if (this.hasNative && this.native.VRFrameData) {
  40862. var NativeVRFrameData = this.native.VRFrameData;
  40863. var nativeFrameData = new this.native.VRFrameData();
  40864. var nativeGetFrameData = this.native.VRDisplay.prototype.getFrameData;
  40865. window.VRDisplay.prototype.getFrameData = function (frameData) {
  40866. if (frameData instanceof NativeVRFrameData) {
  40867. nativeGetFrameData.call(this, frameData);
  40868. return;
  40869. }
  40870. nativeGetFrameData.call(this, nativeFrameData);
  40871. frameData.pose = nativeFrameData.pose;
  40872. copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  40873. copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  40874. copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  40875. copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  40876. };
  40877. }
  40878. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  40879. window.VRDisplay = CardboardVRDisplay.VRDisplay;
  40880. window.VRFrameData = CardboardVRDisplay.VRFrameData;
  40881. };
  40882. WebVRPolyfill.prototype.getVRDisplays = function () {
  40883. var _this = this;
  40884. var config = this.config;
  40885. if (!this.hasNative) {
  40886. return Promise.resolve(this.getPolyfillDisplays());
  40887. }
  40888. return this.native.getVRDisplays.call(navigator).then(function (nativeDisplays) {
  40889. return nativeDisplays.length > 0 ? nativeDisplays : _this.getPolyfillDisplays();
  40890. });
  40891. };
  40892. WebVRPolyfill.version = version;
  40893. WebVRPolyfill.VRFrameData = CardboardVRDisplay.VRFrameData;
  40894. WebVRPolyfill.VRDisplay = CardboardVRDisplay.VRDisplay;
  40895. var webvrPolyfill = Object.freeze({
  40896. default: WebVRPolyfill
  40897. });
  40898. var require$$0 = ( webvrPolyfill && WebVRPolyfill ) || webvrPolyfill;
  40899. if (typeof commonjsGlobal !== 'undefined' && commonjsGlobal.window) {
  40900. if (!commonjsGlobal.document) {
  40901. commonjsGlobal.document = commonjsGlobal.window.document;
  40902. }
  40903. if (!commonjsGlobal.navigator) {
  40904. commonjsGlobal.navigator = commonjsGlobal.window.navigator;
  40905. }
  40906. }
  40907. var src = require$$0;
  40908. return src;
  40909. })));
  40910. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40911. },{}],47:[function(_dereq_,module,exports){
  40912. var newline = /\n/
  40913. var newlineChar = '\n'
  40914. var whitespace = /\s/
  40915. module.exports = function(text, opt) {
  40916. var lines = module.exports.lines(text, opt)
  40917. return lines.map(function(line) {
  40918. return text.substring(line.start, line.end)
  40919. }).join('\n')
  40920. }
  40921. module.exports.lines = function wordwrap(text, opt) {
  40922. opt = opt||{}
  40923. //zero width results in nothing visible
  40924. if (opt.width === 0 && opt.mode !== 'nowrap')
  40925. return []
  40926. text = text||''
  40927. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  40928. var start = Math.max(0, opt.start||0)
  40929. var end = typeof opt.end === 'number' ? opt.end : text.length
  40930. var mode = opt.mode
  40931. var measure = opt.measure || monospace
  40932. if (mode === 'pre')
  40933. return pre(measure, text, start, end, width)
  40934. else
  40935. return greedy(measure, text, start, end, width, mode)
  40936. }
  40937. function idxOf(text, chr, start, end) {
  40938. var idx = text.indexOf(chr, start)
  40939. if (idx === -1 || idx > end)
  40940. return end
  40941. return idx
  40942. }
  40943. function isWhitespace(chr) {
  40944. return whitespace.test(chr)
  40945. }
  40946. function pre(measure, text, start, end, width) {
  40947. var lines = []
  40948. var lineStart = start
  40949. for (var i=start; i<end && i<text.length; i++) {
  40950. var chr = text.charAt(i)
  40951. var isNewline = newline.test(chr)
  40952. //If we've reached a newline, then step down a line
  40953. //Or if we've reached the EOF
  40954. if (isNewline || i===end-1) {
  40955. var lineEnd = isNewline ? i : i+1
  40956. var measured = measure(text, lineStart, lineEnd, width)
  40957. lines.push(measured)
  40958. lineStart = i+1
  40959. }
  40960. }
  40961. return lines
  40962. }
  40963. function greedy(measure, text, start, end, width, mode) {
  40964. //A greedy word wrapper based on LibGDX algorithm
  40965. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  40966. var lines = []
  40967. var testWidth = width
  40968. //if 'nowrap' is specified, we only wrap on newline chars
  40969. if (mode === 'nowrap')
  40970. testWidth = Number.MAX_VALUE
  40971. while (start < end && start < text.length) {
  40972. //get next newline position
  40973. var newLine = idxOf(text, newlineChar, start, end)
  40974. //eat whitespace at start of line
  40975. while (start < newLine) {
  40976. if (!isWhitespace( text.charAt(start) ))
  40977. break
  40978. start++
  40979. }
  40980. //determine visible # of glyphs for the available width
  40981. var measured = measure(text, start, newLine, testWidth)
  40982. var lineEnd = start + (measured.end-measured.start)
  40983. var nextStart = lineEnd + newlineChar.length
  40984. //if we had to cut the line before the next newline...
  40985. if (lineEnd < newLine) {
  40986. //find char to break on
  40987. while (lineEnd > start) {
  40988. if (isWhitespace(text.charAt(lineEnd)))
  40989. break
  40990. lineEnd--
  40991. }
  40992. if (lineEnd === start) {
  40993. if (nextStart > start + newlineChar.length) nextStart--
  40994. lineEnd = nextStart // If no characters to break, show all.
  40995. } else {
  40996. nextStart = lineEnd
  40997. //eat whitespace at end of line
  40998. while (lineEnd > start) {
  40999. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  41000. break
  41001. lineEnd--
  41002. }
  41003. }
  41004. }
  41005. if (lineEnd >= start) {
  41006. var result = measure(text, start, lineEnd, testWidth)
  41007. lines.push(result)
  41008. }
  41009. start = nextStart
  41010. }
  41011. return lines
  41012. }
  41013. //determines the visible number of glyphs within a given width
  41014. function monospace(text, start, end, width) {
  41015. var glyphs = Math.min(width, end-start)
  41016. return {
  41017. start: start,
  41018. end: start+glyphs
  41019. }
  41020. }
  41021. },{}],48:[function(_dereq_,module,exports){
  41022. "use strict";
  41023. var window = _dereq_("global/window")
  41024. var isFunction = _dereq_("is-function")
  41025. var parseHeaders = _dereq_("parse-headers")
  41026. var xtend = _dereq_("xtend")
  41027. module.exports = createXHR
  41028. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  41029. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  41030. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  41031. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  41032. options = initParams(uri, options, callback)
  41033. options.method = method.toUpperCase()
  41034. return _createXHR(options)
  41035. }
  41036. })
  41037. function forEachArray(array, iterator) {
  41038. for (var i = 0; i < array.length; i++) {
  41039. iterator(array[i])
  41040. }
  41041. }
  41042. function isEmpty(obj){
  41043. for(var i in obj){
  41044. if(obj.hasOwnProperty(i)) return false
  41045. }
  41046. return true
  41047. }
  41048. function initParams(uri, options, callback) {
  41049. var params = uri
  41050. if (isFunction(options)) {
  41051. callback = options
  41052. if (typeof uri === "string") {
  41053. params = {uri:uri}
  41054. }
  41055. } else {
  41056. params = xtend(options, {uri: uri})
  41057. }
  41058. params.callback = callback
  41059. return params
  41060. }
  41061. function createXHR(uri, options, callback) {
  41062. options = initParams(uri, options, callback)
  41063. return _createXHR(options)
  41064. }
  41065. function _createXHR(options) {
  41066. if(typeof options.callback === "undefined"){
  41067. throw new Error("callback argument missing")
  41068. }
  41069. var called = false
  41070. var callback = function cbOnce(err, response, body){
  41071. if(!called){
  41072. called = true
  41073. options.callback(err, response, body)
  41074. }
  41075. }
  41076. function readystatechange() {
  41077. if (xhr.readyState === 4) {
  41078. setTimeout(loadFunc, 0)
  41079. }
  41080. }
  41081. function getBody() {
  41082. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  41083. var body = undefined
  41084. if (xhr.response) {
  41085. body = xhr.response
  41086. } else {
  41087. body = xhr.responseText || getXml(xhr)
  41088. }
  41089. if (isJson) {
  41090. try {
  41091. body = JSON.parse(body)
  41092. } catch (e) {}
  41093. }
  41094. return body
  41095. }
  41096. function errorFunc(evt) {
  41097. clearTimeout(timeoutTimer)
  41098. if(!(evt instanceof Error)){
  41099. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  41100. }
  41101. evt.statusCode = 0
  41102. return callback(evt, failureResponse)
  41103. }
  41104. // will load the data & process the response in a special response object
  41105. function loadFunc() {
  41106. if (aborted) return
  41107. var status
  41108. clearTimeout(timeoutTimer)
  41109. if(options.useXDR && xhr.status===undefined) {
  41110. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  41111. status = 200
  41112. } else {
  41113. status = (xhr.status === 1223 ? 204 : xhr.status)
  41114. }
  41115. var response = failureResponse
  41116. var err = null
  41117. if (status !== 0){
  41118. response = {
  41119. body: getBody(),
  41120. statusCode: status,
  41121. method: method,
  41122. headers: {},
  41123. url: uri,
  41124. rawRequest: xhr
  41125. }
  41126. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  41127. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  41128. }
  41129. } else {
  41130. err = new Error("Internal XMLHttpRequest Error")
  41131. }
  41132. return callback(err, response, response.body)
  41133. }
  41134. var xhr = options.xhr || null
  41135. if (!xhr) {
  41136. if (options.cors || options.useXDR) {
  41137. xhr = new createXHR.XDomainRequest()
  41138. }else{
  41139. xhr = new createXHR.XMLHttpRequest()
  41140. }
  41141. }
  41142. var key
  41143. var aborted
  41144. var uri = xhr.url = options.uri || options.url
  41145. var method = xhr.method = options.method || "GET"
  41146. var body = options.body || options.data
  41147. var headers = xhr.headers = options.headers || {}
  41148. var sync = !!options.sync
  41149. var isJson = false
  41150. var timeoutTimer
  41151. var failureResponse = {
  41152. body: undefined,
  41153. headers: {},
  41154. statusCode: 0,
  41155. method: method,
  41156. url: uri,
  41157. rawRequest: xhr
  41158. }
  41159. if ("json" in options && options.json !== false) {
  41160. isJson = true
  41161. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  41162. if (method !== "GET" && method !== "HEAD") {
  41163. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  41164. body = JSON.stringify(options.json === true ? body : options.json)
  41165. }
  41166. }
  41167. xhr.onreadystatechange = readystatechange
  41168. xhr.onload = loadFunc
  41169. xhr.onerror = errorFunc
  41170. // IE9 must have onprogress be set to a unique function.
  41171. xhr.onprogress = function () {
  41172. // IE must die
  41173. }
  41174. xhr.onabort = function(){
  41175. aborted = true;
  41176. }
  41177. xhr.ontimeout = errorFunc
  41178. xhr.open(method, uri, !sync, options.username, options.password)
  41179. //has to be after open
  41180. if(!sync) {
  41181. xhr.withCredentials = !!options.withCredentials
  41182. }
  41183. // Cannot set timeout with sync request
  41184. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  41185. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  41186. if (!sync && options.timeout > 0 ) {
  41187. timeoutTimer = setTimeout(function(){
  41188. if (aborted) return
  41189. aborted = true//IE9 may still call readystatechange
  41190. xhr.abort("timeout")
  41191. var e = new Error("XMLHttpRequest timeout")
  41192. e.code = "ETIMEDOUT"
  41193. errorFunc(e)
  41194. }, options.timeout )
  41195. }
  41196. if (xhr.setRequestHeader) {
  41197. for(key in headers){
  41198. if(headers.hasOwnProperty(key)){
  41199. xhr.setRequestHeader(key, headers[key])
  41200. }
  41201. }
  41202. } else if (options.headers && !isEmpty(options.headers)) {
  41203. throw new Error("Headers cannot be set on an XDomainRequest object")
  41204. }
  41205. if ("responseType" in options) {
  41206. xhr.responseType = options.responseType
  41207. }
  41208. if ("beforeSend" in options &&
  41209. typeof options.beforeSend === "function"
  41210. ) {
  41211. options.beforeSend(xhr)
  41212. }
  41213. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  41214. // XMLHttpRequest spec says to pass null as body to indicate no body
  41215. // See https://github.com/naugtur/xhr/issues/100.
  41216. xhr.send(body || null)
  41217. return xhr
  41218. }
  41219. function getXml(xhr) {
  41220. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  41221. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  41222. try {
  41223. if (xhr.responseType === "document") {
  41224. return xhr.responseXML
  41225. }
  41226. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  41227. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  41228. return xhr.responseXML
  41229. }
  41230. } catch (e) {}
  41231. return null
  41232. }
  41233. function noop() {}
  41234. },{"global/window":15,"is-function":19,"parse-headers":30,"xtend":50}],49:[function(_dereq_,module,exports){
  41235. module.exports = (function xmlparser() {
  41236. //common browsers
  41237. if (typeof self.DOMParser !== 'undefined') {
  41238. return function(str) {
  41239. var parser = new self.DOMParser()
  41240. return parser.parseFromString(str, 'application/xml')
  41241. }
  41242. }
  41243. //IE8 fallback
  41244. if (typeof self.ActiveXObject !== 'undefined'
  41245. && new self.ActiveXObject('Microsoft.XMLDOM')) {
  41246. return function(str) {
  41247. var xmlDoc = new self.ActiveXObject("Microsoft.XMLDOM")
  41248. xmlDoc.async = "false"
  41249. xmlDoc.loadXML(str)
  41250. return xmlDoc
  41251. }
  41252. }
  41253. //last resort fallback
  41254. return function(str) {
  41255. var div = document.createElement('div')
  41256. div.innerHTML = str
  41257. return div
  41258. }
  41259. })()
  41260. },{}],50:[function(_dereq_,module,exports){
  41261. module.exports = extend
  41262. var hasOwnProperty = Object.prototype.hasOwnProperty;
  41263. function extend() {
  41264. var target = {}
  41265. for (var i = 0; i < arguments.length; i++) {
  41266. var source = arguments[i]
  41267. for (var key in source) {
  41268. if (hasOwnProperty.call(source, key)) {
  41269. target[key] = source[key]
  41270. }
  41271. }
  41272. }
  41273. return target
  41274. }
  41275. },{}],51:[function(_dereq_,module,exports){
  41276. module.exports={
  41277. "name": "aframe",
  41278. "version": "0.9.2",
  41279. "description": "A web framework for building virtual reality experiences.",
  41280. "homepage": "https://aframe.io/",
  41281. "main": "dist/aframe-master.js",
  41282. "scripts": {
  41283. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  41284. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  41285. "codecov": "codecov",
  41286. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  41287. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  41288. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  41289. "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",
  41290. "docs": "markserv --dir docs --port 9001",
  41291. "preghpages": "node ./scripts/preghpages.js",
  41292. "ghpages": "ghpages -p gh-pages/",
  41293. "lint": "semistandard -v | snazzy",
  41294. "lint:fix": "semistandard --fix",
  41295. "precommit": "npm run lint",
  41296. "prepush": "node scripts/testOnlyCheck.js",
  41297. "prerelease": "node scripts/release.js 0.9.1 0.9.2",
  41298. "start": "npm run dev",
  41299. "start:https": "cross-env SSL=true npm run dev",
  41300. "test": "karma start ./tests/karma.conf.js",
  41301. "test:docs": "node scripts/docsLint.js",
  41302. "test:firefox": "npm test -- --browsers Firefox",
  41303. "test:chrome": "npm test -- --browsers Chrome",
  41304. "test:nobrowser": "NO_BROWSER=true npm test",
  41305. "test:node": "mocha --ui tdd tests/node"
  41306. },
  41307. "repository": "aframevr/aframe",
  41308. "license": "MIT",
  41309. "files": [
  41310. "dist/*",
  41311. "docs/**/*",
  41312. "src/**/*",
  41313. "vendor/**/*"
  41314. ],
  41315. "dependencies": {
  41316. "browserify-css": "^0.8.4",
  41317. "custom-event-polyfill": "^1.0.6",
  41318. "debug": "ngokevin/debug#noTimestamp",
  41319. "deep-assign": "^2.0.0",
  41320. "document-register-element": "dmarcos/document-register-element#8ccc532b7f3744be954574caf3072a5fd260ca90",
  41321. "envify": "^3.4.1",
  41322. "load-bmfont": "^1.2.3",
  41323. "object-assign": "^4.0.1",
  41324. "present": "0.0.6",
  41325. "promise-polyfill": "^3.1.0",
  41326. "style-attr": "^1.0.2",
  41327. "super-animejs": "^3.0.0",
  41328. "super-three": "^0.102.2",
  41329. "three-bmfont-text": "^2.1.0",
  41330. "webvr-polyfill": "^0.10.10"
  41331. },
  41332. "devDependencies": {
  41333. "browserify": "^13.1.0",
  41334. "browserify-derequire": "^0.9.4",
  41335. "browserify-istanbul": "^2.0.0",
  41336. "budo": "^9.2.0",
  41337. "chai": "^3.5.0",
  41338. "chai-shallow-deep-equal": "^1.4.0",
  41339. "chalk": "^1.1.3",
  41340. "codecov": "^1.0.1",
  41341. "cross-env": "^5.0.1",
  41342. "exorcist": "^0.4.0",
  41343. "ghpages": "0.0.8",
  41344. "git-rev": "^0.2.1",
  41345. "glob": "^7.1.1",
  41346. "husky": "^0.11.7",
  41347. "istanbul": "^0.4.5",
  41348. "jsdom": "^9.11.0",
  41349. "karma": "1.4.1",
  41350. "karma-browserify": "^5.1.0",
  41351. "karma-chai-shallow-deep-equal": "0.0.4",
  41352. "karma-chrome-launcher": "^2.0.0",
  41353. "karma-coverage": "^1.1.1",
  41354. "karma-env-preprocessor": "^0.1.1",
  41355. "karma-firefox-launcher": "^1.0.0",
  41356. "karma-mocha": "^1.1.1",
  41357. "karma-mocha-reporter": "^2.1.0",
  41358. "karma-sinon-chai": "1.2.4",
  41359. "lolex": "^1.5.1",
  41360. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  41361. "minifyify": "^7.3.3",
  41362. "mocha": "^3.0.2",
  41363. "mozilla-download": "^1.1.1",
  41364. "replace-in-file": "^2.5.3",
  41365. "semistandard": "^9.0.0",
  41366. "shelljs": "^0.7.7",
  41367. "shx": "^0.2.2",
  41368. "sinon": "^1.17.5",
  41369. "sinon-chai": "2.8.0",
  41370. "snazzy": "^5.0.0",
  41371. "too-wordy": "ngokevin/too-wordy",
  41372. "uglifyjs": "^2.4.10",
  41373. "write-good": "^0.9.1"
  41374. },
  41375. "link": true,
  41376. "browserify": {
  41377. "transform": [
  41378. "browserify-css",
  41379. "envify"
  41380. ]
  41381. },
  41382. "semistandard": {
  41383. "ignore": [
  41384. "build/**",
  41385. "dist/**",
  41386. "examples/**/shaders/*.js",
  41387. "**/vendor/**"
  41388. ]
  41389. },
  41390. "keywords": [
  41391. "3d",
  41392. "aframe",
  41393. "cardboard",
  41394. "components",
  41395. "oculus",
  41396. "three",
  41397. "three.js",
  41398. "rift",
  41399. "vive",
  41400. "vr",
  41401. "web-components",
  41402. "webvr"
  41403. ],
  41404. "browserify-css": {
  41405. "minify": true
  41406. },
  41407. "engines": {
  41408. "node": ">= 4.6.0",
  41409. "npm": "^2.15.9"
  41410. }
  41411. }
  41412. },{}],52:[function(_dereq_,module,exports){
  41413. var anime = _dereq_('super-animejs');
  41414. var components = _dereq_('../core/component').components;
  41415. var registerComponent = _dereq_('../core/component').registerComponent;
  41416. var THREE = _dereq_('../lib/three');
  41417. var utils = _dereq_('../utils');
  41418. var colorHelperFrom = new THREE.Color();
  41419. var colorHelperTo = new THREE.Color();
  41420. var getComponentProperty = utils.entity.getComponentProperty;
  41421. var setComponentProperty = utils.entity.setComponentProperty;
  41422. var splitCache = {};
  41423. var TYPE_COLOR = 'color';
  41424. var PROP_POSITION = 'position';
  41425. var PROP_ROTATION = 'rotation';
  41426. var PROP_SCALE = 'scale';
  41427. var STRING_COMPONENTS = 'components';
  41428. var STRING_OBJECT3D = 'object3D';
  41429. /**
  41430. * Animation component for A-Frame using anime.js.
  41431. *
  41432. * The component manually controls the tick by setting `autoplay: false` on anime.js and
  41433. * manually * calling `animation.tick()` in the tick handler. To pause or resume, we toggle a
  41434. * boolean * flag * `isAnimationPlaying`.
  41435. *
  41436. * anime.js animation config for tweenining Javascript objects and values works as:
  41437. *
  41438. * config = {
  41439. * targets: {foo: 0.0, bar: '#000'},
  41440. * foo: 1.0,
  41441. * bar: '#FFF'
  41442. * }
  41443. *
  41444. * The above will tween each property in `targets`. The `to` values are set in the root of
  41445. * the config.
  41446. *
  41447. * @member {object} animation - anime.js instance.
  41448. * @member {boolean} animationIsPlaying - Control if animation is playing.
  41449. */
  41450. module.exports.Component = registerComponent('animation', {
  41451. schema: {
  41452. autoplay: {default: true},
  41453. delay: {default: 0},
  41454. dir: {default: ''},
  41455. dur: {default: 1000},
  41456. easing: {default: 'easeInQuad'},
  41457. elasticity: {default: 400},
  41458. enabled: {default: true},
  41459. from: {default: ''},
  41460. loop: {
  41461. default: 0,
  41462. parse: function (value) {
  41463. // Boolean or integer.
  41464. if (value === true || value === 'true') { return true; }
  41465. if (value === false || value === 'false') { return false; }
  41466. return parseInt(value, 10);
  41467. }
  41468. },
  41469. property: {default: ''},
  41470. startEvents: {type: 'array'},
  41471. pauseEvents: {type: 'array'},
  41472. resumeEvents: {type: 'array'},
  41473. round: {default: false},
  41474. to: {default: ''},
  41475. type: {default: ''},
  41476. isRawProperty: {default: false}
  41477. },
  41478. multiple: true,
  41479. init: function () {
  41480. var self = this;
  41481. this.eventDetail = {name: this.attrName};
  41482. this.time = 0;
  41483. this.animation = null;
  41484. this.animationIsPlaying = false;
  41485. this.onStartEvent = this.onStartEvent.bind(this);
  41486. this.beginAnimation = this.beginAnimation.bind(this);
  41487. this.pauseAnimation = this.pauseAnimation.bind(this);
  41488. this.resumeAnimation = this.resumeAnimation.bind(this);
  41489. this.fromColor = {};
  41490. this.toColor = {};
  41491. this.targets = {};
  41492. this.targetsArray = [];
  41493. this.updateConfigForDefault = this.updateConfigForDefault.bind(this);
  41494. this.updateConfigForRawColor = this.updateConfigForRawColor.bind(this);
  41495. this.config = {
  41496. complete: function () {
  41497. self.animationIsPlaying = false;
  41498. self.el.emit('animationcomplete', self.eventDetail, false);
  41499. if (self.id) {
  41500. self.el.emit('animationcomplete__' + self.id, self.eventDetail, false);
  41501. }
  41502. }
  41503. };
  41504. },
  41505. update: function (oldData) {
  41506. var config = this.config;
  41507. var data = this.data;
  41508. this.animationIsPlaying = false;
  41509. if (!this.data.enabled) { return; }
  41510. if (!data.property) { return; }
  41511. // Base config.
  41512. config.autoplay = false;
  41513. config.direction = data.dir;
  41514. config.duration = data.dur;
  41515. config.easing = data.easing;
  41516. config.elasticity = data.elasticity;
  41517. config.loop = data.loop;
  41518. config.round = data.round;
  41519. // Start new animation.
  41520. this.createAndStartAnimation();
  41521. },
  41522. tick: function (t, dt) {
  41523. if (!this.animationIsPlaying) { return; }
  41524. this.time += dt;
  41525. this.animation.tick(this.time);
  41526. },
  41527. remove: function () {
  41528. this.pauseAnimation();
  41529. this.removeEventListeners();
  41530. },
  41531. pause: function () {
  41532. this.paused = true;
  41533. this.pausedWasPlaying = this.animationIsPlaying;
  41534. this.pauseAnimation();
  41535. this.removeEventListeners();
  41536. },
  41537. /**
  41538. * `play` handler only for resuming scene.
  41539. */
  41540. play: function () {
  41541. if (!this.paused) { return; }
  41542. this.paused = false;
  41543. this.addEventListeners();
  41544. if (this.pausedWasPlaying) {
  41545. this.resumeAnimation();
  41546. this.pausedWasPlaying = false;
  41547. }
  41548. },
  41549. /**
  41550. * Start animation from scratch.
  41551. */
  41552. createAndStartAnimation: function () {
  41553. var data = this.data;
  41554. this.updateConfig();
  41555. this.animationIsPlaying = false;
  41556. this.animation = anime(this.config);
  41557. this.animation.began = true;
  41558. this.removeEventListeners();
  41559. this.addEventListeners();
  41560. // Wait for start events for animation.
  41561. if (!data.autoplay || data.startEvents && data.startEvents.length) { return; }
  41562. // Delay animation.
  41563. if (data.delay) {
  41564. setTimeout(this.beginAnimation, data.delay);
  41565. return;
  41566. }
  41567. // Play animation.
  41568. this.beginAnimation();
  41569. },
  41570. /**
  41571. * This is before animation start (including from startEvents).
  41572. * Set to initial state (config.from, time = 0, seekTime = 0).
  41573. */
  41574. beginAnimation: function () {
  41575. this.updateConfig();
  41576. this.animation.began = true;
  41577. this.time = 0;
  41578. this.animationIsPlaying = true;
  41579. this.stopRelatedAnimations();
  41580. this.el.emit('animationbegin', this.eventDetail, false);
  41581. },
  41582. pauseAnimation: function () {
  41583. this.animationIsPlaying = false;
  41584. },
  41585. resumeAnimation: function () {
  41586. this.animationIsPlaying = true;
  41587. },
  41588. /**
  41589. * startEvents callback.
  41590. */
  41591. onStartEvent: function () {
  41592. if (!this.data.enabled) { return; }
  41593. this.updateConfig();
  41594. if (this.animation) {
  41595. this.animation.pause();
  41596. }
  41597. this.animation = anime(this.config);
  41598. // Include the delay before each start event.
  41599. if (this.data.delay) {
  41600. setTimeout(this.beginAnimation, this.data.delay);
  41601. return;
  41602. }
  41603. this.beginAnimation();
  41604. },
  41605. /**
  41606. * rawProperty: true and type: color;
  41607. */
  41608. updateConfigForRawColor: function () {
  41609. var config = this.config;
  41610. var data = this.data;
  41611. var el = this.el;
  41612. var from;
  41613. var key;
  41614. var to;
  41615. if (this.waitComponentInitRawProperty(this.updateConfigForRawColor)) {
  41616. return;
  41617. }
  41618. from = data.from === '' ? getRawProperty(el, data.property) : data.from;
  41619. to = data.to;
  41620. // Use r/g/b vector for color type.
  41621. this.setColorConfig(from, to);
  41622. from = this.fromColor;
  41623. to = this.toColor;
  41624. this.targetsArray.length = 0;
  41625. this.targetsArray.push(from);
  41626. config.targets = this.targetsArray;
  41627. for (key in to) { config[key] = to[key]; }
  41628. config.update = (function () {
  41629. var lastValue = {};
  41630. return function (anim) {
  41631. var value;
  41632. value = anim.animatables[0].target;
  41633. // For animation timeline.
  41634. if (value.r === lastValue.r &&
  41635. value.g === lastValue.g &&
  41636. value.b === lastValue.b) { return; }
  41637. setRawProperty(el, data.property, value, data.type);
  41638. };
  41639. })();
  41640. },
  41641. /**
  41642. * Stuff property into generic `property` key.
  41643. */
  41644. updateConfigForDefault: function () {
  41645. var config = this.config;
  41646. var data = this.data;
  41647. var el = this.el;
  41648. var from;
  41649. var isBoolean;
  41650. var isNumber;
  41651. var to;
  41652. if (this.waitComponentInitRawProperty(this.updateConfigForDefault)) {
  41653. return;
  41654. }
  41655. if (data.from === '') {
  41656. // Infer from.
  41657. from = isRawProperty(data)
  41658. ? getRawProperty(el, data.property)
  41659. : getComponentProperty(el, data.property);
  41660. } else {
  41661. // Explicit from.
  41662. from = data.from;
  41663. }
  41664. to = data.to;
  41665. isNumber = !isNaN(from || to);
  41666. if (isNumber) {
  41667. from = parseFloat(from);
  41668. to = parseFloat(to);
  41669. } else {
  41670. from = from ? from.toString() : from;
  41671. to = to ? to.toString() : to;
  41672. }
  41673. // Convert booleans to integer to allow boolean flipping.
  41674. isBoolean = data.to === 'true' || data.to === 'false' ||
  41675. data.to === true || data.to === false;
  41676. if (isBoolean) {
  41677. from = data.from === 'true' || data.from === true ? 1 : 0;
  41678. to = data.to === 'true' || data.to === true ? 1 : 0;
  41679. }
  41680. this.targets.aframeProperty = from;
  41681. config.targets = this.targets;
  41682. config.aframeProperty = to;
  41683. config.update = (function () {
  41684. var lastValue;
  41685. return function (anim) {
  41686. var value;
  41687. value = anim.animatables[0].target.aframeProperty;
  41688. // Need to do a last value check for animation timeline since all the tweening
  41689. // begins simultaenously even if the value has not changed. Also better for perf
  41690. // anyways.
  41691. if (value === lastValue) { return; }
  41692. lastValue = value;
  41693. if (isBoolean) { value = value >= 1; }
  41694. if (isRawProperty(data)) {
  41695. setRawProperty(el, data.property, value, data.type);
  41696. } else {
  41697. setComponentProperty(el, data.property, value);
  41698. }
  41699. };
  41700. })();
  41701. },
  41702. /**
  41703. * Extend x/y/z/w onto the config.
  41704. * Update vector by modifying object3D.
  41705. */
  41706. updateConfigForVector: function () {
  41707. var config = this.config;
  41708. var data = this.data;
  41709. var el = this.el;
  41710. var key;
  41711. var from;
  41712. var to;
  41713. // Parse coordinates.
  41714. from = data.from !== ''
  41715. ? utils.coordinates.parse(data.from) // If data.from defined, use that.
  41716. : getComponentProperty(el, data.property); // If data.from not defined, get on the fly.
  41717. to = utils.coordinates.parse(data.to);
  41718. if (data.property === PROP_ROTATION) {
  41719. toRadians(from);
  41720. toRadians(to);
  41721. }
  41722. // Set to and from.
  41723. this.targetsArray.length = 0;
  41724. this.targetsArray.push(from);
  41725. config.targets = this.targetsArray;
  41726. for (key in to) { config[key] = to[key]; }
  41727. // If animating object3D transformation, run more optimized updater.
  41728. if (data.property === PROP_POSITION || data.property === PROP_ROTATION ||
  41729. data.property === PROP_SCALE) {
  41730. config.update = (function () {
  41731. var lastValue = {};
  41732. return function (anim) {
  41733. var value = anim.animatables[0].target;
  41734. if (data.property === PROP_SCALE) {
  41735. value.x = Math.max(0.0001, value.x);
  41736. value.y = Math.max(0.0001, value.y);
  41737. value.z = Math.max(0.0001, value.z);
  41738. }
  41739. // For animation timeline.
  41740. if (value.x === lastValue.x &&
  41741. value.y === lastValue.y &&
  41742. value.z === lastValue.z) { return; }
  41743. lastValue.x = value.x;
  41744. lastValue.y = value.y;
  41745. lastValue.z = value.z;
  41746. el.object3D[data.property].set(value.x, value.y, value.z);
  41747. };
  41748. })();
  41749. return;
  41750. }
  41751. // Animating some vector.
  41752. config.update = (function () {
  41753. var lastValue = {};
  41754. return function (anim) {
  41755. var value = anim.animatables[0].target;
  41756. // Animate rotation through radians.
  41757. // For animation timeline.
  41758. if (value.x === lastValue.x &&
  41759. value.y === lastValue.y &&
  41760. value.z === lastValue.z) { return; }
  41761. lastValue.x = value.x;
  41762. lastValue.y = value.y;
  41763. lastValue.z = value.z;
  41764. setComponentProperty(el, data.property, value);
  41765. };
  41766. })();
  41767. },
  41768. /**
  41769. * Update the config before each run.
  41770. */
  41771. updateConfig: function () {
  41772. var propType;
  41773. // Route config type.
  41774. propType = getPropertyType(this.el, this.data.property);
  41775. if (isRawProperty(this.data) && this.data.type === TYPE_COLOR) {
  41776. this.updateConfigForRawColor();
  41777. } else if (propType === 'vec2' || propType === 'vec3' || propType === 'vec4') {
  41778. this.updateConfigForVector();
  41779. } else {
  41780. this.updateConfigForDefault();
  41781. }
  41782. },
  41783. /**
  41784. * Wait for component to initialize.
  41785. */
  41786. waitComponentInitRawProperty: function (cb) {
  41787. var componentName;
  41788. var data = this.data;
  41789. var el = this.el;
  41790. var self = this;
  41791. if (data.from !== '') { return false; }
  41792. if (!data.property.startsWith(STRING_COMPONENTS)) { return false; }
  41793. componentName = splitDot(data.property)[1];
  41794. if (el.components[componentName]) { return false; }
  41795. el.addEventListener('componentinitialized', function wait (evt) {
  41796. if (evt.detail.name !== componentName) { return; }
  41797. cb();
  41798. // Since the config was created async, create the animation now since we missed it
  41799. // earlier.
  41800. self.animation = anime(self.config);
  41801. el.removeEventListener('componentinitialized', wait);
  41802. });
  41803. return true;
  41804. },
  41805. /**
  41806. * Make sure two animations on the same property don't fight each other.
  41807. * e.g., animation__mouseenter="property: material.opacity"
  41808. * animation__mouseleave="property: material.opacity"
  41809. */
  41810. stopRelatedAnimations: function () {
  41811. var component;
  41812. var componentName;
  41813. for (componentName in this.el.components) {
  41814. component = this.el.components[componentName];
  41815. if (componentName === this.attrName) { continue; }
  41816. if (component.name !== 'animation') { continue; }
  41817. if (!component.animationIsPlaying) { continue; }
  41818. if (component.data.property !== this.data.property) { continue; }
  41819. component.animationIsPlaying = false;
  41820. }
  41821. },
  41822. addEventListeners: function () {
  41823. var data = this.data;
  41824. var el = this.el;
  41825. addEventListeners(el, data.startEvents, this.onStartEvent);
  41826. addEventListeners(el, data.pauseEvents, this.pauseAnimation);
  41827. addEventListeners(el, data.resumeEvents, this.resumeAnimation);
  41828. },
  41829. removeEventListeners: function () {
  41830. var data = this.data;
  41831. var el = this.el;
  41832. removeEventListeners(el, data.startEvents, this.onStartEvent);
  41833. removeEventListeners(el, data.pauseEvents, this.pauseAnimation);
  41834. removeEventListeners(el, data.resumeEvents, this.resumeAnimation);
  41835. },
  41836. setColorConfig: function (from, to) {
  41837. colorHelperFrom.set(from);
  41838. colorHelperTo.set(to);
  41839. from = this.fromColor;
  41840. to = this.toColor;
  41841. from.r = colorHelperFrom.r;
  41842. from.g = colorHelperFrom.g;
  41843. from.b = colorHelperFrom.b;
  41844. to.r = colorHelperTo.r;
  41845. to.g = colorHelperTo.g;
  41846. to.b = colorHelperTo.b;
  41847. }
  41848. });
  41849. /**
  41850. * Given property name, check schema to see what type we are animating.
  41851. * We just care whether the property is a vector.
  41852. */
  41853. function getPropertyType (el, property) {
  41854. var component;
  41855. var componentName;
  41856. var split;
  41857. var propertyName;
  41858. split = property.split('.');
  41859. componentName = split[0];
  41860. propertyName = split[1];
  41861. component = el.components[componentName] || components[componentName];
  41862. // Primitives.
  41863. if (!component) { return null; }
  41864. // Dynamic schema. We only care about vectors anyways.
  41865. if (propertyName && !component.schema[propertyName]) { return null; }
  41866. // Multi-prop.
  41867. if (propertyName) { return component.schema[propertyName].type; }
  41868. // Single-prop.
  41869. return component.schema.type;
  41870. }
  41871. /**
  41872. * Convert object to radians.
  41873. */
  41874. function toRadians (obj) {
  41875. obj.x = THREE.Math.degToRad(obj.x);
  41876. obj.y = THREE.Math.degToRad(obj.y);
  41877. obj.z = THREE.Math.degToRad(obj.z);
  41878. }
  41879. function addEventListeners (el, eventNames, handler) {
  41880. var i;
  41881. for (i = 0; i < eventNames.length; i++) {
  41882. el.addEventListener(eventNames[i], handler);
  41883. }
  41884. }
  41885. function removeEventListeners (el, eventNames, handler) {
  41886. var i;
  41887. for (i = 0; i < eventNames.length; i++) {
  41888. el.removeEventListener(eventNames[i], handler);
  41889. }
  41890. }
  41891. function getRawProperty (el, path) {
  41892. var i;
  41893. var split;
  41894. var value;
  41895. split = splitDot(path);
  41896. value = el;
  41897. for (i = 0; i < split.length; i++) {
  41898. value = value[split[i]];
  41899. }
  41900. if (value === undefined) {
  41901. console.log(el);
  41902. throw new Error('[animation] property (' + path + ') could not be found');
  41903. }
  41904. return value;
  41905. }
  41906. function setRawProperty (el, path, value, type) {
  41907. var i;
  41908. var split;
  41909. var propertyName;
  41910. var targetValue;
  41911. if (path.startsWith('object3D.rotation')) {
  41912. value = THREE.Math.degToRad(value);
  41913. }
  41914. // Walk.
  41915. split = splitDot(path);
  41916. targetValue = el;
  41917. for (i = 0; i < split.length - 1; i++) { targetValue = targetValue[split[i]]; }
  41918. propertyName = split[split.length - 1];
  41919. // Raw color.
  41920. if (type === TYPE_COLOR) {
  41921. if ('r' in targetValue[propertyName]) {
  41922. targetValue[propertyName].r = value.r;
  41923. targetValue[propertyName].g = value.g;
  41924. targetValue[propertyName].b = value.b;
  41925. } else {
  41926. targetValue[propertyName].x = value.r;
  41927. targetValue[propertyName].y = value.g;
  41928. targetValue[propertyName].z = value.b;
  41929. }
  41930. return;
  41931. }
  41932. targetValue[propertyName] = value;
  41933. }
  41934. function splitDot (path) {
  41935. if (path in splitCache) { return splitCache[path]; }
  41936. splitCache[path] = path.split('.');
  41937. return splitCache[path];
  41938. }
  41939. function isRawProperty (data) {
  41940. return data.isRawProperty || data.property.startsWith(STRING_COMPONENTS) ||
  41941. data.property.startsWith(STRING_OBJECT3D);
  41942. }
  41943. },{"../core/component":103,"../lib/three":151,"../utils":176,"super-animejs":35}],53:[function(_dereq_,module,exports){
  41944. var registerComponent = _dereq_('../core/component').registerComponent;
  41945. var THREE = _dereq_('../lib/three');
  41946. /**
  41947. * Camera component.
  41948. * Pairs along with camera system to handle tracking the active camera.
  41949. */
  41950. module.exports.Component = registerComponent('camera', {
  41951. schema: {
  41952. active: {default: true},
  41953. far: {default: 10000},
  41954. fov: {default: 80, min: 0},
  41955. near: {default: 0.005, min: 0},
  41956. spectator: {default: false},
  41957. zoom: {default: 1, min: 0}
  41958. },
  41959. /**
  41960. * Initialize three.js camera and add it to the entity.
  41961. * Add reference from scene to this entity as the camera.
  41962. */
  41963. init: function () {
  41964. var camera;
  41965. var el = this.el;
  41966. // Create camera.
  41967. camera = this.camera = new THREE.PerspectiveCamera();
  41968. el.setObject3D('camera', camera);
  41969. },
  41970. /**
  41971. * Update three.js camera.
  41972. */
  41973. update: function (oldData) {
  41974. var data = this.data;
  41975. var camera = this.camera;
  41976. // Update properties.
  41977. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  41978. camera.far = data.far;
  41979. camera.fov = data.fov;
  41980. camera.near = data.near;
  41981. camera.zoom = data.zoom;
  41982. camera.updateProjectionMatrix();
  41983. this.updateActiveCamera(oldData);
  41984. this.updateSpectatorCamera(oldData);
  41985. },
  41986. updateActiveCamera: function (oldData) {
  41987. var data = this.data;
  41988. var el = this.el;
  41989. var system = this.system;
  41990. // Active property did not change.
  41991. if (oldData && oldData.active === data.active || data.spectator) { return; }
  41992. // If `active` property changes, or first update, handle active camera with system.
  41993. if (data.active && system.activeCameraEl !== el) {
  41994. // Camera enabled. Set camera to this camera.
  41995. system.setActiveCamera(el);
  41996. } else if (!data.active && system.activeCameraEl === el) {
  41997. // Camera disabled. Set camera to another camera.
  41998. system.disableActiveCamera();
  41999. }
  42000. },
  42001. updateSpectatorCamera: function (oldData) {
  42002. var data = this.data;
  42003. var el = this.el;
  42004. var system = this.system;
  42005. // spectator property did not change.
  42006. if (oldData && oldData.spectator === data.spectator) { return; }
  42007. // If `spectator` property changes, or first update, handle spectator camera with system.
  42008. if (data.spectator && system.spectatorCameraEl !== el) {
  42009. // Camera enabled. Set camera to this camera.
  42010. system.setSpectatorCamera(el);
  42011. } else if (!data.spectator && system.spectatorCameraEl === el) {
  42012. // Camera disabled. Set camera to another camera.
  42013. system.disableSpectatorCamera();
  42014. }
  42015. },
  42016. /**
  42017. * Remove camera on remove (callback).
  42018. */
  42019. remove: function () {
  42020. this.el.removeObject3D('camera');
  42021. }
  42022. });
  42023. },{"../core/component":103,"../lib/three":151}],54:[function(_dereq_,module,exports){
  42024. /* global THREE */
  42025. var registerComponent = _dereq_('../core/component').registerComponent;
  42026. var utils = _dereq_('../utils/');
  42027. var bind = utils.bind;
  42028. var EVENTS = {
  42029. CLICK: 'click',
  42030. FUSING: 'fusing',
  42031. MOUSEENTER: 'mouseenter',
  42032. MOUSEDOWN: 'mousedown',
  42033. MOUSELEAVE: 'mouseleave',
  42034. MOUSEUP: 'mouseup'
  42035. };
  42036. var STATES = {
  42037. FUSING: 'cursor-fusing',
  42038. HOVERING: 'cursor-hovering',
  42039. HOVERED: 'cursor-hovered'
  42040. };
  42041. var CANVAS_EVENTS = {
  42042. DOWN: ['mousedown', 'touchstart'],
  42043. UP: ['mouseup', 'touchend']
  42044. };
  42045. var CANVAS_HOVER_CLASS = 'a-mouse-cursor-hover';
  42046. /**
  42047. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  42048. * from the camera and pointing from camera's facing direction, and then only returning the
  42049. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  42050. *
  42051. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  42052. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  42053. * @member {object} intersection - Attributes of the current intersection event, including
  42054. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  42055. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  42056. * emit events when unintersecting.
  42057. */
  42058. module.exports.Component = registerComponent('cursor', {
  42059. dependencies: ['raycaster'],
  42060. schema: {
  42061. downEvents: {default: []},
  42062. fuse: {default: utils.device.isMobile()},
  42063. fuseTimeout: {default: 1500, min: 0},
  42064. mouseCursorStylesEnabled: {default: true},
  42065. upEvents: {default: []},
  42066. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  42067. },
  42068. init: function () {
  42069. var self = this;
  42070. this.fuseTimeout = undefined;
  42071. this.cursorDownEl = null;
  42072. this.intersectedEl = null;
  42073. this.canvasBounds = document.body.getBoundingClientRect();
  42074. // Debounce.
  42075. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  42076. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  42077. }, 500);
  42078. this.eventDetail = {};
  42079. this.intersectedEventDetail = {cursorEl: this.el};
  42080. // Bind methods.
  42081. this.onCursorDown = bind(this.onCursorDown, this);
  42082. this.onCursorUp = bind(this.onCursorUp, this);
  42083. this.onIntersection = bind(this.onIntersection, this);
  42084. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  42085. this.onMouseMove = bind(this.onMouseMove, this);
  42086. },
  42087. update: function (oldData) {
  42088. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  42089. this.updateMouseEventListeners();
  42090. },
  42091. play: function () {
  42092. this.addEventListeners();
  42093. },
  42094. pause: function () {
  42095. this.removeEventListeners();
  42096. },
  42097. remove: function () {
  42098. var el = this.el;
  42099. el.removeState(STATES.HOVERING);
  42100. el.removeState(STATES.FUSING);
  42101. clearTimeout(this.fuseTimeout);
  42102. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  42103. this.removeEventListeners();
  42104. },
  42105. addEventListeners: function () {
  42106. var canvas;
  42107. var data = this.data;
  42108. var el = this.el;
  42109. var self = this;
  42110. function addCanvasListeners () {
  42111. canvas = el.sceneEl.canvas;
  42112. if (data.downEvents.length || data.upEvents.length) { return; }
  42113. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  42114. canvas.addEventListener(downEvent, self.onCursorDown);
  42115. });
  42116. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  42117. canvas.addEventListener(upEvent, self.onCursorUp);
  42118. });
  42119. }
  42120. canvas = el.sceneEl.canvas;
  42121. if (canvas) {
  42122. addCanvasListeners();
  42123. } else {
  42124. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  42125. }
  42126. data.downEvents.forEach(function (downEvent) {
  42127. el.addEventListener(downEvent, self.onCursorDown);
  42128. });
  42129. data.upEvents.forEach(function (upEvent) {
  42130. el.addEventListener(upEvent, self.onCursorUp);
  42131. });
  42132. el.addEventListener('raycaster-intersection', this.onIntersection);
  42133. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42134. el.sceneEl.addEventListener('rendererresize', this.updateCanvasBounds);
  42135. window.addEventListener('resize', this.updateCanvasBounds);
  42136. window.addEventListener('scroll', this.updateCanvasBounds);
  42137. this.updateMouseEventListeners();
  42138. },
  42139. removeEventListeners: function () {
  42140. var canvas;
  42141. var data = this.data;
  42142. var el = this.el;
  42143. var self = this;
  42144. canvas = el.sceneEl.canvas;
  42145. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  42146. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  42147. canvas.removeEventListener(downEvent, self.onCursorDown);
  42148. });
  42149. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  42150. canvas.removeEventListener(upEvent, self.onCursorUp);
  42151. });
  42152. }
  42153. data.downEvents.forEach(function (downEvent) {
  42154. el.removeEventListener(downEvent, self.onCursorDown);
  42155. });
  42156. data.upEvents.forEach(function (upEvent) {
  42157. el.removeEventListener(upEvent, self.onCursorUp);
  42158. });
  42159. el.removeEventListener('raycaster-intersection', this.onIntersection);
  42160. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  42161. canvas.removeEventListener('mousemove', this.onMouseMove);
  42162. canvas.removeEventListener('touchstart', this.onMouseMove);
  42163. canvas.removeEventListener('touchmove', this.onMouseMove);
  42164. el.sceneEl.removeEventListener('rendererresize', this.updateCanvasBounds);
  42165. window.removeEventListener('resize', this.updateCanvasBounds);
  42166. window.removeEventListener('scroll', this.updateCanvasBounds);
  42167. },
  42168. updateMouseEventListeners: function () {
  42169. var canvas;
  42170. var el = this.el;
  42171. canvas = el.sceneEl.canvas;
  42172. canvas.removeEventListener('mousemove', this.onMouseMove);
  42173. canvas.removeEventListener('touchmove', this.onMouseMove);
  42174. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  42175. if (this.data.rayOrigin !== 'mouse') { return; }
  42176. canvas.addEventListener('mousemove', this.onMouseMove, false);
  42177. canvas.addEventListener('touchmove', this.onMouseMove, false);
  42178. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  42179. this.updateCanvasBounds();
  42180. },
  42181. onMouseMove: (function () {
  42182. var direction = new THREE.Vector3();
  42183. var mouse = new THREE.Vector2();
  42184. var origin = new THREE.Vector3();
  42185. var rayCasterConfig = {origin: origin, direction: direction};
  42186. return function (evt) {
  42187. var bounds = this.canvasBounds;
  42188. var camera = this.el.sceneEl.camera;
  42189. var left;
  42190. var point;
  42191. var top;
  42192. camera.parent.updateMatrixWorld();
  42193. // Calculate mouse position based on the canvas element
  42194. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  42195. // Track the first touch for simplicity.
  42196. point = evt.touches.item(0);
  42197. } else {
  42198. point = evt;
  42199. }
  42200. left = point.clientX - bounds.left;
  42201. top = point.clientY - bounds.top;
  42202. mouse.x = (left / bounds.width) * 2 - 1;
  42203. mouse.y = -(top / bounds.height) * 2 + 1;
  42204. origin.setFromMatrixPosition(camera.matrixWorld);
  42205. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  42206. this.el.setAttribute('raycaster', rayCasterConfig);
  42207. if (evt.type === 'touchmove') { evt.preventDefault(); }
  42208. };
  42209. })(),
  42210. /**
  42211. * Trigger mousedown and keep track of the mousedowned entity.
  42212. */
  42213. onCursorDown: function (evt) {
  42214. // Raycast again for touch.
  42215. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  42216. this.onMouseMove(evt);
  42217. this.el.components.raycaster.checkIntersections();
  42218. evt.preventDefault();
  42219. }
  42220. this.twoWayEmit(EVENTS.MOUSEDOWN);
  42221. this.cursorDownEl = this.intersectedEl;
  42222. },
  42223. /**
  42224. * Trigger mouseup if:
  42225. * - Not fusing (mobile has no mouse).
  42226. * - Currently intersecting an entity.
  42227. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  42228. * in case user mousedowned one entity, dragged to another, and mouseupped.
  42229. */
  42230. onCursorUp: function (evt) {
  42231. var data = this.data;
  42232. this.twoWayEmit(EVENTS.MOUSEUP);
  42233. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  42234. // previously cursorUp entity.
  42235. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  42236. this.intersectedEventDetail.intersection = null;
  42237. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  42238. }
  42239. if ((!data.fuse || data.rayOrigin === 'mouse') &&
  42240. this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  42241. this.twoWayEmit(EVENTS.CLICK);
  42242. }
  42243. this.cursorDownEl = null;
  42244. if (evt.type === 'touchend') { evt.preventDefault(); }
  42245. },
  42246. /**
  42247. * Handle intersection.
  42248. */
  42249. onIntersection: function (evt) {
  42250. var currentIntersection;
  42251. var cursorEl = this.el;
  42252. var index;
  42253. var intersectedEl;
  42254. var intersection;
  42255. // Select closest object, excluding the cursor.
  42256. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  42257. intersection = evt.detail.intersections[index];
  42258. intersectedEl = evt.detail.els[index];
  42259. // If cursor is the only intersected object, ignore the event.
  42260. if (!intersectedEl) { return; }
  42261. // Already intersecting this entity.
  42262. if (this.intersectedEl === intersectedEl) { return; }
  42263. // Ignore events further away than active intersection.
  42264. if (this.intersectedEl) {
  42265. currentIntersection = this.el.components.raycaster.getIntersection(this.intersectedEl);
  42266. if (currentIntersection && currentIntersection.distance <= intersection.distance) { return; }
  42267. }
  42268. // Unset current intersection.
  42269. this.clearCurrentIntersection(true);
  42270. this.setIntersection(intersectedEl, intersection);
  42271. },
  42272. /**
  42273. * Handle intersection cleared.
  42274. */
  42275. onIntersectionCleared: function (evt) {
  42276. var clearedEls = evt.detail.clearedEls;
  42277. // Check if the current intersection has ended
  42278. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  42279. this.clearCurrentIntersection();
  42280. },
  42281. setIntersection: function (intersectedEl, intersection) {
  42282. var cursorEl = this.el;
  42283. var data = this.data;
  42284. var self = this;
  42285. // Already intersecting.
  42286. if (this.intersectedEl === intersectedEl) { return; }
  42287. // Set new intersection.
  42288. this.intersectedEl = intersectedEl;
  42289. // Hovering.
  42290. cursorEl.addState(STATES.HOVERING);
  42291. intersectedEl.addState(STATES.HOVERED);
  42292. this.twoWayEmit(EVENTS.MOUSEENTER);
  42293. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  42294. this.el.sceneEl.canvas.classList.add(CANVAS_HOVER_CLASS);
  42295. }
  42296. // Begin fuse if necessary.
  42297. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  42298. cursorEl.addState(STATES.FUSING);
  42299. this.twoWayEmit(EVENTS.FUSING);
  42300. this.fuseTimeout = setTimeout(function fuse () {
  42301. cursorEl.removeState(STATES.FUSING);
  42302. self.twoWayEmit(EVENTS.CLICK);
  42303. }, data.fuseTimeout);
  42304. },
  42305. clearCurrentIntersection: function (ignoreRemaining) {
  42306. var index;
  42307. var intersection;
  42308. var intersections;
  42309. var cursorEl = this.el;
  42310. // Nothing to be cleared.
  42311. if (!this.intersectedEl) { return; }
  42312. // No longer hovering (or fusing).
  42313. this.intersectedEl.removeState(STATES.HOVERED);
  42314. cursorEl.removeState(STATES.HOVERING);
  42315. cursorEl.removeState(STATES.FUSING);
  42316. this.twoWayEmit(EVENTS.MOUSELEAVE);
  42317. if (this.data.mouseCursorStylesEnabled && this.data.rayOrigin === 'mouse') {
  42318. this.el.sceneEl.canvas.classList.remove(CANVAS_HOVER_CLASS);
  42319. }
  42320. // Unset intersected entity (after emitting the event).
  42321. this.intersectedEl = null;
  42322. // Clear fuseTimeout.
  42323. clearTimeout(this.fuseTimeout);
  42324. // Set intersection to another raycasted element if any.
  42325. if (ignoreRemaining === true) { return; }
  42326. intersections = this.el.components.raycaster.intersections;
  42327. if (intersections.length === 0) { return; }
  42328. // Exclude the cursor.
  42329. index = intersections[0].object.el === cursorEl ? 1 : 0;
  42330. intersection = intersections[index];
  42331. if (!intersection) { return; }
  42332. this.setIntersection(intersection.object.el, intersection);
  42333. },
  42334. /**
  42335. * Helper to emit on both the cursor and the intersected entity (if exists).
  42336. */
  42337. twoWayEmit: function (evtName) {
  42338. var el = this.el;
  42339. var intersectedEl = this.intersectedEl;
  42340. var intersection;
  42341. intersection = this.el.components.raycaster.getIntersection(intersectedEl);
  42342. this.eventDetail.intersectedEl = intersectedEl;
  42343. this.eventDetail.intersection = intersection;
  42344. el.emit(evtName, this.eventDetail);
  42345. if (!intersectedEl) { return; }
  42346. this.intersectedEventDetail.intersection = intersection;
  42347. intersectedEl.emit(evtName, this.intersectedEventDetail);
  42348. }
  42349. });
  42350. },{"../core/component":103,"../utils/":176}],55:[function(_dereq_,module,exports){
  42351. var registerComponent = _dereq_('../core/component').registerComponent;
  42352. var bind = _dereq_('../utils/bind');
  42353. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  42354. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  42355. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  42356. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  42357. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  42358. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  42359. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  42360. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  42361. /**
  42362. * Daydream controls.
  42363. * Interface with Daydream controller and map Gamepad events to
  42364. * controller buttons: trackpad, menu, system
  42365. * Load a controller model and highlight the pressed buttons.
  42366. */
  42367. module.exports.Component = registerComponent('daydream-controls', {
  42368. schema: {
  42369. hand: {default: ''}, // This informs the degenerate arm model.
  42370. buttonColor: {type: 'color', default: '#000000'},
  42371. buttonTouchedColor: {type: 'color', default: '#777777'},
  42372. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42373. model: {default: true},
  42374. orientationOffset: {type: 'vec3'},
  42375. armModel: {default: true}
  42376. },
  42377. /**
  42378. * Button IDs:
  42379. * 0 - trackpad
  42380. * 1 - menu (never dispatched on this layer)
  42381. * 2 - system (never dispatched on this layer)
  42382. */
  42383. mapping: {
  42384. axes: {trackpad: [0, 1]},
  42385. buttons: ['trackpad', 'menu', 'system']
  42386. },
  42387. bindMethods: function () {
  42388. this.onModelLoaded = bind(this.onModelLoaded, this);
  42389. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42390. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42391. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42392. this.onAxisMoved = bind(this.onAxisMoved, this);
  42393. },
  42394. init: function () {
  42395. var self = this;
  42396. this.onButtonChanged = bind(this.onButtonChanged, this);
  42397. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  42398. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  42399. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  42400. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  42401. this.controllerPresent = false;
  42402. this.lastControllerCheck = 0;
  42403. this.bindMethods();
  42404. },
  42405. addEventListeners: function () {
  42406. var el = this.el;
  42407. el.addEventListener('buttonchanged', this.onButtonChanged);
  42408. el.addEventListener('buttondown', this.onButtonDown);
  42409. el.addEventListener('buttonup', this.onButtonUp);
  42410. el.addEventListener('touchstart', this.onButtonTouchStart);
  42411. el.addEventListener('touchend', this.onButtonTouchEnd);
  42412. el.addEventListener('model-loaded', this.onModelLoaded);
  42413. el.addEventListener('axismove', this.onAxisMoved);
  42414. this.controllerEventsActive = true;
  42415. },
  42416. removeEventListeners: function () {
  42417. var el = this.el;
  42418. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42419. el.removeEventListener('buttondown', this.onButtonDown);
  42420. el.removeEventListener('buttonup', this.onButtonUp);
  42421. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42422. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42423. el.removeEventListener('model-loaded', this.onModelLoaded);
  42424. el.removeEventListener('axismove', this.onAxisMoved);
  42425. this.controllerEventsActive = false;
  42426. },
  42427. checkIfControllerPresent: function () {
  42428. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  42429. },
  42430. play: function () {
  42431. this.checkIfControllerPresent();
  42432. this.addControllersUpdateListener();
  42433. },
  42434. pause: function () {
  42435. this.removeEventListeners();
  42436. this.removeControllersUpdateListener();
  42437. },
  42438. injectTrackedControls: function () {
  42439. var el = this.el;
  42440. var data = this.data;
  42441. el.setAttribute('tracked-controls', {
  42442. armModel: data.armModel,
  42443. hand: data.hand,
  42444. idPrefix: GAMEPAD_ID_PREFIX,
  42445. orientationOffset: data.orientationOffset
  42446. });
  42447. if (!this.data.model) { return; }
  42448. this.el.setAttribute('obj-model', {
  42449. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  42450. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  42451. });
  42452. },
  42453. addControllersUpdateListener: function () {
  42454. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42455. },
  42456. removeControllersUpdateListener: function () {
  42457. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42458. },
  42459. onControllersUpdate: function () {
  42460. this.checkIfControllerPresent();
  42461. },
  42462. onModelLoaded: function (evt) {
  42463. var controllerObject3D = evt.detail.model;
  42464. var buttonMeshes;
  42465. if (!this.data.model) { return; }
  42466. buttonMeshes = this.buttonMeshes = {};
  42467. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  42468. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  42469. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  42470. // Offset pivot point.
  42471. controllerObject3D.position.set(0, 0, -0.04);
  42472. },
  42473. onAxisMoved: function (evt) {
  42474. emitIfAxesChanged(this, this.mapping.axes, evt);
  42475. },
  42476. onButtonChanged: function (evt) {
  42477. var button = this.mapping.buttons[evt.detail.id];
  42478. if (!button) return;
  42479. // Pass along changed event with button state, using button mapping for convenience.
  42480. this.el.emit(button + 'changed', evt.detail.state);
  42481. },
  42482. updateModel: function (buttonName, evtName) {
  42483. if (!this.data.model) { return; }
  42484. this.updateButtonModel(buttonName, evtName);
  42485. },
  42486. updateButtonModel: function (buttonName, state) {
  42487. var buttonMeshes = this.buttonMeshes;
  42488. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42489. var color;
  42490. switch (state) {
  42491. case 'down':
  42492. color = this.data.buttonHighlightColor;
  42493. break;
  42494. case 'touchstart':
  42495. color = this.data.buttonTouchedColor;
  42496. break;
  42497. default:
  42498. color = this.data.buttonColor;
  42499. }
  42500. buttonMeshes[buttonName].material.color.set(color);
  42501. }
  42502. });
  42503. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],56:[function(_dereq_,module,exports){
  42504. var registerComponent = _dereq_('../core/component').registerComponent;
  42505. var bind = _dereq_('../utils/bind');
  42506. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  42507. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  42508. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  42509. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  42510. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  42511. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  42512. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  42513. var GAMEPAD_ID_PREFIX = 'Gear VR';
  42514. /**
  42515. * Gear VR controls.
  42516. * Interface with Gear VR controller and map Gamepad events to
  42517. * controller buttons: trackpad, trigger
  42518. * Load a controller model and highlight the pressed buttons.
  42519. */
  42520. module.exports.Component = registerComponent('gearvr-controls', {
  42521. schema: {
  42522. hand: {default: ''}, // This informs the degenerate arm model.
  42523. buttonColor: {type: 'color', default: '#000000'},
  42524. buttonTouchedColor: {type: 'color', default: '#777777'},
  42525. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  42526. model: {default: true},
  42527. orientationOffset: {type: 'vec3'},
  42528. armModel: {default: true}
  42529. },
  42530. /**
  42531. * Button IDs:
  42532. * 0 - trackpad
  42533. * 1 - trigger
  42534. */
  42535. mapping: {
  42536. axes: {trackpad: [0, 1]},
  42537. buttons: ['trackpad', 'trigger']
  42538. },
  42539. bindMethods: function () {
  42540. this.onModelLoaded = bind(this.onModelLoaded, this);
  42541. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  42542. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  42543. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  42544. this.onAxisMoved = bind(this.onAxisMoved, this);
  42545. },
  42546. init: function () {
  42547. var self = this;
  42548. this.onButtonChanged = bind(this.onButtonChanged, this);
  42549. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  42550. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  42551. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  42552. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  42553. this.controllerPresent = false;
  42554. this.lastControllerCheck = 0;
  42555. this.bindMethods();
  42556. },
  42557. addEventListeners: function () {
  42558. var el = this.el;
  42559. el.addEventListener('buttonchanged', this.onButtonChanged);
  42560. el.addEventListener('buttondown', this.onButtonDown);
  42561. el.addEventListener('buttonup', this.onButtonUp);
  42562. el.addEventListener('touchstart', this.onButtonTouchStart);
  42563. el.addEventListener('touchend', this.onButtonTouchEnd);
  42564. el.addEventListener('model-loaded', this.onModelLoaded);
  42565. el.addEventListener('axismove', this.onAxisMoved);
  42566. this.controllerEventsActive = true;
  42567. },
  42568. removeEventListeners: function () {
  42569. var el = this.el;
  42570. el.removeEventListener('buttonchanged', this.onButtonChanged);
  42571. el.removeEventListener('buttondown', this.onButtonDown);
  42572. el.removeEventListener('buttonup', this.onButtonUp);
  42573. el.removeEventListener('touchstart', this.onButtonTouchStart);
  42574. el.removeEventListener('touchend', this.onButtonTouchEnd);
  42575. el.removeEventListener('model-loaded', this.onModelLoaded);
  42576. el.removeEventListener('axismove', this.onAxisMoved);
  42577. this.controllerEventsActive = false;
  42578. },
  42579. checkIfControllerPresent: function () {
  42580. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  42581. this.data.hand ? {hand: this.data.hand} : {});
  42582. },
  42583. play: function () {
  42584. this.checkIfControllerPresent();
  42585. this.addControllersUpdateListener();
  42586. },
  42587. pause: function () {
  42588. this.removeEventListeners();
  42589. this.removeControllersUpdateListener();
  42590. },
  42591. injectTrackedControls: function () {
  42592. var el = this.el;
  42593. var data = this.data;
  42594. el.setAttribute('tracked-controls', {
  42595. armModel: data.armModel,
  42596. idPrefix: GAMEPAD_ID_PREFIX,
  42597. orientationOffset: data.orientationOffset
  42598. });
  42599. if (!this.data.model) { return; }
  42600. this.el.setAttribute('obj-model', {
  42601. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  42602. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  42603. });
  42604. },
  42605. addControllersUpdateListener: function () {
  42606. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  42607. },
  42608. removeControllersUpdateListener: function () {
  42609. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  42610. },
  42611. onControllersUpdate: function () {
  42612. this.checkIfControllerPresent();
  42613. },
  42614. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  42615. onModelLoaded: function (evt) {
  42616. var controllerObject3D = evt.detail.model;
  42617. var buttonMeshes;
  42618. if (!this.data.model) { return; }
  42619. buttonMeshes = this.buttonMeshes = {};
  42620. buttonMeshes.trigger = controllerObject3D.children[2];
  42621. buttonMeshes.trackpad = controllerObject3D.children[1];
  42622. },
  42623. onButtonChanged: function (evt) {
  42624. var button = this.mapping.buttons[evt.detail.id];
  42625. if (!button) return;
  42626. // Pass along changed event with button state, using button mapping for convenience.
  42627. this.el.emit(button + 'changed', evt.detail.state);
  42628. },
  42629. onAxisMoved: function (evt) {
  42630. emitIfAxesChanged(this, this.mapping.axes, evt);
  42631. },
  42632. updateModel: function (buttonName, evtName) {
  42633. if (!this.data.model) { return; }
  42634. this.updateButtonModel(buttonName, evtName);
  42635. },
  42636. updateButtonModel: function (buttonName, state) {
  42637. var buttonMeshes = this.buttonMeshes;
  42638. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  42639. var color;
  42640. switch (state) {
  42641. case 'down':
  42642. color = this.data.buttonHighlightColor;
  42643. break;
  42644. case 'touchstart':
  42645. color = this.data.buttonTouchedColor;
  42646. break;
  42647. default:
  42648. color = this.data.buttonColor;
  42649. }
  42650. buttonMeshes[buttonName].material.color.set(color);
  42651. }
  42652. });
  42653. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],57:[function(_dereq_,module,exports){
  42654. var geometries = _dereq_('../core/geometry').geometries;
  42655. var geometryNames = _dereq_('../core/geometry').geometryNames;
  42656. var registerComponent = _dereq_('../core/component').registerComponent;
  42657. var THREE = _dereq_('../lib/three');
  42658. var dummyGeometry = new THREE.Geometry();
  42659. /**
  42660. * Geometry component. Combined with material component to make a mesh in 3D object.
  42661. * Extended with registered geometries.
  42662. */
  42663. module.exports.Component = registerComponent('geometry', {
  42664. schema: {
  42665. buffer: {default: true},
  42666. primitive: {default: 'box', oneOf: geometryNames, schemaChange: true},
  42667. skipCache: {default: false}
  42668. },
  42669. init: function () {
  42670. this.geometry = null;
  42671. },
  42672. /**
  42673. * Talk to geometry system to get or create geometry.
  42674. */
  42675. update: function (previousData) {
  42676. var data = this.data;
  42677. var el = this.el;
  42678. var mesh;
  42679. var system = this.system;
  42680. // Dispose old geometry if we created one.
  42681. if (this.geometry) {
  42682. system.unuseGeometry(previousData);
  42683. this.geometry = null;
  42684. }
  42685. // Create new geometry.
  42686. this.geometry = system.getOrCreateGeometry(data);
  42687. // Set on mesh. If mesh does not exist, create it.
  42688. mesh = el.getObject3D('mesh');
  42689. if (mesh) {
  42690. mesh.geometry = this.geometry;
  42691. } else {
  42692. mesh = new THREE.Mesh();
  42693. mesh.geometry = this.geometry;
  42694. el.setObject3D('mesh', mesh);
  42695. }
  42696. },
  42697. /**
  42698. * Tell geometry system that entity is no longer using the geometry.
  42699. * Unset the geometry on the mesh
  42700. */
  42701. remove: function () {
  42702. this.system.unuseGeometry(this.data);
  42703. this.el.getObject3D('mesh').geometry = dummyGeometry;
  42704. this.geometry = null;
  42705. },
  42706. /**
  42707. * Update geometry component schema based on geometry type.
  42708. */
  42709. updateSchema: function (data) {
  42710. var currentGeometryType = this.oldData && this.oldData.primitive;
  42711. var newGeometryType = data.primitive;
  42712. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  42713. // Geometry has no schema.
  42714. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  42715. // Nothing has changed.
  42716. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  42717. this.extendSchema(schema);
  42718. }
  42719. });
  42720. },{"../core/component":103,"../core/geometry":104,"../lib/three":151}],58:[function(_dereq_,module,exports){
  42721. var registerComponent = _dereq_('../core/component').registerComponent;
  42722. var THREE = _dereq_('../lib/three');
  42723. var utils = _dereq_('../utils/');
  42724. var warn = utils.debug('components:gltf-model:warn');
  42725. /**
  42726. * glTF model loader.
  42727. */
  42728. module.exports.Component = registerComponent('gltf-model', {
  42729. schema: {type: 'model'},
  42730. init: function () {
  42731. var dracoLoader = this.system.getDRACOLoader();
  42732. this.model = null;
  42733. this.loader = new THREE.GLTFLoader();
  42734. if (dracoLoader) {
  42735. this.loader.setDRACOLoader(dracoLoader);
  42736. }
  42737. },
  42738. update: function () {
  42739. var self = this;
  42740. var el = this.el;
  42741. var src = this.data;
  42742. if (!src) { return; }
  42743. this.remove();
  42744. this.loader.load(src, function gltfLoaded (gltfModel) {
  42745. self.model = gltfModel.scene || gltfModel.scenes[0];
  42746. self.model.animations = gltfModel.animations;
  42747. el.setObject3D('mesh', self.model);
  42748. el.emit('model-loaded', {format: 'gltf', model: self.model});
  42749. }, undefined /* onProgress */, function gltfFailed (error) {
  42750. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  42751. warn(message);
  42752. el.emit('model-error', {format: 'gltf', src: src});
  42753. });
  42754. },
  42755. remove: function () {
  42756. if (!this.model) { return; }
  42757. this.el.removeObject3D('mesh');
  42758. }
  42759. });
  42760. },{"../core/component":103,"../lib/three":151,"../utils/":176}],59:[function(_dereq_,module,exports){
  42761. /* global THREE */
  42762. var registerComponent = _dereq_('../core/component').registerComponent;
  42763. // Found at https://github.com/aframevr/assets.
  42764. var MODEL_URLS = {
  42765. left: 'https://cdn.aframe.io/controllers/hands/leftHand.glb',
  42766. right: 'https://cdn.aframe.io/controllers/hands/rightHand.glb'
  42767. };
  42768. // Poses.
  42769. var ANIMATIONS = {
  42770. open: 'Open',
  42771. // point: grip active, trackpad surface active, trigger inactive.
  42772. point: 'Point',
  42773. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  42774. pointThumb: 'Point + Thumb',
  42775. // fist: grip active, trigger active, trackpad surface active.
  42776. fist: 'Fist',
  42777. // hold: trigger active, grip inactive.
  42778. hold: 'Hold',
  42779. // thumbUp: grip active, trigger active, trackpad surface inactive.
  42780. thumbUp: 'Thumb Up'
  42781. };
  42782. // Map animation to public events for the API.
  42783. var EVENTS = {};
  42784. EVENTS[ANIMATIONS.fist] = 'grip';
  42785. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  42786. EVENTS[ANIMATIONS.point] = 'pointing';
  42787. EVENTS[ANIMATIONS.thumb] = 'thumb';
  42788. /**
  42789. * Hand controls component that abstracts 6DoF controls:
  42790. * oculus-touch-controls, vive-controls, windows-motion-controls.
  42791. *
  42792. * Originally meant to be a sample implementation of applications-specific controls that
  42793. * abstracts multiple types of controllers.
  42794. *
  42795. * Auto-detect appropriate controller.
  42796. * Handle common events coming from the detected vendor-specific controls.
  42797. * Translate button events to semantic hand-related event names:
  42798. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  42799. * Load hand model with gestures that are applied based on the button pressed.
  42800. *
  42801. * @property {string} Hand mapping (`left`, `right`).
  42802. */
  42803. module.exports.Component = registerComponent('hand-controls', {
  42804. schema: {default: 'left'},
  42805. init: function () {
  42806. var self = this;
  42807. var el = this.el;
  42808. // Current pose.
  42809. this.gesture = ANIMATIONS.open;
  42810. // Active buttons populated by events provided by the attached controls.
  42811. this.pressedButtons = {};
  42812. this.touchedButtons = {};
  42813. this.loader = new THREE.GLTFLoader();
  42814. this.loader.setCrossOrigin('anonymous');
  42815. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  42816. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  42817. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  42818. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  42819. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  42820. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  42821. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  42822. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  42823. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  42824. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  42825. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  42826. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  42827. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  42828. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  42829. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  42830. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  42831. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  42832. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  42833. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  42834. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  42835. el.addEventListener('controllerconnected', this.onControllerConnected);
  42836. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  42837. // Hidden by default.
  42838. el.object3D.visible = false;
  42839. },
  42840. play: function () {
  42841. this.addEventListeners();
  42842. },
  42843. pause: function () {
  42844. this.removeEventListeners();
  42845. },
  42846. tick: function (time, delta) {
  42847. var mesh = this.el.getObject3D('mesh');
  42848. if (!mesh || !mesh.mixer) { return; }
  42849. mesh.mixer.update(delta / 1000);
  42850. },
  42851. addEventListeners: function () {
  42852. var el = this.el;
  42853. el.addEventListener('gripdown', this.onGripDown);
  42854. el.addEventListener('gripup', this.onGripUp);
  42855. el.addEventListener('trackpaddown', this.onTrackpadDown);
  42856. el.addEventListener('trackpadup', this.onTrackpadUp);
  42857. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42858. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42859. el.addEventListener('triggerdown', this.onTriggerDown);
  42860. el.addEventListener('triggerup', this.onTriggerUp);
  42861. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  42862. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  42863. el.addEventListener('griptouchstart', this.onGripTouchStart);
  42864. el.addEventListener('griptouchend', this.onGripTouchEnd);
  42865. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  42866. el.addEventListener('thumbstickup', this.onThumbstickUp);
  42867. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  42868. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  42869. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42870. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42871. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42872. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42873. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42874. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42875. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42876. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42877. },
  42878. removeEventListeners: function () {
  42879. var el = this.el;
  42880. el.removeEventListener('gripdown', this.onGripDown);
  42881. el.removeEventListener('gripup', this.onGripUp);
  42882. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  42883. el.removeEventListener('trackpadup', this.onTrackpadUp);
  42884. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  42885. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  42886. el.removeEventListener('triggerdown', this.onTriggerDown);
  42887. el.removeEventListener('triggerup', this.onTriggerUp);
  42888. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  42889. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  42890. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  42891. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  42892. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  42893. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  42894. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  42895. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  42896. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  42897. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  42898. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  42899. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  42900. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  42901. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  42902. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  42903. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  42904. },
  42905. /**
  42906. * Update handler. More like the `init` handler since the only property is the hand, and
  42907. * that won't be changing much.
  42908. */
  42909. update: function (previousHand) {
  42910. var controlConfiguration;
  42911. var el = this.el;
  42912. var hand = this.data;
  42913. var self = this;
  42914. // Get common configuration to abstract different vendor controls.
  42915. controlConfiguration = {
  42916. hand: hand,
  42917. model: false,
  42918. orientationOffset: {x: 0, y: 0, z: hand === 'left' ? 90 : -90}
  42919. };
  42920. // Set model.
  42921. if (hand !== previousHand) {
  42922. this.loader.load(MODEL_URLS[hand], function (gltf) {
  42923. var mesh = gltf.scene.children[0];
  42924. mesh.mixer = new THREE.AnimationMixer(mesh);
  42925. self.clips = gltf.animations;
  42926. el.setObject3D('mesh', mesh);
  42927. mesh.position.set(0, 0, 0);
  42928. mesh.rotation.set(0, 0, 0);
  42929. el.setAttribute('vive-controls', controlConfiguration);
  42930. el.setAttribute('oculus-touch-controls', controlConfiguration);
  42931. el.setAttribute('windows-motion-controls', controlConfiguration);
  42932. });
  42933. }
  42934. },
  42935. remove: function () {
  42936. this.el.removeObject3D('mesh');
  42937. },
  42938. /**
  42939. * Play model animation, based on which button was pressed and which kind of event.
  42940. *
  42941. * 1. Process buttons.
  42942. * 2. Determine gesture (this.determineGesture()).
  42943. * 3. Animation gesture (this.animationGesture()).
  42944. * 4. Emit gesture events (this.emitGestureEvents()).
  42945. *
  42946. * @param {string} button - Name of the button.
  42947. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  42948. */
  42949. handleButton: function (button, evt) {
  42950. var lastGesture;
  42951. var isPressed = evt === 'down';
  42952. var isTouched = evt === 'touchstart';
  42953. // Update objects.
  42954. if (evt.indexOf('touch') === 0) {
  42955. // Update touch object.
  42956. if (isTouched === this.touchedButtons[button]) { return; }
  42957. this.touchedButtons[button] = isTouched;
  42958. } else {
  42959. // Update button object.
  42960. if (isPressed === this.pressedButtons[button]) { return; }
  42961. this.pressedButtons[button] = isPressed;
  42962. }
  42963. // Determine the gesture.
  42964. lastGesture = this.gesture;
  42965. this.gesture = this.determineGesture();
  42966. // Same gesture.
  42967. if (this.gesture === lastGesture) { return; }
  42968. // Animate gesture.
  42969. this.animateGesture(this.gesture, lastGesture);
  42970. // Emit events.
  42971. this.emitGestureEvents(this.gesture, lastGesture);
  42972. },
  42973. /**
  42974. * Determine which pose hand should be in considering active and touched buttons.
  42975. */
  42976. determineGesture: function () {
  42977. var gesture;
  42978. var isGripActive = this.pressedButtons['grip'];
  42979. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  42980. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  42981. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  42982. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  42983. var isVive = isViveController(this.el.components['tracked-controls']);
  42984. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  42985. if (isVive) {
  42986. if (isGripActive || isTriggerActive) {
  42987. gesture = ANIMATIONS.fist;
  42988. } else if (isTrackpadActive) {
  42989. gesture = ANIMATIONS.point;
  42990. }
  42991. } else {
  42992. if (isGripActive) {
  42993. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  42994. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  42995. } else {
  42996. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  42997. }
  42998. } else if (isTriggerActive) {
  42999. gesture = ANIMATIONS.hold;
  43000. }
  43001. }
  43002. return gesture;
  43003. },
  43004. /**
  43005. * Play corresponding clip to a gesture
  43006. */
  43007. getClip: function (gesture) {
  43008. var clip;
  43009. var i;
  43010. for (i = 0; i < this.clips.length; i++) {
  43011. clip = this.clips[i];
  43012. if (clip.name !== gesture) { continue; }
  43013. return clip;
  43014. }
  43015. },
  43016. /**
  43017. * Play gesture animation.
  43018. *
  43019. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  43020. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  43021. */
  43022. animateGesture: function (gesture, lastGesture) {
  43023. if (gesture) {
  43024. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  43025. return;
  43026. }
  43027. // If no gesture, then reverse the current gesture back to open pose.
  43028. this.playAnimation(lastGesture, lastGesture, true);
  43029. },
  43030. /**
  43031. * Emit `hand-controls`-specific events.
  43032. */
  43033. emitGestureEvents: function (gesture, lastGesture) {
  43034. var el = this.el;
  43035. var eventName;
  43036. if (lastGesture === gesture) { return; }
  43037. // Emit event for lastGesture not inactive.
  43038. eventName = getGestureEventName(lastGesture, false);
  43039. if (eventName) { el.emit(eventName); }
  43040. // Emit event for current gesture now active.
  43041. eventName = getGestureEventName(gesture, true);
  43042. if (eventName) { el.emit(eventName); }
  43043. },
  43044. /**
  43045. * Play hand animation based on button state.
  43046. *
  43047. * @param {string} gesture - Name of the animation as specified by the model.
  43048. * @param {string} lastGesture - Previous pose.
  43049. * @param {boolean} reverse - Whether animation should play in reverse.
  43050. */
  43051. playAnimation: function (gesture, lastGesture, reverse) {
  43052. var clip;
  43053. var fromAction;
  43054. var mesh = this.el.getObject3D('mesh');
  43055. var toAction;
  43056. if (!mesh) { return; }
  43057. // Stop all current animations.
  43058. mesh.mixer.stopAllAction();
  43059. // Grab clip action.
  43060. clip = this.getClip(gesture);
  43061. toAction = mesh.mixer.clipAction(clip);
  43062. toAction.clampWhenFinished = true;
  43063. toAction.loop = THREE.LoopRepeat;
  43064. toAction.repetitions = 0;
  43065. toAction.timeScale = reverse ? -1 : 1;
  43066. toAction.time = reverse ? clip.duration : 0;
  43067. toAction.weight = 1;
  43068. // No gesture to gesture or gesture to no gesture.
  43069. if (!lastGesture || gesture === lastGesture) {
  43070. // Stop all current animations.
  43071. mesh.mixer.stopAllAction();
  43072. // Play animation.
  43073. toAction.play();
  43074. return;
  43075. }
  43076. // Animate or crossfade from gesture to gesture.
  43077. clip = this.getClip(lastGesture);
  43078. fromAction = mesh.mixer.clipAction(clip);
  43079. fromAction.weight = 0.15;
  43080. fromAction.play();
  43081. toAction.play();
  43082. fromAction.crossFadeTo(toAction, 0.15, true);
  43083. }
  43084. });
  43085. /**
  43086. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  43087. *
  43088. * @param {string} gesture
  43089. * @param {boolean} active
  43090. */
  43091. function getGestureEventName (gesture, active) {
  43092. var eventName;
  43093. if (!gesture) { return; }
  43094. eventName = EVENTS[gesture];
  43095. if (eventName === 'grip') {
  43096. return eventName + (active ? 'close' : 'open');
  43097. }
  43098. if (eventName === 'point' || eventName === 'thumb') {
  43099. return eventName + (active ? 'up' : 'down');
  43100. }
  43101. if (eventName === 'pointing' || eventName === 'pistol') {
  43102. return eventName + (active ? 'start' : 'end');
  43103. }
  43104. return;
  43105. }
  43106. function isViveController (trackedControls) {
  43107. var controllerId = trackedControls && trackedControls.controller &&
  43108. trackedControls.controller.id;
  43109. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  43110. }
  43111. },{"../core/component":103}],60:[function(_dereq_,module,exports){
  43112. _dereq_('./animation');
  43113. _dereq_('./camera');
  43114. _dereq_('./cursor');
  43115. _dereq_('./daydream-controls');
  43116. _dereq_('./gearvr-controls');
  43117. _dereq_('./geometry');
  43118. _dereq_('./gltf-model');
  43119. _dereq_('./hand-controls');
  43120. _dereq_('./laser-controls');
  43121. _dereq_('./light');
  43122. _dereq_('./line');
  43123. _dereq_('./link');
  43124. _dereq_('./look-controls');
  43125. _dereq_('./material');
  43126. _dereq_('./obj-model');
  43127. _dereq_('./oculus-go-controls');
  43128. _dereq_('./oculus-touch-controls');
  43129. _dereq_('./position');
  43130. _dereq_('./raycaster');
  43131. _dereq_('./rotation');
  43132. _dereq_('./scale');
  43133. _dereq_('./shadow');
  43134. _dereq_('./sound');
  43135. _dereq_('./text');
  43136. _dereq_('./tracked-controls');
  43137. _dereq_('./tracked-controls-webvr');
  43138. _dereq_('./tracked-controls-webxr');
  43139. _dereq_('./visible');
  43140. _dereq_('./vive-controls');
  43141. _dereq_('./vive-focus-controls');
  43142. _dereq_('./wasd-controls');
  43143. _dereq_('./windows-motion-controls');
  43144. _dereq_('./scene/background');
  43145. _dereq_('./scene/debug');
  43146. _dereq_('./scene/embedded');
  43147. _dereq_('./scene/inspector');
  43148. _dereq_('./scene/fog');
  43149. _dereq_('./scene/keyboard-shortcuts');
  43150. _dereq_('./scene/pool');
  43151. _dereq_('./scene/screenshot');
  43152. _dereq_('./scene/stats');
  43153. _dereq_('./scene/vr-mode-ui');
  43154. },{"./animation":52,"./camera":53,"./cursor":54,"./daydream-controls":55,"./gearvr-controls":56,"./geometry":57,"./gltf-model":58,"./hand-controls":59,"./laser-controls":61,"./light":62,"./line":63,"./link":64,"./look-controls":65,"./material":66,"./obj-model":67,"./oculus-go-controls":68,"./oculus-touch-controls":69,"./position":70,"./raycaster":71,"./rotation":72,"./scale":73,"./scene/background":74,"./scene/debug":75,"./scene/embedded":76,"./scene/fog":77,"./scene/inspector":78,"./scene/keyboard-shortcuts":79,"./scene/pool":80,"./scene/screenshot":81,"./scene/stats":82,"./scene/vr-mode-ui":83,"./shadow":84,"./sound":85,"./text":86,"./tracked-controls":89,"./tracked-controls-webvr":87,"./tracked-controls-webxr":88,"./visible":90,"./vive-controls":91,"./vive-focus-controls":92,"./wasd-controls":93,"./windows-motion-controls":94}],61:[function(_dereq_,module,exports){
  43155. var registerComponent = _dereq_('../core/component').registerComponent;
  43156. var utils = _dereq_('../utils/');
  43157. registerComponent('laser-controls', {
  43158. schema: {
  43159. hand: {default: 'right'},
  43160. model: {default: true},
  43161. defaultModelColor: {type: 'color', default: 'grey'}
  43162. },
  43163. init: function () {
  43164. var config = this.config;
  43165. var data = this.data;
  43166. var el = this.el;
  43167. var self = this;
  43168. var modelEnabled = this.data.model && !this.el.sceneEl.hasWebXR;
  43169. var controlsConfiguration = {hand: data.hand, model: modelEnabled};
  43170. // Set all controller models.
  43171. el.setAttribute('daydream-controls', controlsConfiguration);
  43172. el.setAttribute('gearvr-controls', controlsConfiguration);
  43173. el.setAttribute('oculus-go-controls', controlsConfiguration);
  43174. el.setAttribute('oculus-touch-controls', controlsConfiguration);
  43175. el.setAttribute('vive-controls', controlsConfiguration);
  43176. el.setAttribute('vive-focus-controls', controlsConfiguration);
  43177. el.setAttribute('windows-motion-controls', controlsConfiguration);
  43178. // WebXR doesn't allow to discriminate between controllers, a default model is used.
  43179. if (this.data.model && this.el.sceneEl.hasWebXR) { this.initDefaultModel(); }
  43180. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  43181. el.addEventListener('controllerconnected', createRay);
  43182. el.addEventListener('controllerdisconnected', hideRay);
  43183. el.addEventListener('controllermodelready', function (evt) {
  43184. createRay(evt);
  43185. self.modelReady = true;
  43186. });
  43187. function createRay (evt) {
  43188. var controllerConfig = config[evt.detail.name];
  43189. if (!controllerConfig) { return; }
  43190. // Show the line unless a particular config opts to hide it, until a controllermodelready
  43191. // event comes through.
  43192. var raycasterConfig = utils.extend({
  43193. showLine: true
  43194. }, controllerConfig.raycaster || {});
  43195. // The controllermodelready event contains a rayOrigin that takes into account
  43196. // offsets specific to the loaded model.
  43197. if (evt.detail.rayOrigin) {
  43198. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  43199. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  43200. raycasterConfig.showLine = true;
  43201. }
  43202. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  43203. // config applied from a controllermodelready event.
  43204. if (evt.detail.rayOrigin || !self.modelReady) {
  43205. el.setAttribute('raycaster', raycasterConfig);
  43206. } else {
  43207. el.setAttribute('raycaster', 'showLine', true);
  43208. }
  43209. el.setAttribute('cursor', utils.extend({
  43210. fuse: false
  43211. }, controllerConfig.cursor));
  43212. }
  43213. function hideRay () {
  43214. el.setAttribute('raycaster', 'showLine', false);
  43215. }
  43216. },
  43217. config: {
  43218. 'daydream-controls': {
  43219. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  43220. },
  43221. 'gearvr-controls': {
  43222. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43223. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43224. },
  43225. 'oculus-go-controls': {
  43226. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43227. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  43228. },
  43229. 'oculus-touch-controls': {
  43230. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43231. raycaster: {origin: {x: 0, y: 0, z: 0}}
  43232. },
  43233. 'vive-controls': {
  43234. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  43235. },
  43236. 'vive-focus-controls': {
  43237. cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
  43238. },
  43239. 'windows-motion-controls': {
  43240. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  43241. raycaster: {showLine: false}
  43242. }
  43243. },
  43244. initDefaultModel: function () {
  43245. var modelEl = this.modelEl = document.createElement('a-entity');
  43246. modelEl.setAttribute('geometry', {
  43247. primitive: 'sphere',
  43248. radius: 0.03
  43249. });
  43250. modelEl.setAttribute('material', {color: this.data.color});
  43251. this.el.appendChild(modelEl);
  43252. }
  43253. });
  43254. },{"../core/component":103,"../utils/":176}],62:[function(_dereq_,module,exports){
  43255. var bind = _dereq_('../utils/bind');
  43256. var diff = _dereq_('../utils').diff;
  43257. var debug = _dereq_('../utils/debug');
  43258. var registerComponent = _dereq_('../core/component').registerComponent;
  43259. var THREE = _dereq_('../lib/three');
  43260. var degToRad = THREE.Math.degToRad;
  43261. var warn = debug('components:light:warn');
  43262. /**
  43263. * Light component.
  43264. */
  43265. module.exports.Component = registerComponent('light', {
  43266. schema: {
  43267. angle: {default: 60, if: {type: ['spot']}},
  43268. color: {type: 'color'},
  43269. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  43270. decay: {default: 1, if: {type: ['point', 'spot']}},
  43271. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  43272. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  43273. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  43274. type: {
  43275. default: 'directional',
  43276. oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot'],
  43277. schemaChange: true
  43278. },
  43279. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  43280. // Shadows.
  43281. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  43282. shadowBias: {default: 0, if: {castShadow: true}},
  43283. shadowCameraFar: {default: 500, if: {castShadow: true}},
  43284. shadowCameraFov: {default: 90, if: {castShadow: true}},
  43285. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  43286. shadowCameraTop: {default: 5, if: {castShadow: true}},
  43287. shadowCameraRight: {default: 5, if: {castShadow: true}},
  43288. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  43289. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  43290. shadowCameraVisible: {default: false, if: {castShadow: true}},
  43291. shadowMapHeight: {default: 512, if: {castShadow: true}},
  43292. shadowMapWidth: {default: 512, if: {castShadow: true}},
  43293. shadowRadius: {default: 1, if: {castShadow: true}}
  43294. },
  43295. /**
  43296. * Notifies scene a light has been added to remove default lighting.
  43297. */
  43298. init: function () {
  43299. var el = this.el;
  43300. this.light = null;
  43301. this.defaultTarget = null;
  43302. this.rendererSystem = this.el.sceneEl.systems.renderer;
  43303. this.system.registerLight(el);
  43304. },
  43305. /**
  43306. * (Re)create or update light.
  43307. */
  43308. update: function (oldData) {
  43309. var data = this.data;
  43310. var diffData = diff(data, oldData);
  43311. var light = this.light;
  43312. var rendererSystem = this.rendererSystem;
  43313. var self = this;
  43314. // Existing light.
  43315. if (light && !('type' in diffData)) {
  43316. var shadowsLoaded = false;
  43317. // Light type has not changed. Update light.
  43318. Object.keys(diffData).forEach(function (key) {
  43319. var value = data[key];
  43320. switch (key) {
  43321. case 'color': {
  43322. light.color.set(value);
  43323. rendererSystem.applyColorCorrection(light.color);
  43324. break;
  43325. }
  43326. case 'groundColor': {
  43327. light.groundColor.set(value);
  43328. rendererSystem.applyColorCorrection(light.groundColor);
  43329. break;
  43330. }
  43331. case 'angle': {
  43332. light.angle = degToRad(value);
  43333. break;
  43334. }
  43335. case 'target': {
  43336. // Reset target if selector is null.
  43337. if (value === null) {
  43338. if (data.type === 'spot' || data.type === 'directional') {
  43339. light.target = self.defaultTarget;
  43340. }
  43341. } else {
  43342. // Target specified, set target to entity's `object3D` when it is loaded.
  43343. if (value.hasLoaded) {
  43344. self.onSetTarget(value, light);
  43345. } else {
  43346. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  43347. }
  43348. }
  43349. break;
  43350. }
  43351. case 'castShadow':
  43352. case 'shadowBias':
  43353. case 'shadowCameraFar':
  43354. case 'shadowCameraFov':
  43355. case 'shadowCameraNear':
  43356. case 'shadowCameraTop':
  43357. case 'shadowCameraRight':
  43358. case 'shadowCameraBottom':
  43359. case 'shadowCameraLeft':
  43360. case 'shadowCameraVisible':
  43361. case 'shadowMapHeight':
  43362. case 'shadowMapWidth':
  43363. case 'shadowRadius':
  43364. if (!shadowsLoaded) {
  43365. self.updateShadow();
  43366. shadowsLoaded = true;
  43367. }
  43368. break;
  43369. default: {
  43370. light[key] = value;
  43371. }
  43372. }
  43373. });
  43374. return;
  43375. }
  43376. // No light yet or light type has changed. Create and add light.
  43377. this.setLight(this.data);
  43378. this.updateShadow();
  43379. },
  43380. setLight: function (data) {
  43381. var el = this.el;
  43382. var newLight = this.getLight(data);
  43383. if (newLight) {
  43384. if (this.light) {
  43385. el.removeObject3D('light');
  43386. }
  43387. this.light = newLight;
  43388. this.light.el = el;
  43389. el.setObject3D('light', this.light);
  43390. // HACK solution for issue #1624
  43391. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  43392. el.getObject3D('light').translateY(-1);
  43393. }
  43394. // set and position default lighttarget as a child to enable spotlight orientation
  43395. if (data.type === 'spot') {
  43396. el.setObject3D('light-target', this.defaultTarget);
  43397. el.getObject3D('light-target').position.set(0, 0, -1);
  43398. }
  43399. }
  43400. },
  43401. /**
  43402. * Updates shadow-related properties on the current light.
  43403. */
  43404. updateShadow: function () {
  43405. var el = this.el;
  43406. var data = this.data;
  43407. var light = this.light;
  43408. light.castShadow = data.castShadow;
  43409. // Shadow camera helper.
  43410. var cameraHelper = el.getObject3D('cameraHelper');
  43411. if (data.shadowCameraVisible && !cameraHelper) {
  43412. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  43413. } else if (!data.shadowCameraVisible && cameraHelper) {
  43414. el.removeObject3D('cameraHelper');
  43415. }
  43416. if (!data.castShadow) { return light; }
  43417. // Shadow appearance.
  43418. light.shadow.bias = data.shadowBias;
  43419. light.shadow.radius = data.shadowRadius;
  43420. light.shadow.mapSize.height = data.shadowMapHeight;
  43421. light.shadow.mapSize.width = data.shadowMapWidth;
  43422. // Shadow camera.
  43423. light.shadow.camera.near = data.shadowCameraNear;
  43424. light.shadow.camera.far = data.shadowCameraFar;
  43425. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  43426. light.shadow.camera.top = data.shadowCameraTop;
  43427. light.shadow.camera.right = data.shadowCameraRight;
  43428. light.shadow.camera.bottom = data.shadowCameraBottom;
  43429. light.shadow.camera.left = data.shadowCameraLeft;
  43430. } else {
  43431. light.shadow.camera.fov = data.shadowCameraFov;
  43432. }
  43433. light.shadow.camera.updateProjectionMatrix();
  43434. if (cameraHelper) { cameraHelper.update(); }
  43435. },
  43436. /**
  43437. * Creates a new three.js light object given data object defining the light.
  43438. *
  43439. * @param {object} data
  43440. */
  43441. getLight: function (data) {
  43442. var angle = data.angle;
  43443. var color = new THREE.Color(data.color);
  43444. this.rendererSystem.applyColorCorrection(color);
  43445. color = color.getHex();
  43446. var decay = data.decay;
  43447. var distance = data.distance;
  43448. var groundColor = new THREE.Color(data.groundColor);
  43449. this.rendererSystem.applyColorCorrection(groundColor);
  43450. groundColor = groundColor.getHex();
  43451. var intensity = data.intensity;
  43452. var type = data.type;
  43453. var target = data.target;
  43454. var light = null;
  43455. switch (type.toLowerCase()) {
  43456. case 'ambient': {
  43457. return new THREE.AmbientLight(color, intensity);
  43458. }
  43459. case 'directional': {
  43460. light = new THREE.DirectionalLight(color, intensity);
  43461. this.defaultTarget = light.target;
  43462. if (target) {
  43463. if (target.hasLoaded) {
  43464. this.onSetTarget(target, light);
  43465. } else {
  43466. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43467. }
  43468. }
  43469. return light;
  43470. }
  43471. case 'hemisphere': {
  43472. return new THREE.HemisphereLight(color, groundColor, intensity);
  43473. }
  43474. case 'point': {
  43475. return new THREE.PointLight(color, intensity, distance, decay);
  43476. }
  43477. case 'spot': {
  43478. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  43479. this.defaultTarget = light.target;
  43480. if (target) {
  43481. if (target.hasLoaded) {
  43482. this.onSetTarget(target, light);
  43483. } else {
  43484. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  43485. }
  43486. }
  43487. return light;
  43488. }
  43489. default: {
  43490. warn('%s is not a valid light type. ' +
  43491. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  43492. }
  43493. }
  43494. },
  43495. onSetTarget: function (targetEl, light) {
  43496. light.target = targetEl.object3D;
  43497. },
  43498. /**
  43499. * Remove light on remove (callback).
  43500. */
  43501. remove: function () {
  43502. var el = this.el;
  43503. el.removeObject3D('light');
  43504. if (el.getObject3D('cameraHelper')) {
  43505. el.removeObject3D('cameraHelper');
  43506. }
  43507. }
  43508. });
  43509. },{"../core/component":103,"../lib/three":151,"../utils":176,"../utils/bind":170,"../utils/debug":172}],63:[function(_dereq_,module,exports){
  43510. /* global THREE */
  43511. var registerComponent = _dereq_('../core/component').registerComponent;
  43512. module.exports.Component = registerComponent('line', {
  43513. schema: {
  43514. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43515. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  43516. color: {type: 'color', default: '#74BEC1'},
  43517. opacity: {type: 'number', default: 1},
  43518. visible: {default: true}
  43519. },
  43520. multiple: true,
  43521. init: function () {
  43522. var data = this.data;
  43523. var geometry;
  43524. var material;
  43525. this.rendererSystem = this.el.sceneEl.systems.renderer;
  43526. material = this.material = new THREE.LineBasicMaterial({
  43527. color: data.color,
  43528. opacity: data.opacity,
  43529. transparent: data.opacity < 1,
  43530. visible: data.visible
  43531. });
  43532. geometry = this.geometry = new THREE.BufferGeometry();
  43533. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  43534. this.rendererSystem.applyColorCorrection(material.color);
  43535. this.line = new THREE.Line(geometry, material);
  43536. this.el.setObject3D(this.attrName, this.line);
  43537. },
  43538. update: function (oldData) {
  43539. var data = this.data;
  43540. var geometry = this.geometry;
  43541. var geoNeedsUpdate = false;
  43542. var material = this.material;
  43543. var positionArray = geometry.attributes.position.array;
  43544. // Update geometry.
  43545. if (!isEqualVec3(data.start, oldData.start)) {
  43546. positionArray[0] = data.start.x;
  43547. positionArray[1] = data.start.y;
  43548. positionArray[2] = data.start.z;
  43549. geoNeedsUpdate = true;
  43550. }
  43551. if (!isEqualVec3(data.end, oldData.end)) {
  43552. positionArray[3] = data.end.x;
  43553. positionArray[4] = data.end.y;
  43554. positionArray[5] = data.end.z;
  43555. geoNeedsUpdate = true;
  43556. }
  43557. if (geoNeedsUpdate) {
  43558. geometry.attributes.position.needsUpdate = true;
  43559. geometry.computeBoundingSphere();
  43560. }
  43561. material.color.setStyle(data.color);
  43562. this.rendererSystem.applyColorCorrection(material.color);
  43563. material.opacity = data.opacity;
  43564. material.transparent = data.opacity < 1;
  43565. material.visible = data.visible;
  43566. },
  43567. remove: function () {
  43568. this.el.removeObject3D('line', this.line);
  43569. }
  43570. });
  43571. function isEqualVec3 (a, b) {
  43572. if (!a || !b) { return false; }
  43573. return (a.x === b.x && a.y === b.y && a.z === b.z);
  43574. }
  43575. },{"../core/component":103}],64:[function(_dereq_,module,exports){
  43576. var registerComponent = _dereq_('../core/component').registerComponent;
  43577. var registerShader = _dereq_('../core/shader').registerShader;
  43578. var THREE = _dereq_('../lib/three');
  43579. /**
  43580. * Link component. Connect experiences and traverse between them in VR
  43581. *
  43582. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  43583. */
  43584. module.exports.Component = registerComponent('link', {
  43585. schema: {
  43586. backgroundColor: {default: 'red', type: 'color'},
  43587. borderColor: {default: 'white', type: 'color'},
  43588. highlighted: {default: false},
  43589. highlightedColor: {default: '#24CAFF', type: 'color'},
  43590. href: {default: ''},
  43591. image: {type: 'asset'},
  43592. on: {default: 'click'},
  43593. peekMode: {default: false},
  43594. title: {default: ''},
  43595. titleColor: {default: 'white', type: 'color'},
  43596. visualAspectEnabled: {default: false}
  43597. },
  43598. init: function () {
  43599. this.navigate = this.navigate.bind(this);
  43600. this.previousQuaternion = undefined;
  43601. this.quaternionClone = new THREE.Quaternion();
  43602. // Store hidden elements during peek mode so we can show them again later.
  43603. this.hiddenEls = [];
  43604. },
  43605. update: function (oldData) {
  43606. var data = this.data;
  43607. var el = this.el;
  43608. var backgroundColor;
  43609. var strokeColor;
  43610. if (!data.visualAspectEnabled) { return; }
  43611. this.initVisualAspect();
  43612. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  43613. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  43614. el.setAttribute('material', 'backgroundColor', backgroundColor);
  43615. el.setAttribute('material', 'strokeColor', strokeColor);
  43616. if (data.on !== oldData.on) { this.updateEventListener(); }
  43617. if (oldData.peekMode !== undefined &&
  43618. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  43619. if (!data.image || oldData.image === data.image) { return; }
  43620. el.setAttribute('material', 'pano',
  43621. typeof data.image === 'string' ? data.image : data.image.src);
  43622. },
  43623. /*
  43624. * Toggle all elements and full 360 preview of the linked page.
  43625. */
  43626. updatePeekMode: function () {
  43627. var el = this.el;
  43628. var sphereEl = this.sphereEl;
  43629. if (this.data.peekMode) {
  43630. this.hideAll();
  43631. el.getObject3D('mesh').visible = false;
  43632. sphereEl.setAttribute('visible', true);
  43633. } else {
  43634. this.showAll();
  43635. el.getObject3D('mesh').visible = true;
  43636. sphereEl.setAttribute('visible', false);
  43637. }
  43638. },
  43639. play: function () {
  43640. this.updateEventListener();
  43641. },
  43642. pause: function () {
  43643. this.removeEventListener();
  43644. },
  43645. updateEventListener: function () {
  43646. var el = this.el;
  43647. if (!el.isPlaying) { return; }
  43648. this.removeEventListener();
  43649. el.addEventListener(this.data.on, this.navigate);
  43650. },
  43651. removeEventListener: function () {
  43652. var on = this.data.on;
  43653. if (!on) { return; }
  43654. this.el.removeEventListener(on, this.navigate);
  43655. },
  43656. initVisualAspect: function () {
  43657. var el = this.el;
  43658. var semiSphereEl;
  43659. var sphereEl;
  43660. var textEl;
  43661. if (!this.data.visualAspectEnabled || this.visualAspectInitialized) { return; }
  43662. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  43663. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  43664. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  43665. // Set portal.
  43666. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  43667. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  43668. // Set text that displays the link title and URL.
  43669. textEl.setAttribute('text', {
  43670. color: this.data.titleColor,
  43671. align: 'center',
  43672. font: 'kelsonsans',
  43673. value: this.data.title || this.data.href,
  43674. width: 4
  43675. });
  43676. textEl.setAttribute('position', '0 1.5 0');
  43677. el.appendChild(textEl);
  43678. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  43679. semiSphereEl.setAttribute('geometry', {
  43680. primitive: 'sphere',
  43681. radius: 1.0,
  43682. phiStart: 0,
  43683. segmentsWidth: 64,
  43684. segmentsHeight: 64,
  43685. phiLength: 180,
  43686. thetaStart: 0,
  43687. thetaLength: 360
  43688. });
  43689. semiSphereEl.setAttribute('material', {
  43690. shader: 'portal',
  43691. borderEnabled: 0.0,
  43692. pano: this.data.image,
  43693. side: 'back'
  43694. });
  43695. semiSphereEl.setAttribute('rotation', '0 180 0');
  43696. semiSphereEl.setAttribute('position', '0 0 0');
  43697. semiSphereEl.setAttribute('visible', false);
  43698. el.appendChild(semiSphereEl);
  43699. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  43700. sphereEl.setAttribute('geometry', {
  43701. primitive: 'sphere',
  43702. radius: 10,
  43703. segmentsWidth: 64,
  43704. segmentsHeight: 64
  43705. });
  43706. sphereEl.setAttribute('material', {
  43707. shader: 'portal',
  43708. borderEnabled: 0.0,
  43709. pano: this.data.image,
  43710. side: 'back'
  43711. });
  43712. sphereEl.setAttribute('visible', false);
  43713. el.appendChild(sphereEl);
  43714. this.visualAspectInitialized = true;
  43715. },
  43716. navigate: function () {
  43717. window.location = this.data.href;
  43718. },
  43719. /**
  43720. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  43721. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  43722. * from where user enters.
  43723. * 2. Place the url/title above or inside portal depending on distance to camera.
  43724. * 3. Face portal to camera when far away from user.
  43725. */
  43726. tick: (function () {
  43727. var cameraWorldPosition = new THREE.Vector3();
  43728. var elWorldPosition = new THREE.Vector3();
  43729. var quaternion = new THREE.Quaternion();
  43730. var scale = new THREE.Vector3();
  43731. return function () {
  43732. var el = this.el;
  43733. var object3D = el.object3D;
  43734. var camera = el.sceneEl.camera;
  43735. var cameraPortalOrientation;
  43736. var distance;
  43737. var textEl = this.textEl;
  43738. if (!this.data.visualAspectEnabled) { return; }
  43739. // Update matrices
  43740. object3D.updateMatrixWorld();
  43741. camera.parent.updateMatrixWorld();
  43742. camera.updateMatrixWorld();
  43743. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  43744. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  43745. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  43746. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  43747. if (distance > 20) {
  43748. // Store original orientation to be restored when the portal stops facing the camera.
  43749. if (!this.previousQuaternion) {
  43750. this.quaternionClone.copy(quaternion);
  43751. this.previousQuaternion = this.quaternionClone;
  43752. }
  43753. // If the portal is far away from the user, face portal to camera.
  43754. object3D.lookAt(cameraWorldPosition);
  43755. } else {
  43756. // When portal is close to the user/camera.
  43757. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  43758. // If user gets very close to portal, replace with holed sphere they can peek in.
  43759. if (distance < 0.5) {
  43760. // Configure text size and sphere orientation depending side user approaches portal.
  43761. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  43762. textEl.setAttribute('text', 'width', 1.5);
  43763. if (cameraPortalOrientation <= 0.0) {
  43764. textEl.setAttribute('position', '0 0 0.75');
  43765. textEl.setAttribute('rotation', '0 180 0');
  43766. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  43767. } else {
  43768. textEl.setAttribute('position', '0 0 -0.75');
  43769. textEl.setAttribute('rotation', '0 0 0');
  43770. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  43771. }
  43772. el.getObject3D('mesh').visible = false;
  43773. this.semiSphereEl.setAttribute('visible', true);
  43774. this.peekCameraPortalOrientation = cameraPortalOrientation;
  43775. } else {
  43776. // Calculate wich side the camera is approaching the camera (back / front).
  43777. // Adjust text orientation based on camera position.
  43778. if (cameraPortalOrientation <= 0.0) {
  43779. textEl.setAttribute('rotation', '0 180 0');
  43780. } else {
  43781. textEl.setAttribute('rotation', '0 0 0');
  43782. }
  43783. textEl.setAttribute('text', 'width', 5);
  43784. textEl.setAttribute('position', '0 1.5 0');
  43785. el.getObject3D('mesh').visible = true;
  43786. this.semiSphereEl.setAttribute('visible', false);
  43787. this.peekCameraPortalOrientation = undefined;
  43788. }
  43789. if (this.previousQuaternion) {
  43790. object3D.quaternion.copy(this.previousQuaternion);
  43791. this.previousQuaternion = undefined;
  43792. }
  43793. }
  43794. };
  43795. })(),
  43796. hideAll: function () {
  43797. var el = this.el;
  43798. var hiddenEls = this.hiddenEls;
  43799. var self = this;
  43800. if (hiddenEls.length > 0) { return; }
  43801. el.sceneEl.object3D.traverse(function (object) {
  43802. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  43803. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  43804. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  43805. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  43806. object.el === self.semiSphereEl) {
  43807. return;
  43808. }
  43809. object.el.setAttribute('visible', false);
  43810. hiddenEls.push(object.el);
  43811. });
  43812. },
  43813. showAll: function () {
  43814. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  43815. this.hiddenEls = [];
  43816. },
  43817. /**
  43818. * Calculate whether the camera faces the front or back face of the portal.
  43819. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  43820. */
  43821. calculateCameraPortalOrientation: (function () {
  43822. var mat4 = new THREE.Matrix4();
  43823. var cameraPosition = new THREE.Vector3();
  43824. var portalNormal = new THREE.Vector3(0, 0, 1);
  43825. var portalPosition = new THREE.Vector3(0, 0, 0);
  43826. return function () {
  43827. var el = this.el;
  43828. var camera = el.sceneEl.camera;
  43829. // Reset tmp variables.
  43830. cameraPosition.set(0, 0, 0);
  43831. portalNormal.set(0, 0, 1);
  43832. portalPosition.set(0, 0, 0);
  43833. // Apply portal orientation to the normal.
  43834. el.object3D.matrixWorld.extractRotation(mat4);
  43835. portalNormal.applyMatrix4(mat4);
  43836. // Calculate portal world position.
  43837. el.object3D.updateMatrixWorld();
  43838. el.object3D.localToWorld(portalPosition);
  43839. // Calculate camera world position.
  43840. camera.parent.parent.updateMatrixWorld();
  43841. camera.parent.updateMatrixWorld();
  43842. camera.updateMatrixWorld();
  43843. camera.localToWorld(cameraPosition);
  43844. // Calculate vector from portal to camera.
  43845. // (portal) -------> (camera)
  43846. cameraPosition.sub(portalPosition).normalize();
  43847. portalNormal.normalize();
  43848. // Side where camera approaches portal is given by sign of dot product of portal normal
  43849. // and portal to camera vectors.
  43850. return Math.sign(portalNormal.dot(cameraPosition));
  43851. };
  43852. })(),
  43853. remove: function () {
  43854. this.removeEventListener();
  43855. }
  43856. });
  43857. /* eslint-disable */
  43858. registerShader('portal', {
  43859. schema: {
  43860. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  43861. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  43862. pano: {type: 'map', is: 'uniform'},
  43863. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  43864. },
  43865. vertexShader: [
  43866. 'vec3 portalPosition;',
  43867. 'varying vec3 vWorldPosition;',
  43868. 'varying float vDistanceToCenter;',
  43869. 'varying float vDistance;',
  43870. 'void main() {',
  43871. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  43872. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  43873. 'vDistance = length(portalPosition - cameraPosition);',
  43874. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  43875. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  43876. '}'
  43877. ].join('\n'),
  43878. fragmentShader: [
  43879. '#define RECIPROCAL_PI2 0.15915494',
  43880. 'uniform sampler2D pano;',
  43881. 'uniform vec3 strokeColor;',
  43882. 'uniform vec3 backgroundColor;',
  43883. 'uniform float borderEnabled;',
  43884. 'varying float vDistanceToCenter;',
  43885. 'varying float vDistance;',
  43886. 'varying vec3 vWorldPosition;',
  43887. 'void main() {',
  43888. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  43889. 'vec2 sampleUV;',
  43890. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  43891. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  43892. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  43893. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  43894. 'gl_FragColor = vec4(strokeColor, 1.0);',
  43895. '} else {',
  43896. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  43897. '}',
  43898. '}'
  43899. ].join('\n')
  43900. });
  43901. /* eslint-enable */
  43902. },{"../core/component":103,"../core/shader":113,"../lib/three":151}],65:[function(_dereq_,module,exports){
  43903. var registerComponent = _dereq_('../core/component').registerComponent;
  43904. var THREE = _dereq_('../lib/three');
  43905. var utils = _dereq_('../utils/');
  43906. var bind = utils.bind;
  43907. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  43908. // To avoid recalculation at every mouse movement tick
  43909. var PI_2 = Math.PI / 2;
  43910. /**
  43911. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  43912. */
  43913. module.exports.Component = registerComponent('look-controls', {
  43914. dependencies: ['position', 'rotation'],
  43915. schema: {
  43916. enabled: {default: true},
  43917. hmdEnabled: {default: true},
  43918. pointerLockEnabled: {default: false},
  43919. reverseMouseDrag: {default: false},
  43920. reverseTouchDrag: {default: false},
  43921. touchEnabled: {default: true}
  43922. },
  43923. init: function () {
  43924. this.previousHMDPosition = new THREE.Vector3();
  43925. this.hmdQuaternion = new THREE.Quaternion();
  43926. this.hmdEuler = new THREE.Euler();
  43927. this.position = new THREE.Vector3();
  43928. // To save / restore camera pose
  43929. this.savedRotation = new THREE.Vector3();
  43930. this.savedPosition = new THREE.Vector3();
  43931. this.polyfillObject = new THREE.Object3D();
  43932. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  43933. this.rotation = {};
  43934. this.deltaRotation = {};
  43935. this.savedPose = null;
  43936. this.pointerLocked = false;
  43937. this.setupMouseControls();
  43938. this.bindMethods();
  43939. this.el.object3D.matrixAutoUpdate = false;
  43940. this.el.object3D.updateMatrix();
  43941. this.savedPose = {
  43942. position: new THREE.Vector3(),
  43943. rotation: new THREE.Euler()
  43944. };
  43945. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  43946. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  43947. },
  43948. update: function (oldData) {
  43949. var data = this.data;
  43950. // Disable grab cursor classes if no longer enabled.
  43951. if (data.enabled !== oldData.enabled) {
  43952. this.updateGrabCursor(data.enabled);
  43953. }
  43954. // Reset pitch and yaw if disabling HMD.
  43955. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  43956. this.pitchObject.rotation.set(0, 0, 0);
  43957. this.yawObject.rotation.set(0, 0, 0);
  43958. }
  43959. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  43960. this.removeEventListeners();
  43961. this.addEventListeners();
  43962. if (this.pointerLocked) { this.exitPointerLock(); }
  43963. }
  43964. },
  43965. tick: function (t) {
  43966. var data = this.data;
  43967. if (!data.enabled) { return; }
  43968. this.updateOrientation();
  43969. },
  43970. play: function () {
  43971. this.addEventListeners();
  43972. },
  43973. pause: function () {
  43974. this.removeEventListeners();
  43975. if (this.pointerLocked) { this.exitPointerLock(); }
  43976. },
  43977. remove: function () {
  43978. this.removeEventListeners();
  43979. if (this.pointerLocked) { this.exitPointerLock(); }
  43980. },
  43981. bindMethods: function () {
  43982. this.onMouseDown = bind(this.onMouseDown, this);
  43983. this.onMouseMove = bind(this.onMouseMove, this);
  43984. this.onMouseUp = bind(this.onMouseUp, this);
  43985. this.onTouchStart = bind(this.onTouchStart, this);
  43986. this.onTouchMove = bind(this.onTouchMove, this);
  43987. this.onTouchEnd = bind(this.onTouchEnd, this);
  43988. this.onEnterVR = bind(this.onEnterVR, this);
  43989. this.onExitVR = bind(this.onExitVR, this);
  43990. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  43991. this.onPointerLockError = bind(this.onPointerLockError, this);
  43992. },
  43993. /**
  43994. * Set up states and Object3Ds needed to store rotation data.
  43995. */
  43996. setupMouseControls: function () {
  43997. this.mouseDown = false;
  43998. this.pitchObject = new THREE.Object3D();
  43999. this.yawObject = new THREE.Object3D();
  44000. this.yawObject.position.y = 10;
  44001. this.yawObject.add(this.pitchObject);
  44002. },
  44003. /**
  44004. * Add mouse and touch event listeners to canvas.
  44005. */
  44006. addEventListeners: function () {
  44007. var sceneEl = this.el.sceneEl;
  44008. var canvasEl = sceneEl.canvas;
  44009. // Wait for canvas to load.
  44010. if (!canvasEl) {
  44011. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  44012. return;
  44013. }
  44014. // Mouse events.
  44015. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  44016. window.addEventListener('mousemove', this.onMouseMove, false);
  44017. window.addEventListener('mouseup', this.onMouseUp, false);
  44018. // Touch events.
  44019. canvasEl.addEventListener('touchstart', this.onTouchStart);
  44020. window.addEventListener('touchmove', this.onTouchMove);
  44021. window.addEventListener('touchend', this.onTouchEnd);
  44022. // sceneEl events.
  44023. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  44024. sceneEl.addEventListener('exit-vr', this.onExitVR);
  44025. // Pointer Lock events.
  44026. if (this.data.pointerLockEnabled) {
  44027. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  44028. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  44029. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  44030. }
  44031. },
  44032. /**
  44033. * Remove mouse and touch event listeners from canvas.
  44034. */
  44035. removeEventListeners: function () {
  44036. var sceneEl = this.el.sceneEl;
  44037. var canvasEl = sceneEl && sceneEl.canvas;
  44038. if (!canvasEl) { return; }
  44039. // Mouse events.
  44040. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  44041. window.removeEventListener('mousemove', this.onMouseMove);
  44042. window.removeEventListener('mouseup', this.onMouseUp);
  44043. // Touch events.
  44044. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  44045. window.removeEventListener('touchmove', this.onTouchMove);
  44046. window.removeEventListener('touchend', this.onTouchEnd);
  44047. // sceneEl events.
  44048. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  44049. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  44050. // Pointer Lock events.
  44051. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  44052. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  44053. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  44054. },
  44055. /**
  44056. * Update orientation for mobile, mouse drag, and headset.
  44057. * Mouse-drag only enabled if HMD is not active.
  44058. */
  44059. updateOrientation: (function () {
  44060. var poseMatrix = new THREE.Matrix4();
  44061. return function () {
  44062. var hmdEuler = this.hmdEuler;
  44063. var object3D = this.el.object3D;
  44064. var pitchObject = this.pitchObject;
  44065. var yawObject = this.yawObject;
  44066. var pose;
  44067. var sceneEl = this.el.sceneEl;
  44068. // WebXR API updates applies headset pose to the object3D matrixWorld internally.
  44069. // Reflect values back on position, rotation, scale so setAttribute returns expected values.
  44070. if (sceneEl.is('vr-mode') && sceneEl.hasWebXR) {
  44071. pose = sceneEl.renderer.vr.getCameraPose();
  44072. if (pose) {
  44073. poseMatrix.elements = pose.poseModelMatrix;
  44074. poseMatrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  44075. }
  44076. } else {
  44077. object3D.updateMatrix();
  44078. }
  44079. // In VR mode, THREE is in charge of updating the camera rotation.
  44080. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  44081. // Calculate polyfilled HMD quaternion.
  44082. this.polyfillControls.update();
  44083. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  44084. // On mobile, do camera rotation with touch events and sensors.
  44085. object3D.rotation.x = hmdEuler.x + pitchObject.rotation.x;
  44086. object3D.rotation.y = hmdEuler.y + yawObject.rotation.y;
  44087. };
  44088. })(),
  44089. /**
  44090. * Translate mouse drag into rotation.
  44091. *
  44092. * Dragging up and down rotates the camera around the X-axis (yaw).
  44093. * Dragging left and right rotates the camera around the Y-axis (pitch).
  44094. */
  44095. onMouseMove: function (event) {
  44096. var direction;
  44097. var movementX;
  44098. var movementY;
  44099. var pitchObject = this.pitchObject;
  44100. var previousMouseEvent = this.previousMouseEvent;
  44101. var yawObject = this.yawObject;
  44102. // Not dragging or not enabled.
  44103. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  44104. // Calculate delta.
  44105. if (this.pointerLocked) {
  44106. movementX = event.movementX || event.mozMovementX || 0;
  44107. movementY = event.movementY || event.mozMovementY || 0;
  44108. } else {
  44109. movementX = event.screenX - previousMouseEvent.screenX;
  44110. movementY = event.screenY - previousMouseEvent.screenY;
  44111. }
  44112. this.previousMouseEvent = event;
  44113. // Calculate rotation.
  44114. direction = this.data.reverseMouseDrag ? 1 : -1;
  44115. yawObject.rotation.y += movementX * 0.002 * direction;
  44116. pitchObject.rotation.x += movementY * 0.002 * direction;
  44117. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  44118. },
  44119. /**
  44120. * Register mouse down to detect mouse drag.
  44121. */
  44122. onMouseDown: function (evt) {
  44123. if (!this.data.enabled) { return; }
  44124. // Handle only primary button.
  44125. if (evt.button !== 0) { return; }
  44126. var sceneEl = this.el.sceneEl;
  44127. var canvasEl = sceneEl && sceneEl.canvas;
  44128. this.mouseDown = true;
  44129. this.previousMouseEvent = evt;
  44130. this.showGrabbingCursor();
  44131. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  44132. if (canvasEl.requestPointerLock) {
  44133. canvasEl.requestPointerLock();
  44134. } else if (canvasEl.mozRequestPointerLock) {
  44135. canvasEl.mozRequestPointerLock();
  44136. }
  44137. }
  44138. },
  44139. /**
  44140. * Shows grabbing cursor on scene
  44141. */
  44142. showGrabbingCursor: function () {
  44143. this.el.sceneEl.canvas.style.cursor = 'grabbing';
  44144. },
  44145. /**
  44146. * Hides grabbing cursor on scene
  44147. */
  44148. hideGrabbingCursor: function () {
  44149. this.el.sceneEl.canvas.style.cursor = '';
  44150. },
  44151. /**
  44152. * Register mouse up to detect release of mouse drag.
  44153. */
  44154. onMouseUp: function () {
  44155. this.mouseDown = false;
  44156. this.hideGrabbingCursor();
  44157. },
  44158. /**
  44159. * Register touch down to detect touch drag.
  44160. */
  44161. onTouchStart: function (evt) {
  44162. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  44163. this.touchStart = {
  44164. x: evt.touches[0].pageX,
  44165. y: evt.touches[0].pageY
  44166. };
  44167. this.touchStarted = true;
  44168. },
  44169. /**
  44170. * Translate touch move to Y-axis rotation.
  44171. */
  44172. onTouchMove: function (evt) {
  44173. var direction;
  44174. var canvas = this.el.sceneEl.canvas;
  44175. var deltaY;
  44176. var yawObject = this.yawObject;
  44177. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  44178. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  44179. direction = this.data.reverseTouchDrag ? 1 : -1;
  44180. // Limit touch orientaion to to yaw (y axis).
  44181. yawObject.rotation.y -= deltaY * 0.5 * direction;
  44182. this.touchStart = {
  44183. x: evt.touches[0].pageX,
  44184. y: evt.touches[0].pageY
  44185. };
  44186. },
  44187. /**
  44188. * Register touch end to detect release of touch drag.
  44189. */
  44190. onTouchEnd: function () {
  44191. this.touchStarted = false;
  44192. },
  44193. /**
  44194. * Save pose.
  44195. */
  44196. onEnterVR: function () {
  44197. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  44198. this.saveCameraPose();
  44199. this.el.object3D.position.set(0, 0, 0);
  44200. this.el.object3D.updateMatrix();
  44201. },
  44202. /**
  44203. * Restore the pose.
  44204. */
  44205. onExitVR: function () {
  44206. if (!this.el.sceneEl.checkHeadsetConnected()) { return; }
  44207. this.restoreCameraPose();
  44208. this.previousHMDPosition.set(0, 0, 0);
  44209. },
  44210. /**
  44211. * Update Pointer Lock state.
  44212. */
  44213. onPointerLockChange: function () {
  44214. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  44215. },
  44216. /**
  44217. * Recover from Pointer Lock error.
  44218. */
  44219. onPointerLockError: function () {
  44220. this.pointerLocked = false;
  44221. },
  44222. // Exits pointer-locked mode.
  44223. exitPointerLock: function () {
  44224. document.exitPointerLock();
  44225. this.pointerLocked = false;
  44226. },
  44227. /**
  44228. * Toggle the feature of showing/hiding the grab cursor.
  44229. */
  44230. updateGrabCursor: function (enabled) {
  44231. var sceneEl = this.el.sceneEl;
  44232. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  44233. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  44234. if (!sceneEl.canvas) {
  44235. if (enabled) {
  44236. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  44237. } else {
  44238. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  44239. }
  44240. return;
  44241. }
  44242. if (enabled) {
  44243. enableGrabCursor();
  44244. return;
  44245. }
  44246. disableGrabCursor();
  44247. },
  44248. /**
  44249. * Save camera pose before entering VR to restore later if exiting.
  44250. */
  44251. saveCameraPose: function () {
  44252. var el = this.el;
  44253. this.savedPose.position.copy(el.object3D.position);
  44254. this.savedPose.rotation.copy(el.object3D.rotation);
  44255. this.hasSavedPose = true;
  44256. },
  44257. /**
  44258. * Reset camera pose to before entering VR.
  44259. */
  44260. restoreCameraPose: function () {
  44261. var el = this.el;
  44262. var savedPose = this.savedPose;
  44263. if (!this.hasSavedPose) { return; }
  44264. // Reset camera orientation.
  44265. el.object3D.position.copy(savedPose.position);
  44266. el.object3D.rotation.copy(savedPose.rotation);
  44267. this.hasSavedPose = false;
  44268. }
  44269. });
  44270. },{"../core/component":103,"../lib/three":151,"../utils":176,"../utils/":176}],66:[function(_dereq_,module,exports){
  44271. /* global Promise */
  44272. var utils = _dereq_('../utils/');
  44273. var component = _dereq_('../core/component');
  44274. var THREE = _dereq_('../lib/three');
  44275. var shader = _dereq_('../core/shader');
  44276. var error = utils.debug('components:material:error');
  44277. var registerComponent = component.registerComponent;
  44278. var shaders = shader.shaders;
  44279. var shaderNames = shader.shaderNames;
  44280. /**
  44281. * Material component.
  44282. *
  44283. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  44284. * three.js's implementation of PBR. Another standard shading model is `flat` which
  44285. * uses MeshBasicMaterial.
  44286. */
  44287. module.exports.Component = registerComponent('material', {
  44288. schema: {
  44289. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  44290. depthTest: {default: true},
  44291. depthWrite: {default: true},
  44292. flatShading: {default: false},
  44293. npot: {default: false},
  44294. offset: {type: 'vec2', default: {x: 0, y: 0}},
  44295. opacity: {default: 1.0, min: 0.0, max: 1.0},
  44296. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  44297. shader: {default: 'standard', oneOf: shaderNames, schemaChange: true},
  44298. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  44299. transparent: {default: false},
  44300. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  44301. visible: {default: true},
  44302. blending: {default: 'normal', oneOf: ['none', 'normal', 'additive', 'subtractive', 'multiply']}
  44303. },
  44304. init: function () {
  44305. this.material = null;
  44306. },
  44307. /**
  44308. * Update or create material.
  44309. *
  44310. * @param {object|null} oldData
  44311. */
  44312. update: function (oldData) {
  44313. var data = this.data;
  44314. if (!this.shader || data.shader !== oldData.shader) {
  44315. this.updateShader(data.shader);
  44316. }
  44317. this.shader.update(this.data);
  44318. this.updateMaterial(oldData);
  44319. },
  44320. updateSchema: function (data) {
  44321. var currentShader;
  44322. var newShader;
  44323. var schema;
  44324. var shader;
  44325. newShader = data && data.shader;
  44326. currentShader = this.oldData && this.oldData.shader;
  44327. shader = newShader || currentShader;
  44328. schema = shaders[shader] && shaders[shader].schema;
  44329. if (!schema) { error('Unknown shader schema ' + shader); }
  44330. if (currentShader && newShader === currentShader) { return; }
  44331. this.extendSchema(schema);
  44332. this.updateBehavior();
  44333. },
  44334. updateBehavior: function () {
  44335. var key;
  44336. var sceneEl = this.el.sceneEl;
  44337. var schema = this.schema;
  44338. var self = this;
  44339. var tickProperties;
  44340. function tickTime (time, delta) {
  44341. var key;
  44342. for (key in tickProperties) {
  44343. tickProperties[key] = time;
  44344. }
  44345. self.shader.update(tickProperties);
  44346. }
  44347. this.tick = undefined;
  44348. tickProperties = {};
  44349. for (key in schema) {
  44350. if (schema[key].type === 'time') {
  44351. this.tick = tickTime;
  44352. tickProperties[key] = true;
  44353. }
  44354. }
  44355. if (!sceneEl) { return; }
  44356. if (this.tick) {
  44357. sceneEl.addBehavior(this);
  44358. } else {
  44359. sceneEl.removeBehavior(this);
  44360. }
  44361. },
  44362. updateShader: function (shaderName) {
  44363. var data = this.data;
  44364. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  44365. var shaderInstance;
  44366. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  44367. // Get material from A-Frame shader.
  44368. shaderInstance = this.shader = new Shader();
  44369. shaderInstance.el = this.el;
  44370. shaderInstance.init(data);
  44371. this.setMaterial(shaderInstance.material);
  44372. this.updateSchema(data);
  44373. },
  44374. /**
  44375. * Set and update base material properties.
  44376. * Set `needsUpdate` when needed.
  44377. */
  44378. updateMaterial: function (oldData) {
  44379. var data = this.data;
  44380. var material = this.material;
  44381. var oldDataHasKeys;
  44382. // Base material properties.
  44383. material.alphaTest = data.alphaTest;
  44384. material.depthTest = data.depthTest !== false;
  44385. material.depthWrite = data.depthWrite !== false;
  44386. material.opacity = data.opacity;
  44387. material.flatShading = data.flatShading;
  44388. material.side = parseSide(data.side);
  44389. material.transparent = data.transparent !== false || data.opacity < 1.0;
  44390. material.vertexColors = parseVertexColors(data.vertexColors);
  44391. material.visible = data.visible;
  44392. material.blending = parseBlending(data.blending);
  44393. // Check if material needs update.
  44394. for (oldDataHasKeys in oldData) { break; }
  44395. if (oldDataHasKeys &&
  44396. (oldData.alphaTest !== data.alphaTest ||
  44397. oldData.side !== data.side ||
  44398. oldData.vertexColors !== data.vertexColors)) {
  44399. material.needsUpdate = true;
  44400. }
  44401. },
  44402. /**
  44403. * Remove material on remove (callback).
  44404. * Dispose of it from memory and unsubscribe from scene updates.
  44405. */
  44406. remove: function () {
  44407. var defaultMaterial = new THREE.MeshBasicMaterial();
  44408. var material = this.material;
  44409. var object3D = this.el.getObject3D('mesh');
  44410. if (object3D) { object3D.material = defaultMaterial; }
  44411. disposeMaterial(material, this.system);
  44412. },
  44413. /**
  44414. * (Re)create new material. Has side-effects of setting `this.material` and updating
  44415. * material registration in scene.
  44416. *
  44417. * @param {object} data - Material component data.
  44418. * @param {object} type - Material type to create.
  44419. * @returns {object} Material.
  44420. */
  44421. setMaterial: function (material) {
  44422. var el = this.el;
  44423. var mesh;
  44424. var system = this.system;
  44425. if (this.material) { disposeMaterial(this.material, system); }
  44426. this.material = material;
  44427. system.registerMaterial(material);
  44428. // Set on mesh. If mesh does not exist, wait for it.
  44429. mesh = el.getObject3D('mesh');
  44430. if (mesh) {
  44431. mesh.material = material;
  44432. } else {
  44433. el.addEventListener('object3dset', function waitForMesh (evt) {
  44434. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  44435. el.getObject3D('mesh').material = material;
  44436. el.removeEventListener('object3dset', waitForMesh);
  44437. });
  44438. }
  44439. }
  44440. });
  44441. /**
  44442. * Return a three.js constant determining which material face sides to render
  44443. * based on the side parameter (passed as a component property).
  44444. *
  44445. * @param {string} [side=front] - `front`, `back`, or `double`.
  44446. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  44447. */
  44448. function parseSide (side) {
  44449. switch (side) {
  44450. case 'back': {
  44451. return THREE.BackSide;
  44452. }
  44453. case 'double': {
  44454. return THREE.DoubleSide;
  44455. }
  44456. default: {
  44457. // Including case `front`.
  44458. return THREE.FrontSide;
  44459. }
  44460. }
  44461. }
  44462. /**
  44463. * Return a three.js constant determining vertex coloring.
  44464. */
  44465. function parseVertexColors (coloring) {
  44466. switch (coloring) {
  44467. case 'face': {
  44468. return THREE.FaceColors;
  44469. }
  44470. case 'vertex': {
  44471. return THREE.VertexColors;
  44472. }
  44473. default: {
  44474. return THREE.NoColors;
  44475. }
  44476. }
  44477. }
  44478. /**
  44479. * Return a three.js constant determining blending
  44480. *
  44481. * @param {string} [blending=normal]
  44482. * - `none`, additive`, `subtractive`,`multiply` or `normal`.
  44483. * @returns {number}
  44484. */
  44485. function parseBlending (blending) {
  44486. switch (blending) {
  44487. case 'none': {
  44488. return THREE.NoBlending;
  44489. }
  44490. case 'additive': {
  44491. return THREE.AdditiveBlending;
  44492. }
  44493. case 'subtractive': {
  44494. return THREE.SubtractiveBlending;
  44495. }
  44496. case 'multiply': {
  44497. return THREE.MultiplyBlending;
  44498. }
  44499. default: {
  44500. return THREE.NormalBlending;
  44501. }
  44502. }
  44503. }
  44504. /**
  44505. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  44506. */
  44507. function disposeMaterial (material, system) {
  44508. material.dispose();
  44509. system.unregisterMaterial(material);
  44510. }
  44511. },{"../core/component":103,"../core/shader":113,"../lib/three":151,"../utils/":176}],67:[function(_dereq_,module,exports){
  44512. var debug = _dereq_('../utils/debug');
  44513. var registerComponent = _dereq_('../core/component').registerComponent;
  44514. var THREE = _dereq_('../lib/three');
  44515. var warn = debug('components:obj-model:warn');
  44516. module.exports.Component = registerComponent('obj-model', {
  44517. schema: {
  44518. mtl: {type: 'model'},
  44519. obj: {type: 'model'}
  44520. },
  44521. init: function () {
  44522. var self = this;
  44523. this.model = null;
  44524. this.objLoader = new THREE.OBJLoader();
  44525. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  44526. // Allow cross-origin images to be loaded.
  44527. this.mtlLoader.crossOrigin = '';
  44528. this.el.addEventListener('componentinitialized', function (evt) {
  44529. if (!self.model) { return; }
  44530. if (evt.detail.name !== 'material') { return; }
  44531. self.applyMaterial();
  44532. });
  44533. },
  44534. update: function () {
  44535. var data = this.data;
  44536. if (!data.obj) { return; }
  44537. this.resetMesh();
  44538. this.loadObj(data.obj, data.mtl);
  44539. },
  44540. remove: function () {
  44541. if (!this.model) { return; }
  44542. this.resetMesh();
  44543. },
  44544. resetMesh: function () {
  44545. this.el.removeObject3D('mesh');
  44546. },
  44547. loadObj: function (objUrl, mtlUrl) {
  44548. var self = this;
  44549. var el = this.el;
  44550. var mtlLoader = this.mtlLoader;
  44551. var objLoader = this.objLoader;
  44552. var rendererSystem = this.el.sceneEl.systems.renderer;
  44553. var BASE_PATH = mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1);
  44554. if (mtlUrl) {
  44555. // .OBJ with an .MTL.
  44556. if (el.hasAttribute('material')) {
  44557. warn('Material component properties are ignored when a .MTL is provided');
  44558. }
  44559. mtlLoader.setResourcePath(BASE_PATH);
  44560. mtlLoader.load(mtlUrl, function (materials) {
  44561. materials.preload();
  44562. objLoader.setMaterials(materials);
  44563. objLoader.load(objUrl, function (objModel) {
  44564. self.model = objModel;
  44565. self.model.traverse(function (object) {
  44566. if (object.isMesh) {
  44567. var material = object.material;
  44568. if (material.color) rendererSystem.applyColorCorrection(material.color);
  44569. if (material.map) rendererSystem.applyColorCorrection(material.map);
  44570. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  44571. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  44572. }
  44573. });
  44574. el.setObject3D('mesh', objModel);
  44575. el.emit('model-loaded', {format: 'obj', model: objModel});
  44576. });
  44577. });
  44578. return;
  44579. }
  44580. // .OBJ only.
  44581. objLoader.load(objUrl, function loadObjOnly (objModel) {
  44582. self.model = objModel;
  44583. self.applyMaterial();
  44584. el.setObject3D('mesh', objModel);
  44585. el.emit('model-loaded', {format: 'obj', model: objModel});
  44586. });
  44587. },
  44588. /**
  44589. * Apply material from material component recursively.
  44590. */
  44591. applyMaterial: function () {
  44592. var material = this.el.components.material;
  44593. if (!material) { return; }
  44594. this.model.traverse(function (child) {
  44595. if (child instanceof THREE.Mesh) {
  44596. child.material = material.material;
  44597. }
  44598. });
  44599. }
  44600. });
  44601. },{"../core/component":103,"../lib/three":151,"../utils/debug":172}],68:[function(_dereq_,module,exports){
  44602. var registerComponent = _dereq_('../core/component').registerComponent;
  44603. var bind = _dereq_('../utils/bind');
  44604. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44605. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44606. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44607. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44608. var GAMEPAD_ID_PREFIX = 'Oculus Go';
  44609. var OCULUS_GO_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus/go/oculus-go-controller.gltf';
  44610. /**
  44611. * Oculus Go controls.
  44612. * Interface with Oculus Go controller and map Gamepad events to
  44613. * controller buttons: trackpad, trigger
  44614. * Load a controller model and highlight the pressed buttons.
  44615. */
  44616. module.exports.Component = registerComponent('oculus-go-controls', {
  44617. schema: {
  44618. hand: {default: ''}, // This informs the degenerate arm model.
  44619. buttonColor: {type: 'color', default: '#FFFFFF'},
  44620. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  44621. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  44622. model: {default: true},
  44623. orientationOffset: {type: 'vec3'},
  44624. armModel: {default: true}
  44625. },
  44626. /**
  44627. * Button IDs:
  44628. * 0 - trackpad
  44629. * 1 - trigger
  44630. */
  44631. mapping: {
  44632. axes: {trackpad: [0, 1]},
  44633. buttons: ['trackpad', 'trigger']
  44634. },
  44635. bindMethods: function () {
  44636. this.onModelLoaded = bind(this.onModelLoaded, this);
  44637. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44638. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44639. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  44640. this.onAxisMoved = bind(this.onAxisMoved, this);
  44641. },
  44642. init: function () {
  44643. var self = this;
  44644. this.onButtonChanged = bind(this.onButtonChanged, this);
  44645. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  44646. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  44647. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  44648. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  44649. this.controllerPresent = false;
  44650. this.lastControllerCheck = 0;
  44651. this.rendererSystem = this.el.sceneEl.systems.renderer;
  44652. this.bindMethods();
  44653. },
  44654. addEventListeners: function () {
  44655. var el = this.el;
  44656. el.addEventListener('buttonchanged', this.onButtonChanged);
  44657. el.addEventListener('buttondown', this.onButtonDown);
  44658. el.addEventListener('buttonup', this.onButtonUp);
  44659. el.addEventListener('touchstart', this.onButtonTouchStart);
  44660. el.addEventListener('touchend', this.onButtonTouchEnd);
  44661. el.addEventListener('model-loaded', this.onModelLoaded);
  44662. el.addEventListener('axismove', this.onAxisMoved);
  44663. this.controllerEventsActive = true;
  44664. },
  44665. removeEventListeners: function () {
  44666. var el = this.el;
  44667. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44668. el.removeEventListener('buttondown', this.onButtonDown);
  44669. el.removeEventListener('buttonup', this.onButtonUp);
  44670. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44671. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44672. el.removeEventListener('model-loaded', this.onModelLoaded);
  44673. el.removeEventListener('axismove', this.onAxisMoved);
  44674. this.controllerEventsActive = false;
  44675. },
  44676. checkIfControllerPresent: function () {
  44677. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  44678. this.data.hand ? {hand: this.data.hand} : {});
  44679. },
  44680. play: function () {
  44681. this.checkIfControllerPresent();
  44682. this.addControllersUpdateListener();
  44683. },
  44684. pause: function () {
  44685. this.removeEventListeners();
  44686. this.removeControllersUpdateListener();
  44687. },
  44688. injectTrackedControls: function () {
  44689. var el = this.el;
  44690. var data = this.data;
  44691. el.setAttribute('tracked-controls', {
  44692. armModel: data.armModel,
  44693. idPrefix: GAMEPAD_ID_PREFIX,
  44694. orientationOffset: data.orientationOffset
  44695. });
  44696. if (!this.data.model) { return; }
  44697. this.el.setAttribute('gltf-model', OCULUS_GO_CONTROLLER_MODEL_URL);
  44698. },
  44699. addControllersUpdateListener: function () {
  44700. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44701. },
  44702. removeControllersUpdateListener: function () {
  44703. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44704. },
  44705. onControllersUpdate: function () {
  44706. this.checkIfControllerPresent();
  44707. },
  44708. // No need for onButtonChanged, since Oculus Go controller has no analog buttons.
  44709. onModelLoaded: function (evt) {
  44710. var controllerObject3D = evt.detail.model;
  44711. var buttonMeshes;
  44712. if (!this.data.model) { return; }
  44713. buttonMeshes = this.buttonMeshes = {};
  44714. buttonMeshes.trigger = controllerObject3D.getObjectByName('oculus_go_button_trigger');
  44715. buttonMeshes.trackpad = controllerObject3D.getObjectByName('oculus_go_touchpad');
  44716. },
  44717. onButtonChanged: function (evt) {
  44718. var button = this.mapping.buttons[evt.detail.id];
  44719. if (!button) return;
  44720. // Pass along changed event with button state, using button mapping for convenience.
  44721. this.el.emit(button + 'changed', evt.detail.state);
  44722. },
  44723. onAxisMoved: function (evt) {
  44724. emitIfAxesChanged(this, this.mapping.axes, evt);
  44725. },
  44726. updateModel: function (buttonName, evtName) {
  44727. if (!this.data.model) { return; }
  44728. this.updateButtonModel(buttonName, evtName);
  44729. },
  44730. updateButtonModel: function (buttonName, state) {
  44731. var buttonMeshes = this.buttonMeshes;
  44732. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  44733. var color;
  44734. var button;
  44735. switch (state) {
  44736. case 'down':
  44737. color = this.data.buttonHighlightColor;
  44738. break;
  44739. case 'touchstart':
  44740. color = this.data.buttonTouchedColor;
  44741. break;
  44742. default:
  44743. color = this.data.buttonColor;
  44744. }
  44745. button = buttonMeshes[buttonName];
  44746. button.material.color.set(color);
  44747. this.rendererSystem.applyColorCorrection(button.material.color);
  44748. }
  44749. });
  44750. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],69:[function(_dereq_,module,exports){
  44751. var bind = _dereq_('../utils/bind');
  44752. var registerComponent = _dereq_('../core/component').registerComponent;
  44753. var THREE = _dereq_('../lib/three');
  44754. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  44755. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  44756. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  44757. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  44758. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  44759. var TOUCH_CONTROLLER_MODEL_URL = {
  44760. left: TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.gltf',
  44761. right: TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.gltf'
  44762. };
  44763. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  44764. var DEFAULT_MODEL_PIVOT_OFFSET = new THREE.Vector3(0, 0, -0.053);
  44765. var RAY_ORIGIN = {
  44766. left: {origin: {x: 0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}},
  44767. right: {origin: {x: -0.008, y: -0.004, z: 0}, direction: {x: 0, y: -0.8, z: -1}}
  44768. };
  44769. /**
  44770. * Oculus Touch controls.
  44771. * Interface with Oculus Touch controllers and map Gamepad events to
  44772. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  44773. * Load a controller model and highlight the pressed buttons.
  44774. */
  44775. module.exports.Component = registerComponent('oculus-touch-controls', {
  44776. schema: {
  44777. hand: {default: 'left'},
  44778. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  44779. buttonTouchColor: {type: 'color', default: '#8AB'},
  44780. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  44781. model: {default: true},
  44782. orientationOffset: {type: 'vec3', default: {x: 43, y: 0, z: 0}}
  44783. },
  44784. /**
  44785. * Button IDs:
  44786. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  44787. * 1 - trigger (with analog value, which goes up to 1)
  44788. * 2 - grip (with analog value, which goes up to 1)
  44789. * 3 - X (left) or A (right)
  44790. * 4 - Y (left) or B (right)
  44791. * 5 - surface (touch only)
  44792. */
  44793. mapping: {
  44794. left: {
  44795. axes: {thumbstick: [0, 1]},
  44796. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  44797. },
  44798. right: {
  44799. axes: {thumbstick: [0, 1]},
  44800. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  44801. }
  44802. },
  44803. bindMethods: function () {
  44804. this.onModelLoaded = bind(this.onModelLoaded, this);
  44805. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  44806. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  44807. this.onAxisMoved = bind(this.onAxisMoved, this);
  44808. },
  44809. init: function () {
  44810. var self = this;
  44811. this.onButtonChanged = bind(this.onButtonChanged, this);
  44812. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  44813. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  44814. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  44815. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  44816. this.controllerPresent = false;
  44817. this.lastControllerCheck = 0;
  44818. this.previousButtonValues = {};
  44819. this.rendererSystem = this.el.sceneEl.systems.renderer;
  44820. this.bindMethods();
  44821. },
  44822. addEventListeners: function () {
  44823. var el = this.el;
  44824. el.addEventListener('buttonchanged', this.onButtonChanged);
  44825. el.addEventListener('buttondown', this.onButtonDown);
  44826. el.addEventListener('buttonup', this.onButtonUp);
  44827. el.addEventListener('touchstart', this.onButtonTouchStart);
  44828. el.addEventListener('touchend', this.onButtonTouchEnd);
  44829. el.addEventListener('axismove', this.onAxisMoved);
  44830. el.addEventListener('model-loaded', this.onModelLoaded);
  44831. this.controllerEventsActive = true;
  44832. },
  44833. removeEventListeners: function () {
  44834. var el = this.el;
  44835. el.removeEventListener('buttonchanged', this.onButtonChanged);
  44836. el.removeEventListener('buttondown', this.onButtonDown);
  44837. el.removeEventListener('buttonup', this.onButtonUp);
  44838. el.removeEventListener('touchstart', this.onButtonTouchStart);
  44839. el.removeEventListener('touchend', this.onButtonTouchEnd);
  44840. el.removeEventListener('axismove', this.onAxisMoved);
  44841. el.removeEventListener('model-loaded', this.onModelLoaded);
  44842. this.controllerEventsActive = false;
  44843. },
  44844. checkIfControllerPresent: function () {
  44845. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  44846. hand: this.data.hand
  44847. });
  44848. },
  44849. play: function () {
  44850. this.checkIfControllerPresent();
  44851. this.addControllersUpdateListener();
  44852. },
  44853. pause: function () {
  44854. this.removeEventListeners();
  44855. this.removeControllersUpdateListener();
  44856. },
  44857. loadModel: function () {
  44858. var data = this.data;
  44859. if (!data.model) { return; }
  44860. this.el.setAttribute('gltf-model', 'url(' + TOUCH_CONTROLLER_MODEL_URL[data.hand] + ')');
  44861. },
  44862. injectTrackedControls: function () {
  44863. var data = this.data;
  44864. this.el.setAttribute('tracked-controls', {
  44865. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  44866. controller: 0,
  44867. hand: data.hand,
  44868. orientationOffset: data.orientationOffset
  44869. });
  44870. this.loadModel();
  44871. },
  44872. addControllersUpdateListener: function () {
  44873. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  44874. },
  44875. removeControllersUpdateListener: function () {
  44876. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  44877. },
  44878. onControllersUpdate: function () {
  44879. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  44880. this.checkIfControllerPresent();
  44881. },
  44882. onButtonChanged: function (evt) {
  44883. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  44884. var buttonMeshes = this.buttonMeshes;
  44885. var analogValue;
  44886. if (!button) { return; }
  44887. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  44888. // Update trigger and/or grip meshes, if any.
  44889. if (buttonMeshes) {
  44890. if (button === 'trigger' && buttonMeshes.trigger) {
  44891. buttonMeshes.trigger.rotation.x = this.originalXRotationTrigger - analogValue * (Math.PI / 26);
  44892. }
  44893. if (button === 'grip' && buttonMeshes.grip) {
  44894. buttonMeshes.grip.position.x = this.originalXPositionGrip + (this.data.hand === 'left' ? -1 : 1) * analogValue * 0.004;
  44895. }
  44896. }
  44897. // Pass along changed event with button state, using the buttom mapping for convenience.
  44898. this.el.emit(button + 'changed', evt.detail.state);
  44899. },
  44900. onModelLoaded: function (evt) {
  44901. var controllerObject3D = evt.detail.model;
  44902. var buttonMeshes;
  44903. if (!this.data.model) { return; }
  44904. buttonMeshes = this.buttonMeshes = {};
  44905. buttonMeshes.grip = controllerObject3D.getObjectByName('buttonHand');
  44906. this.originalXPositionGrip = buttonMeshes.grip.position.x;
  44907. buttonMeshes.thumbstick = controllerObject3D.getObjectByName('stick');
  44908. buttonMeshes.trigger = controllerObject3D.getObjectByName('buttonTrigger');
  44909. this.originalXRotationTrigger = buttonMeshes.trigger.rotation.x;
  44910. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX');
  44911. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA');
  44912. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY');
  44913. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB');
  44914. // Offset pivot point
  44915. controllerObject3D.position.copy(DEFAULT_MODEL_PIVOT_OFFSET);
  44916. this.el.emit('controllermodelready', {
  44917. name: 'oculus-touch-controls',
  44918. model: this.data.model,
  44919. rayOrigin: RAY_ORIGIN[this.data.hand]
  44920. });
  44921. },
  44922. onAxisMoved: function (evt) {
  44923. emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  44924. },
  44925. updateModel: function (buttonName, evtName) {
  44926. if (!this.data.model) { return; }
  44927. this.updateButtonModel(buttonName, evtName);
  44928. },
  44929. updateButtonModel: function (buttonName, state) {
  44930. var button;
  44931. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  44932. var buttonMeshes = this.buttonMeshes;
  44933. if (!this.data.model) { return; }
  44934. if (buttonMeshes && buttonMeshes[buttonName]) {
  44935. button = buttonMeshes[buttonName];
  44936. button.material.color.set(color);
  44937. this.rendererSystem.applyColorCorrection(button.material.color);
  44938. }
  44939. }
  44940. });
  44941. },{"../core/component":103,"../lib/three":151,"../utils/bind":170,"../utils/tracked-controls":184}],70:[function(_dereq_,module,exports){
  44942. var registerComponent = _dereq_('../core/component').registerComponent;
  44943. module.exports.Component = registerComponent('position', {
  44944. schema: {type: 'vec3'},
  44945. update: function () {
  44946. var object3D = this.el.object3D;
  44947. var data = this.data;
  44948. object3D.position.set(data.x, data.y, data.z);
  44949. },
  44950. remove: function () {
  44951. // Pretty much for mixins.
  44952. this.el.object3D.position.set(0, 0, 0);
  44953. }
  44954. });
  44955. },{"../core/component":103}],71:[function(_dereq_,module,exports){
  44956. /* global MutationObserver */
  44957. var registerComponent = _dereq_('../core/component').registerComponent;
  44958. var THREE = _dereq_('../lib/three');
  44959. var utils = _dereq_('../utils/');
  44960. var warn = utils.debug('components:raycaster:warn');
  44961. // Defines selectors that should be 'safe' for the MutationObserver used to
  44962. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  44963. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  44964. // reliably detected and are therefore disallowed.
  44965. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  44966. // Configuration for the MutationObserver used to refresh the whitelist.
  44967. // Listens for addition/removal of elements and attributes within the scene.
  44968. var OBSERVER_CONFIG = {
  44969. childList: true,
  44970. attributes: true,
  44971. subtree: true
  44972. };
  44973. var EVENTS = {
  44974. INTERSECT: 'raycaster-intersected',
  44975. INTERSECTION: 'raycaster-intersection',
  44976. INTERSECT_CLEAR: 'raycaster-intersected-cleared',
  44977. INTERSECTION_CLEAR: 'raycaster-intersection-cleared'
  44978. };
  44979. /**
  44980. * Raycaster component.
  44981. *
  44982. * Pass options to three.js Raycaster including which objects to test.
  44983. * Poll for intersections.
  44984. * Emit event on origin entity and on target entity on intersect.
  44985. *
  44986. * @member {array} intersectedEls - List of currently intersected entities.
  44987. * @member {array} objects - Cached list of meshes to intersect.
  44988. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  44989. * @member {object} raycaster - three.js Raycaster.
  44990. */
  44991. module.exports.Component = registerComponent('raycaster', {
  44992. schema: {
  44993. autoRefresh: {default: true},
  44994. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  44995. enabled: {default: true},
  44996. far: {default: 1000},
  44997. interval: {default: 0},
  44998. near: {default: 0},
  44999. objects: {default: ''},
  45000. origin: {type: 'vec3'},
  45001. showLine: {default: false},
  45002. useWorldCoordinates: {default: false}
  45003. },
  45004. multiple: true,
  45005. init: function () {
  45006. this.clearedIntersectedEls = [];
  45007. this.unitLineEndVec3 = new THREE.Vector3();
  45008. this.intersectedEls = [];
  45009. this.intersections = [];
  45010. this.newIntersectedEls = [];
  45011. this.newIntersections = [];
  45012. this.objects = [];
  45013. this.prevCheckTime = undefined;
  45014. this.prevIntersectedEls = [];
  45015. this.rawIntersections = [];
  45016. this.raycaster = new THREE.Raycaster();
  45017. this.updateOriginDirection();
  45018. this.setDirty = this.setDirty.bind(this);
  45019. this.updateLine = this.updateLine.bind(this);
  45020. this.observer = new MutationObserver(this.setDirty);
  45021. this.dirty = true;
  45022. this.lineEndVec3 = new THREE.Vector3();
  45023. this.otherLineEndVec3 = new THREE.Vector3();
  45024. this.lineData = {end: this.lineEndVec3};
  45025. this.getIntersection = this.getIntersection.bind(this);
  45026. this.intersectedDetail = {el: this.el, getIntersection: this.getIntersection};
  45027. this.intersectedClearedDetail = {el: this.el};
  45028. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  45029. this.intersectionDetail = {};
  45030. },
  45031. /**
  45032. * Create or update raycaster object.
  45033. */
  45034. update: function (oldData) {
  45035. var data = this.data;
  45036. var el = this.el;
  45037. var raycaster = this.raycaster;
  45038. // Set raycaster properties.
  45039. raycaster.far = data.far;
  45040. raycaster.near = data.near;
  45041. // Draw line.
  45042. if (data.showLine &&
  45043. (data.far !== oldData.far || data.origin !== oldData.origin ||
  45044. data.direction !== oldData.direction || !oldData.showLine)) {
  45045. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  45046. // adjust line length.
  45047. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  45048. this.drawLine();
  45049. }
  45050. if (!data.showLine && oldData.showLine) {
  45051. el.removeAttribute('line');
  45052. }
  45053. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  45054. warn('[raycaster] Selector "' + data.objects +
  45055. '" may not update automatically with DOM changes.');
  45056. }
  45057. if (!data.objects) {
  45058. warn('[raycaster] For performance, please define raycaster.objects when using ' +
  45059. 'raycaster or cursor components to whitelist which entities to intersect with. ' +
  45060. 'e.g., raycaster="objects: [data-raycastable]".');
  45061. }
  45062. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  45063. data.autoRefresh
  45064. ? this.addEventListeners()
  45065. : this.removeEventListeners();
  45066. }
  45067. if (oldData.enabled && !data.enabled) { this.clearAllIntersections(); }
  45068. this.setDirty();
  45069. },
  45070. play: function () {
  45071. this.addEventListeners();
  45072. },
  45073. pause: function () {
  45074. this.removeEventListeners();
  45075. },
  45076. remove: function () {
  45077. if (this.data.showLine) {
  45078. this.el.removeAttribute('line');
  45079. }
  45080. this.clearAllIntersections();
  45081. },
  45082. addEventListeners: function () {
  45083. if (!this.data.autoRefresh) { return; }
  45084. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  45085. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  45086. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  45087. },
  45088. removeEventListeners: function () {
  45089. this.observer.disconnect();
  45090. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  45091. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  45092. },
  45093. /**
  45094. * Mark the object list as dirty, to be refreshed before next raycast.
  45095. */
  45096. setDirty: function () {
  45097. this.dirty = true;
  45098. },
  45099. /**
  45100. * Update list of objects to test for intersection.
  45101. */
  45102. refreshObjects: function () {
  45103. var data = this.data;
  45104. var els;
  45105. // If objects not defined, intersect with everything.
  45106. els = data.objects
  45107. ? this.el.sceneEl.querySelectorAll(data.objects)
  45108. : this.el.sceneEl.querySelectorAll('*');
  45109. this.objects = this.flattenObject3DMaps(els);
  45110. this.dirty = false;
  45111. },
  45112. /**
  45113. * Check for intersections and cleared intersections on an interval.
  45114. */
  45115. tick: function (time) {
  45116. var data = this.data;
  45117. var prevCheckTime = this.prevCheckTime;
  45118. if (!data.enabled) { return; }
  45119. // Only check for intersection if interval time has passed.
  45120. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45121. // Update check time.
  45122. this.prevCheckTime = time;
  45123. this.checkIntersections();
  45124. },
  45125. /**
  45126. * Raycast for intersections and emit events for current and cleared inersections.
  45127. */
  45128. checkIntersections: function () {
  45129. var clearedIntersectedEls = this.clearedIntersectedEls;
  45130. var el = this.el;
  45131. var data = this.data;
  45132. var i;
  45133. var intersectedEls = this.intersectedEls;
  45134. var intersection;
  45135. var intersections = this.intersections;
  45136. var newIntersectedEls = this.newIntersectedEls;
  45137. var newIntersections = this.newIntersections;
  45138. var prevIntersectedEls = this.prevIntersectedEls;
  45139. var rawIntersections = this.rawIntersections;
  45140. // Refresh the object whitelist if needed.
  45141. if (this.dirty) { this.refreshObjects(); }
  45142. // Store old previously intersected entities.
  45143. copyArray(this.prevIntersectedEls, this.intersectedEls);
  45144. // Raycast.
  45145. this.updateOriginDirection();
  45146. rawIntersections.length = 0;
  45147. this.raycaster.intersectObjects(this.objects, true, rawIntersections);
  45148. // Only keep intersections against objects that have a reference to an entity.
  45149. intersections.length = 0;
  45150. intersectedEls.length = 0;
  45151. for (i = 0; i < rawIntersections.length; i++) {
  45152. intersection = rawIntersections[i];
  45153. // Don't intersect with own line.
  45154. if (data.showLine && intersection.object === el.getObject3D('line')) {
  45155. continue;
  45156. }
  45157. if (intersection.object.el) {
  45158. intersections.push(intersection);
  45159. intersectedEls.push(intersection.object.el);
  45160. }
  45161. }
  45162. // Get newly intersected entities.
  45163. newIntersections.length = 0;
  45164. newIntersectedEls.length = 0;
  45165. for (i = 0; i < intersections.length; i++) {
  45166. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  45167. newIntersections.push(intersections[i]);
  45168. newIntersectedEls.push(intersections[i].object.el);
  45169. }
  45170. }
  45171. // Emit intersection cleared on both entities per formerly intersected entity.
  45172. clearedIntersectedEls.length = 0;
  45173. for (i = 0; i < prevIntersectedEls.length; i++) {
  45174. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  45175. prevIntersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  45176. this.intersectedClearedDetail);
  45177. clearedIntersectedEls.push(prevIntersectedEls[i]);
  45178. }
  45179. if (clearedIntersectedEls.length) {
  45180. el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  45181. }
  45182. // Emit intersected on intersected entity per intersected entity.
  45183. for (i = 0; i < newIntersectedEls.length; i++) {
  45184. newIntersectedEls[i].emit(EVENTS.INTERSECT, this.intersectedDetail);
  45185. }
  45186. // Emit all intersections at once on raycasting entity.
  45187. if (newIntersections.length) {
  45188. this.intersectionDetail.els = newIntersectedEls;
  45189. this.intersectionDetail.intersections = newIntersections;
  45190. el.emit(EVENTS.INTERSECTION, this.intersectionDetail);
  45191. }
  45192. // Update line length.
  45193. setTimeout(this.updateLine);
  45194. },
  45195. updateLine: function () {
  45196. var el = this.el;
  45197. var intersections = this.intersections;
  45198. var lineLength;
  45199. if (this.data.showLine) {
  45200. if (intersections.length) {
  45201. if (intersections[0].object.el === el && intersections[1]) {
  45202. lineLength = intersections[1].distance;
  45203. } else {
  45204. lineLength = intersections[0].distance;
  45205. }
  45206. }
  45207. this.drawLine(lineLength);
  45208. }
  45209. },
  45210. /**
  45211. * Return the most recent intersection details for a given entity, if any.
  45212. * @param {AEntity} el
  45213. * @return {Object}
  45214. */
  45215. getIntersection: function (el) {
  45216. var i;
  45217. var intersection;
  45218. for (i = 0; i < this.intersections.length; i++) {
  45219. intersection = this.intersections[i];
  45220. if (intersection.object.el === el) { return intersection; }
  45221. }
  45222. return null;
  45223. },
  45224. /**
  45225. * Update origin and direction of raycaster using entity transforms and supplied origin or
  45226. * direction offsets.
  45227. */
  45228. updateOriginDirection: (function () {
  45229. var direction = new THREE.Vector3();
  45230. var originVec3 = new THREE.Vector3();
  45231. // Closure to make quaternion/vector3 objects private.
  45232. return function updateOriginDirection () {
  45233. var el = this.el;
  45234. var data = this.data;
  45235. if (data.useWorldCoordinates) {
  45236. this.raycaster.set(data.origin, data.direction);
  45237. return;
  45238. }
  45239. // Grab the position and rotation. (As a side effect, this updates el.object3D.matrixWorld.)
  45240. el.object3D.getWorldPosition(originVec3);
  45241. // If non-zero origin, translate the origin into world space.
  45242. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  45243. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  45244. }
  45245. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  45246. // provide. Apply the offset to the direction, then rotation from the object,
  45247. // and normalize.
  45248. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  45249. // Apply offset and direction, in world coordinates.
  45250. this.raycaster.set(originVec3, direction);
  45251. };
  45252. })(),
  45253. /**
  45254. * Create or update line to give raycaster visual representation.
  45255. * Customize the line through through line component.
  45256. * We draw the line in the raycaster component to customize the line to the
  45257. * raycaster's origin, direction, and far.
  45258. *
  45259. * Unlike the raycaster, we create the line as a child of the object. The line will
  45260. * be affected by the transforms of the objects, so we don't have to calculate transforms
  45261. * like we do with the raycaster.
  45262. *
  45263. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  45264. * point. If not provided, length will default to the max length, `raycaster.far`.
  45265. */
  45266. drawLine: function (length) {
  45267. var data = this.data;
  45268. var el = this.el;
  45269. var endVec3;
  45270. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  45271. endVec3 = this.lineData.end === this.lineEndVec3
  45272. ? this.otherLineEndVec3
  45273. : this.lineEndVec3;
  45274. // Treat Infinity as 1000m for the line.
  45275. if (length === undefined) {
  45276. length = data.far === Infinity ? 1000 : data.far;
  45277. }
  45278. // Update the length of the line if given. `unitLineEndVec3` is the direction
  45279. // given by data.direction, then we apply a scalar to give it a length.
  45280. this.lineData.start = data.origin;
  45281. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  45282. el.setAttribute('line', this.lineData);
  45283. },
  45284. /**
  45285. * Return A-Frame attachments of each element's object3D group (e.g., mesh).
  45286. * Children are flattened by one level, removing the THREE.Group wrapper,
  45287. * so that non-recursive raycasting remains useful.
  45288. *
  45289. * Only push children defined as component attachemnts (e.g., setObject3D),
  45290. * NOT actual children in the scene graph hierarchy.
  45291. *
  45292. * @param {Array<Element>} els
  45293. * @return {Array<THREE.Object3D>}
  45294. */
  45295. flattenObject3DMaps: function (els) {
  45296. var key;
  45297. var i;
  45298. var objects = this.objects;
  45299. // Push meshes and other attachments onto list of objects to intersect.
  45300. objects.length = 0;
  45301. for (i = 0; i < els.length; i++) {
  45302. if (els[i].isEntity && els[i].object3D) {
  45303. for (key in els[i].object3DMap) {
  45304. objects.push(els[i].getObject3D(key));
  45305. }
  45306. }
  45307. }
  45308. return objects;
  45309. },
  45310. clearAllIntersections: function () {
  45311. var i;
  45312. for (i = 0; i < this.intersectedEls.length; i++) {
  45313. this.intersectedEls[i].emit(EVENTS.INTERSECT_CLEAR,
  45314. this.intersectedClearedDetail);
  45315. }
  45316. copyArray(this.clearedIntersectedEls, this.intersectedEls);
  45317. this.intersectedEls.length = 0;
  45318. this.intersections.length = 0;
  45319. this.el.emit(EVENTS.INTERSECTION_CLEAR, this.intersectionClearedDetail);
  45320. }
  45321. });
  45322. /**
  45323. * Copy contents of one array to another without allocating new array.
  45324. */
  45325. function copyArray (a, b) {
  45326. var i;
  45327. a.length = b.length;
  45328. for (i = 0; i < b.length; i++) {
  45329. a[i] = b[i];
  45330. }
  45331. }
  45332. },{"../core/component":103,"../lib/three":151,"../utils/":176}],72:[function(_dereq_,module,exports){
  45333. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45334. var registerComponent = _dereq_('../core/component').registerComponent;
  45335. module.exports.Component = registerComponent('rotation', {
  45336. schema: {type: 'vec3'},
  45337. /**
  45338. * Updates object3D rotation.
  45339. */
  45340. update: function () {
  45341. var data = this.data;
  45342. var object3D = this.el.object3D;
  45343. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45344. object3D.rotation.order = 'YXZ';
  45345. },
  45346. remove: function () {
  45347. // Pretty much for mixins.
  45348. this.el.object3D.rotation.set(0, 0, 0);
  45349. }
  45350. });
  45351. },{"../core/component":103,"../lib/three":151}],73:[function(_dereq_,module,exports){
  45352. var registerComponent = _dereq_('../core/component').registerComponent;
  45353. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45354. var zeroScale = 0.00001;
  45355. module.exports.Component = registerComponent('scale', {
  45356. schema: {
  45357. type: 'vec3',
  45358. default: {x: 1, y: 1, z: 1}
  45359. },
  45360. update: function () {
  45361. var data = this.data;
  45362. var object3D = this.el.object3D;
  45363. var x = data.x === 0 ? zeroScale : data.x;
  45364. var y = data.y === 0 ? zeroScale : data.y;
  45365. var z = data.z === 0 ? zeroScale : data.z;
  45366. object3D.scale.set(x, y, z);
  45367. },
  45368. remove: function () {
  45369. // Pretty much for mixins.
  45370. this.el.object3D.scale.set(1, 1, 1);
  45371. }
  45372. });
  45373. },{"../core/component":103}],74:[function(_dereq_,module,exports){
  45374. /* global THREE */
  45375. var register = _dereq_('../../core/component').registerComponent;
  45376. module.exports.Component = register('background', {
  45377. schema: {
  45378. color: {type: 'color', default: 'black'},
  45379. transparent: {default: false}
  45380. },
  45381. update: function () {
  45382. var data = this.data;
  45383. var object3D = this.el.object3D;
  45384. if (data.transparent) {
  45385. object3D.background = null;
  45386. return;
  45387. }
  45388. object3D.background = new THREE.Color(data.color);
  45389. }
  45390. });
  45391. },{"../../core/component":103}],75:[function(_dereq_,module,exports){
  45392. var register = _dereq_('../../core/component').registerComponent;
  45393. module.exports.Component = register('debug', {
  45394. schema: {default: true}
  45395. });
  45396. },{"../../core/component":103}],76:[function(_dereq_,module,exports){
  45397. var registerComponent = _dereq_('../../core/component').registerComponent;
  45398. /**
  45399. * Component to embed an a-frame scene within the layout of a 2D page.
  45400. */
  45401. module.exports.Component = registerComponent('embedded', {
  45402. dependencies: ['vr-mode-ui'],
  45403. schema: {default: true},
  45404. update: function () {
  45405. var sceneEl = this.el;
  45406. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45407. if (this.data === true) {
  45408. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45409. sceneEl.removeFullScreenStyles();
  45410. } else {
  45411. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45412. sceneEl.addFullScreenStyles();
  45413. }
  45414. }
  45415. });
  45416. },{"../../core/component":103}],77:[function(_dereq_,module,exports){
  45417. var register = _dereq_('../../core/component').registerComponent;
  45418. var THREE = _dereq_('../../lib/three');
  45419. var debug = _dereq_('../../utils/debug');
  45420. var warn = debug('components:fog:warn');
  45421. /**
  45422. * Fog component.
  45423. * Applies only to the scene entity.
  45424. */
  45425. module.exports.Component = register('fog', {
  45426. schema: {
  45427. color: {type: 'color', default: '#000'},
  45428. density: {default: 0.00025},
  45429. far: {default: 1000, min: 0},
  45430. near: {default: 1, min: 0},
  45431. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  45432. },
  45433. update: function () {
  45434. var data = this.data;
  45435. var el = this.el;
  45436. var fog = this.el.object3D.fog;
  45437. if (!el.isScene) {
  45438. warn('Fog component can only be applied to <a-scene>');
  45439. return;
  45440. }
  45441. // (Re)create fog if fog doesn't exist or fog type changed.
  45442. if (!fog || data.type !== fog.name) {
  45443. el.object3D.fog = getFog(data);
  45444. el.systems.material.updateMaterials();
  45445. return;
  45446. }
  45447. // Fog data changed. Update fog.
  45448. Object.keys(this.schema).forEach(function (key) {
  45449. var value = data[key];
  45450. if (key === 'color') { value = new THREE.Color(value); }
  45451. fog[key] = value;
  45452. });
  45453. },
  45454. /**
  45455. * Remove fog on remove (callback).
  45456. */
  45457. remove: function () {
  45458. var fog = this.el.object3D.fog;
  45459. if (!fog) { return; }
  45460. fog.far = 0;
  45461. fog.near = 0.1;
  45462. }
  45463. });
  45464. /**
  45465. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  45466. *
  45467. * @param {object} data - Fog data.
  45468. * @returns {object} fog
  45469. */
  45470. function getFog (data) {
  45471. var fog;
  45472. if (data.type === 'exponential') {
  45473. fog = new THREE.FogExp2(data.color, data.density);
  45474. } else {
  45475. fog = new THREE.Fog(data.color, data.near, data.far);
  45476. }
  45477. fog.name = data.type;
  45478. return fog;
  45479. }
  45480. },{"../../core/component":103,"../../lib/three":151,"../../utils/debug":172}],78:[function(_dereq_,module,exports){
  45481. (function (process){
  45482. /* global AFRAME */
  45483. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  45484. var pkg = _dereq_('../../../package');
  45485. var registerComponent = _dereq_('../../core/component').registerComponent;
  45486. var utils = _dereq_('../../utils/');
  45487. /**
  45488. * 0.4.2 to 0.4.x
  45489. * Will need to update this when A-Frame goes to 1.x.x.
  45490. */
  45491. function getFuzzyPatchVersion (version) {
  45492. var split = version.split('.');
  45493. split[2] = 'x';
  45494. return split.join('.');
  45495. }
  45496. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  45497. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  45498. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  45499. var LOADING_MESSAGE = 'Loading Inspector';
  45500. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  45501. module.exports.Component = registerComponent('inspector', {
  45502. schema: {
  45503. url: {default: INSPECTOR_URL}
  45504. },
  45505. init: function () {
  45506. this.firstPlay = true;
  45507. this.onKeydown = this.onKeydown.bind(this);
  45508. this.onMessage = this.onMessage.bind(this);
  45509. this.initOverlay();
  45510. window.addEventListener('keydown', this.onKeydown);
  45511. window.addEventListener('message', this.onMessage);
  45512. },
  45513. play: function () {
  45514. var urlParam;
  45515. if (!this.firstPlay) { return; }
  45516. urlParam = utils.getUrlParameter('inspector');
  45517. if (urlParam !== 'false' && !!urlParam) {
  45518. this.openInspector();
  45519. this.firstPlay = false;
  45520. }
  45521. },
  45522. initOverlay: function () {
  45523. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  45524. this.loadingMessageEl = document.createElement('div');
  45525. this.loadingMessageEl.classList.add('a-inspector-loader');
  45526. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  45527. },
  45528. remove: function () {
  45529. this.removeEventListeners();
  45530. },
  45531. /**
  45532. * <ctrl> + <alt> + i keyboard shortcut.
  45533. */
  45534. onKeydown: function (evt) {
  45535. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  45536. if (!shortcutPressed) { return; }
  45537. this.openInspector();
  45538. },
  45539. showLoader: function () {
  45540. document.body.appendChild(this.loadingMessageEl);
  45541. },
  45542. hideLoader: function () {
  45543. document.body.removeChild(this.loadingMessageEl);
  45544. },
  45545. /**
  45546. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  45547. */
  45548. onMessage: function (evt) {
  45549. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.openInspector(); }
  45550. },
  45551. openInspector: function (focusEl) {
  45552. var self = this;
  45553. var script;
  45554. // Already injected. Open.
  45555. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) {
  45556. AFRAME.INSPECTOR.open(focusEl);
  45557. return;
  45558. }
  45559. this.showLoader();
  45560. // Inject.
  45561. script = document.createElement('script');
  45562. script.src = this.data.url;
  45563. script.setAttribute('data-name', 'aframe-inspector');
  45564. script.setAttribute(AFRAME_INJECTED, '');
  45565. script.onload = function () {
  45566. AFRAME.INSPECTOR.open(focusEl);
  45567. self.hideLoader();
  45568. self.removeEventListeners();
  45569. };
  45570. script.onerror = function () {
  45571. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  45572. };
  45573. document.head.appendChild(script);
  45574. AFRAME.inspectorInjected = true;
  45575. },
  45576. removeEventListeners: function () {
  45577. window.removeEventListener('keydown', this.onKeydown);
  45578. window.removeEventListener('message', this.onMessage);
  45579. }
  45580. });
  45581. }).call(this,_dereq_('_process'))
  45582. },{"../../../package":51,"../../constants":95,"../../core/component":103,"../../utils/":176,"_process":32}],79:[function(_dereq_,module,exports){
  45583. var registerComponent = _dereq_('../../core/component').registerComponent;
  45584. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  45585. module.exports.Component = registerComponent('keyboard-shortcuts', {
  45586. schema: {
  45587. enterVR: {default: true},
  45588. exitVR: {default: true}
  45589. },
  45590. init: function () {
  45591. this.onKeyup = this.onKeyup.bind(this);
  45592. },
  45593. update: function (oldData) {
  45594. var data = this.data;
  45595. this.enterVREnabled = data.enterVR;
  45596. },
  45597. play: function () {
  45598. window.addEventListener('keyup', this.onKeyup, false);
  45599. },
  45600. pause: function () {
  45601. window.removeEventListener('keyup', this.onKeyup);
  45602. },
  45603. onKeyup: function (evt) {
  45604. var scene = this.el;
  45605. if (!shouldCaptureKeyEvent(evt)) { return; }
  45606. if (this.enterVREnabled && evt.keyCode === 70) { // f.
  45607. scene.enterVR();
  45608. }
  45609. if (this.enterVREnabled && evt.keyCode === 27) { // escape.
  45610. scene.exitVR();
  45611. }
  45612. }
  45613. });
  45614. },{"../../core/component":103,"../../utils/":176}],80:[function(_dereq_,module,exports){
  45615. var debug = _dereq_('../../utils/debug');
  45616. var registerComponent = _dereq_('../../core/component').registerComponent;
  45617. var warn = debug('components:pool:warn');
  45618. /**
  45619. * Pool component to reuse entities.
  45620. * Avoids creating and destroying the same kind of entities.
  45621. * Helps reduce GC pauses. For example in a game to reuse enemies entities.
  45622. *
  45623. * @member {array} availableEls - Available entities in the pool.
  45624. * @member {array} usedEls - Entities of the pool in use.
  45625. */
  45626. module.exports.Component = registerComponent('pool', {
  45627. schema: {
  45628. container: {default: ''},
  45629. mixin: {default: ''},
  45630. size: {default: 0},
  45631. dynamic: {default: false}
  45632. },
  45633. multiple: true,
  45634. initPool: function () {
  45635. var i;
  45636. this.availableEls = [];
  45637. this.usedEls = [];
  45638. if (!this.data.mixin) {
  45639. warn('No mixin provided for pool component.');
  45640. }
  45641. if (this.data.container) {
  45642. this.container = document.querySelector(this.data.container);
  45643. if (!this.container) {
  45644. warn('Container ' + this.data.container + ' not found.');
  45645. }
  45646. }
  45647. this.container = this.container || this.el;
  45648. for (i = 0; i < this.data.size; ++i) {
  45649. this.createEntity();
  45650. }
  45651. },
  45652. update: function (oldData) {
  45653. var data = this.data;
  45654. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  45655. this.initPool();
  45656. }
  45657. },
  45658. /**
  45659. * Add a new entity to the list of available entities.
  45660. */
  45661. createEntity: function () {
  45662. var el;
  45663. el = document.createElement('a-entity');
  45664. el.play = this.wrapPlay(el.play);
  45665. el.setAttribute('mixin', this.data.mixin);
  45666. el.object3D.visible = false;
  45667. el.pause();
  45668. this.container.appendChild(el);
  45669. this.availableEls.push(el);
  45670. },
  45671. /**
  45672. * Play wrapper for pooled entities. When pausing and playing a scene, don't want to play
  45673. * entities that are not in use.
  45674. */
  45675. wrapPlay: function (playMethod) {
  45676. var usedEls = this.usedEls;
  45677. return function () {
  45678. if (usedEls.indexOf(this) === -1) { return; }
  45679. playMethod.call(this);
  45680. };
  45681. },
  45682. /**
  45683. * Used to request one of the available entities of the pool.
  45684. */
  45685. requestEntity: function () {
  45686. var el;
  45687. if (this.availableEls.length === 0) {
  45688. if (this.data.dynamic === false) {
  45689. warn('Requested entity from empty pool: ' + this.attrName);
  45690. return;
  45691. } else {
  45692. warn('Requested entity from empty pool. This pool is dynamic and will resize ' +
  45693. 'automatically. You might want to increase its initial size: ' + this.attrName);
  45694. }
  45695. this.createEntity();
  45696. }
  45697. el = this.availableEls.shift();
  45698. this.usedEls.push(el);
  45699. el.object3D.visible = true;
  45700. return el;
  45701. },
  45702. /**
  45703. * Used to return a used entity to the pool.
  45704. */
  45705. returnEntity: function (el) {
  45706. var index = this.usedEls.indexOf(el);
  45707. if (index === -1) {
  45708. warn('The returned entity was not previously pooled from ' + this.attrName);
  45709. return;
  45710. }
  45711. this.usedEls.splice(index, 1);
  45712. this.availableEls.push(el);
  45713. el.object3D.visible = false;
  45714. el.pause();
  45715. return el;
  45716. }
  45717. });
  45718. },{"../../core/component":103,"../../utils/debug":172}],81:[function(_dereq_,module,exports){
  45719. /* global ImageData, URL */
  45720. var registerComponent = _dereq_('../../core/component').registerComponent;
  45721. var THREE = _dereq_('../../lib/three');
  45722. var VERTEX_SHADER = [
  45723. 'attribute vec3 position;',
  45724. 'attribute vec2 uv;',
  45725. 'uniform mat4 projectionMatrix;',
  45726. 'uniform mat4 modelViewMatrix;',
  45727. 'varying vec2 vUv;',
  45728. 'void main() {',
  45729. ' vUv = vec2( 1.- uv.x, uv.y );',
  45730. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  45731. '}'
  45732. ].join('\n');
  45733. var FRAGMENT_SHADER = [
  45734. 'precision mediump float;',
  45735. 'uniform samplerCube map;',
  45736. 'varying vec2 vUv;',
  45737. '#define M_PI 3.141592653589793238462643383279',
  45738. 'void main() {',
  45739. ' vec2 uv = vUv;',
  45740. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  45741. ' float latitude = uv.y * M_PI;',
  45742. ' vec3 dir = vec3(',
  45743. ' - sin( longitude ) * sin( latitude ),',
  45744. ' cos( latitude ),',
  45745. ' - cos( longitude ) * sin( latitude )',
  45746. ' );',
  45747. ' normalize( dir );',
  45748. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  45749. '}'
  45750. ].join('\n');
  45751. /**
  45752. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  45753. * It can be configured to either take 360&deg; captures (`equirectangular`)
  45754. * or regular screenshots (`projection`)
  45755. *
  45756. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  45757. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  45758. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  45759. * WebGLRenderTarget with an ortographic camera.
  45760. */
  45761. module.exports.Component = registerComponent('screenshot', {
  45762. schema: {
  45763. width: {default: 4096},
  45764. height: {default: 2048},
  45765. camera: {type: 'selector'}
  45766. },
  45767. init: function () {
  45768. var el = this.el;
  45769. var self = this;
  45770. if (el.renderer) {
  45771. setup();
  45772. } else {
  45773. el.addEventListener('render-target-loaded', setup);
  45774. }
  45775. function setup () {
  45776. var gl = el.renderer.getContext();
  45777. if (!gl) { return; }
  45778. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  45779. self.material = new THREE.RawShaderMaterial({
  45780. uniforms: {map: {type: 't', value: null}},
  45781. vertexShader: VERTEX_SHADER,
  45782. fragmentShader: FRAGMENT_SHADER,
  45783. side: THREE.DoubleSide
  45784. });
  45785. self.quad = new THREE.Mesh(
  45786. new THREE.PlaneBufferGeometry(1, 1),
  45787. self.material
  45788. );
  45789. self.quad.visible = false;
  45790. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  45791. self.canvas = document.createElement('canvas');
  45792. self.ctx = self.canvas.getContext('2d');
  45793. el.object3D.add(self.quad);
  45794. self.onKeyDown = self.onKeyDown.bind(self);
  45795. }
  45796. },
  45797. getRenderTarget: function (width, height) {
  45798. return new THREE.WebGLRenderTarget(width, height, {
  45799. minFilter: THREE.LinearFilter,
  45800. magFilter: THREE.LinearFilter,
  45801. wrapS: THREE.ClampToEdgeWrapping,
  45802. wrapT: THREE.ClampToEdgeWrapping,
  45803. format: THREE.RGBAFormat,
  45804. type: THREE.UnsignedByteType
  45805. });
  45806. },
  45807. resize: function (width, height) {
  45808. // Resize quad.
  45809. this.quad.scale.set(width, height, 1);
  45810. // Resize camera.
  45811. this.camera.left = -1 * width / 2;
  45812. this.camera.right = width / 2;
  45813. this.camera.top = height / 2;
  45814. this.camera.bottom = -1 * height / 2;
  45815. this.camera.updateProjectionMatrix();
  45816. // Resize canvas.
  45817. this.canvas.width = width;
  45818. this.canvas.height = height;
  45819. },
  45820. play: function () {
  45821. window.addEventListener('keydown', this.onKeyDown);
  45822. },
  45823. /**
  45824. * <ctrl> + <alt> + s = Regular screenshot.
  45825. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  45826. */
  45827. onKeyDown: function (evt) {
  45828. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  45829. if (!this.data || !shortcutPressed) { return; }
  45830. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  45831. this.capture(projection);
  45832. },
  45833. /**
  45834. * Capture a screenshot of the scene.
  45835. *
  45836. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  45837. */
  45838. setCapture: function (projection) {
  45839. var el = this.el;
  45840. var size;
  45841. var camera;
  45842. var cubeCamera;
  45843. // Configure camera.
  45844. if (projection === 'perspective') {
  45845. // Quad is only used in equirectangular mode. Hide it in this case.
  45846. this.quad.visible = false;
  45847. // Use scene camera.
  45848. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  45849. size = {width: this.data.width, height: this.data.height};
  45850. } else {
  45851. // Use ortho camera.
  45852. camera = this.camera;
  45853. // Create cube camera and copy position from scene camera.
  45854. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  45855. Math.min(this.cubeMapSize, 2048));
  45856. // Copy camera position into cube camera;
  45857. el.camera.getWorldPosition(cubeCamera.position);
  45858. el.camera.getWorldQuaternion(cubeCamera.quaternion);
  45859. // Render scene with cube camera.
  45860. cubeCamera.update(el.renderer, el.object3D);
  45861. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  45862. size = {width: this.data.width, height: this.data.height};
  45863. // Use quad to project image taken by the cube camera.
  45864. this.quad.visible = true;
  45865. }
  45866. return {
  45867. camera: camera,
  45868. size: size,
  45869. projection: projection
  45870. };
  45871. },
  45872. /**
  45873. * Maintained for backwards compatibility.
  45874. */
  45875. capture: function (projection) {
  45876. var isVREnabled = this.el.renderer.vr.enabled;
  45877. var renderer = this.el.renderer;
  45878. var params;
  45879. // Disable VR.
  45880. renderer.vr.enabled = false;
  45881. params = this.setCapture(projection);
  45882. this.renderCapture(params.camera, params.size, params.projection);
  45883. // Trigger file download.
  45884. this.saveCapture();
  45885. // Restore VR.
  45886. renderer.vr.enabled = isVREnabled;
  45887. },
  45888. /**
  45889. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  45890. */
  45891. getCanvas: function (projection) {
  45892. var params = this.setCapture(projection);
  45893. this.renderCapture(params.camera, params.size, params.projection);
  45894. return this.canvas;
  45895. },
  45896. renderCapture: function (camera, size, projection) {
  45897. var autoClear = this.el.renderer.autoClear;
  45898. var el = this.el;
  45899. var imageData;
  45900. var output;
  45901. var pixels;
  45902. var renderer = el.renderer;
  45903. // Create rendering target and buffer to store the read pixels.
  45904. output = this.getRenderTarget(size.width, size.height);
  45905. pixels = new Uint8Array(4 * size.width * size.height);
  45906. // Resize quad, camera, and canvas.
  45907. this.resize(size.width, size.height);
  45908. // Render scene to render target.
  45909. renderer.autoClear = true;
  45910. renderer.render(el.object3D, camera, output, true);
  45911. renderer.autoClear = autoClear;
  45912. // Read image pizels back.
  45913. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  45914. if (projection === 'perspective') {
  45915. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  45916. }
  45917. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  45918. // Hide quad after projecting the image.
  45919. this.quad.visible = false;
  45920. // Copy pixels into canvas.
  45921. this.ctx.putImageData(imageData, 0, 0);
  45922. },
  45923. flipPixelsVertically: function (pixels, width, height) {
  45924. var flippedPixels = pixels.slice(0);
  45925. for (var x = 0; x < width; ++x) {
  45926. for (var y = 0; y < height; ++y) {
  45927. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  45928. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  45929. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  45930. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  45931. }
  45932. }
  45933. return flippedPixels;
  45934. },
  45935. /**
  45936. * Download capture to file.
  45937. */
  45938. saveCapture: function () {
  45939. this.canvas.toBlob(function (blob) {
  45940. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  45941. var linkEl = document.createElement('a');
  45942. var url = URL.createObjectURL(blob);
  45943. linkEl.href = url;
  45944. linkEl.setAttribute('download', fileName);
  45945. linkEl.innerHTML = 'downloading...';
  45946. linkEl.style.display = 'none';
  45947. document.body.appendChild(linkEl);
  45948. setTimeout(function () {
  45949. linkEl.click();
  45950. document.body.removeChild(linkEl);
  45951. }, 1);
  45952. }, 'image/png');
  45953. }
  45954. });
  45955. },{"../../core/component":103,"../../lib/three":151}],82:[function(_dereq_,module,exports){
  45956. var registerComponent = _dereq_('../../core/component').registerComponent;
  45957. var RStats = _dereq_('../../../vendor/rStats');
  45958. var utils = _dereq_('../../utils');
  45959. _dereq_('../../../vendor/rStats.extras');
  45960. _dereq_('../../lib/rStatsAframe');
  45961. var AFrameStats = window.aframeStats;
  45962. var bind = utils.bind;
  45963. var HIDDEN_CLASS = 'a-hidden';
  45964. var ThreeStats = window.threeStats;
  45965. /**
  45966. * Stats appended to document.body by RStats.
  45967. */
  45968. module.exports.Component = registerComponent('stats', {
  45969. schema: {default: true},
  45970. init: function () {
  45971. var scene = this.el;
  45972. if (utils.getUrlParameter('stats') === 'false') { return; }
  45973. this.stats = createStats(scene);
  45974. this.statsEl = document.querySelector('.rs-base');
  45975. this.hideBound = bind(this.hide, this);
  45976. this.showBound = bind(this.show, this);
  45977. scene.addEventListener('enter-vr', this.hideBound);
  45978. scene.addEventListener('exit-vr', this.showBound);
  45979. },
  45980. update: function () {
  45981. if (!this.stats) { return; }
  45982. return (!this.data) ? this.hide() : this.show();
  45983. },
  45984. remove: function () {
  45985. this.el.removeEventListener('enter-vr', this.hideBound);
  45986. this.el.removeEventListener('exit-vr', this.showBound);
  45987. if (!this.statsEl) { return; } // Scene detached.
  45988. this.statsEl.parentNode.removeChild(this.statsEl);
  45989. },
  45990. tick: function () {
  45991. var stats = this.stats;
  45992. if (!stats) { return; }
  45993. stats('rAF').tick();
  45994. stats('FPS').frame();
  45995. stats().update();
  45996. },
  45997. hide: function () {
  45998. this.statsEl.classList.add(HIDDEN_CLASS);
  45999. },
  46000. show: function () {
  46001. this.statsEl.classList.remove(HIDDEN_CLASS);
  46002. }
  46003. });
  46004. function createStats (scene) {
  46005. var threeStats = new ThreeStats(scene.renderer);
  46006. var aframeStats = new AFrameStats(scene);
  46007. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46008. return new RStats({
  46009. css: [], // Our stylesheet is injected from `src/index.js`.
  46010. values: {
  46011. fps: {caption: 'fps', below: 30}
  46012. },
  46013. groups: [
  46014. {caption: 'Framerate', values: ['fps', 'raf']}
  46015. ],
  46016. plugins: plugins
  46017. });
  46018. }
  46019. },{"../../../vendor/rStats":186,"../../../vendor/rStats.extras":185,"../../core/component":103,"../../lib/rStatsAframe":150,"../../utils":176}],83:[function(_dereq_,module,exports){
  46020. var registerComponent = _dereq_('../../core/component').registerComponent;
  46021. var constants = _dereq_('../../constants/');
  46022. var utils = _dereq_('../../utils/');
  46023. var bind = utils.bind;
  46024. var ENTER_VR_CLASS = 'a-enter-vr';
  46025. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46026. var HIDDEN_CLASS = 'a-hidden';
  46027. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46028. /**
  46029. * UI for entering VR mode.
  46030. */
  46031. module.exports.Component = registerComponent('vr-mode-ui', {
  46032. dependencies: ['canvas'],
  46033. schema: {
  46034. enabled: {default: true},
  46035. enterVRButton: {default: ''}
  46036. },
  46037. init: function () {
  46038. var self = this;
  46039. var sceneEl = this.el;
  46040. if (utils.getUrlParameter('ui') === 'false') { return; }
  46041. this.insideLoader = false;
  46042. this.enterVREl = null;
  46043. this.orientationModalEl = null;
  46044. this.bindMethods();
  46045. // Hide/show VR UI when entering/exiting VR mode.
  46046. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  46047. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  46048. window.addEventListener('message', function (event) {
  46049. if (event.data.type === 'loaderReady') {
  46050. self.insideLoader = true;
  46051. self.remove();
  46052. }
  46053. });
  46054. // Modal that tells the user to change orientation if in portrait.
  46055. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  46056. },
  46057. bindMethods: function () {
  46058. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  46059. this.onModalClick = bind(this.onModalClick, this);
  46060. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  46061. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  46062. },
  46063. /**
  46064. * Exit VR when modal clicked.
  46065. */
  46066. onModalClick: function () {
  46067. this.el.exitVR();
  46068. },
  46069. /**
  46070. * Enter VR when modal clicked.
  46071. */
  46072. onEnterVRButtonClick: function () {
  46073. this.el.enterVR();
  46074. },
  46075. update: function () {
  46076. var data = this.data;
  46077. var sceneEl = this.el;
  46078. if (!data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46079. return this.remove();
  46080. }
  46081. if (this.enterVREl || this.orientationModalEl) { return; }
  46082. // Add UI if enabled and not already present.
  46083. if (data.enterVRButton) {
  46084. // Custom button.
  46085. this.enterVREl = document.querySelector(data.enterVRButton);
  46086. this.enterVREl.addEventListener('click', this.onEnterVRButtonClick);
  46087. } else {
  46088. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  46089. sceneEl.appendChild(this.enterVREl);
  46090. }
  46091. this.orientationModalEl = createOrientationModal(this.onModalClick);
  46092. sceneEl.appendChild(this.orientationModalEl);
  46093. this.updateEnterVRInterface();
  46094. },
  46095. remove: function () {
  46096. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46097. if (uiElement && uiElement.parentNode) {
  46098. uiElement.parentNode.removeChild(uiElement);
  46099. }
  46100. });
  46101. },
  46102. updateEnterVRInterface: function () {
  46103. this.toggleEnterVRButtonIfNeeded();
  46104. this.toggleOrientationModalIfNeeded();
  46105. },
  46106. toggleEnterVRButtonIfNeeded: function () {
  46107. var sceneEl = this.el;
  46108. if (!this.enterVREl) { return; }
  46109. if (sceneEl.is('vr-mode')) {
  46110. this.enterVREl.classList.add(HIDDEN_CLASS);
  46111. } else {
  46112. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46113. }
  46114. },
  46115. toggleOrientationModalIfNeeded: function () {
  46116. var sceneEl = this.el;
  46117. var orientationModalEl = this.orientationModalEl;
  46118. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46119. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46120. // Show if in VR mode on portrait.
  46121. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46122. } else {
  46123. orientationModalEl.classList.add(HIDDEN_CLASS);
  46124. }
  46125. }
  46126. });
  46127. /**
  46128. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  46129. *
  46130. * Structure: <div><button></div>
  46131. *
  46132. * @param {function} onClick - click event handler
  46133. * @returns {Element} Wrapper <div>.
  46134. */
  46135. function createEnterVRButton (onClick) {
  46136. var vrButton;
  46137. var wrapper;
  46138. // Create elements.
  46139. wrapper = document.createElement('div');
  46140. wrapper.classList.add(ENTER_VR_CLASS);
  46141. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46142. vrButton = document.createElement('button');
  46143. vrButton.className = ENTER_VR_BTN_CLASS;
  46144. vrButton.setAttribute('title',
  46145. 'Enter VR mode with a headset or fullscreen mode on a desktop. ' +
  46146. 'Visit https://webvr.rocks or https://webvr.info for more information.');
  46147. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46148. // Insert elements.
  46149. wrapper.appendChild(vrButton);
  46150. vrButton.addEventListener('click', function (evt) {
  46151. onClick();
  46152. evt.stopPropagation();
  46153. });
  46154. return wrapper;
  46155. }
  46156. /**
  46157. * Creates a modal dialog to request the user to switch to landscape orientation.
  46158. *
  46159. * @param {function} onClick - click event handler
  46160. * @returns {Element} Wrapper <div>.
  46161. */
  46162. function createOrientationModal (onClick) {
  46163. var modal = document.createElement('div');
  46164. modal.className = ORIENTATION_MODAL_CLASS;
  46165. modal.classList.add(HIDDEN_CLASS);
  46166. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46167. var exit = document.createElement('button');
  46168. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46169. exit.innerHTML = 'Exit VR';
  46170. // Exit VR on close.
  46171. exit.addEventListener('click', onClick);
  46172. modal.appendChild(exit);
  46173. return modal;
  46174. }
  46175. },{"../../constants/":95,"../../core/component":103,"../../utils/":176}],84:[function(_dereq_,module,exports){
  46176. var component = _dereq_('../core/component');
  46177. var THREE = _dereq_('../lib/three');
  46178. var bind = _dereq_('../utils/bind');
  46179. var registerComponent = component.registerComponent;
  46180. /**
  46181. * Shadow component.
  46182. *
  46183. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46184. * shadows as specified by the `cast` and `receive` properties.
  46185. */
  46186. module.exports.Component = registerComponent('shadow', {
  46187. schema: {
  46188. cast: {default: true},
  46189. receive: {default: true}
  46190. },
  46191. init: function () {
  46192. this.onMeshChanged = bind(this.update, this);
  46193. this.el.addEventListener('object3dset', this.onMeshChanged);
  46194. this.system.setShadowMapEnabled(true);
  46195. },
  46196. update: function () {
  46197. var data = this.data;
  46198. this.updateDescendants(data.cast, data.receive);
  46199. },
  46200. remove: function () {
  46201. var el = this.el;
  46202. el.removeEventListener('object3dset', this.onMeshChanged);
  46203. this.updateDescendants(false, false);
  46204. },
  46205. updateDescendants: function (cast, receive) {
  46206. var sceneEl = this.el.sceneEl;
  46207. this.el.object3D.traverse(function (node) {
  46208. if (!(node instanceof THREE.Mesh)) { return; }
  46209. node.castShadow = cast;
  46210. node.receiveShadow = receive;
  46211. // If scene has already rendered, materials must be updated.
  46212. if (sceneEl.hasLoaded && node.material) {
  46213. var materials = Array.isArray(node.material) ? node.material : [node.material];
  46214. for (var i = 0; i < materials.length; i++) {
  46215. materials[i].needsUpdate = true;
  46216. }
  46217. }
  46218. });
  46219. }
  46220. });
  46221. },{"../core/component":103,"../lib/three":151,"../utils/bind":170}],85:[function(_dereq_,module,exports){
  46222. var registerComponent = _dereq_('../core/component').registerComponent;
  46223. var debug = _dereq_('../utils/debug');
  46224. var THREE = _dereq_('../lib/three');
  46225. var warn = debug('components:sound:warn');
  46226. /**
  46227. * Sound component.
  46228. */
  46229. module.exports.Component = registerComponent('sound', {
  46230. schema: {
  46231. autoplay: {default: false},
  46232. distanceModel: {default: 'inverse', oneOf: ['linear', 'inverse', 'exponential']},
  46233. loop: {default: false},
  46234. maxDistance: {default: 10000},
  46235. on: {default: ''},
  46236. poolSize: {default: 1},
  46237. positional: {default: true},
  46238. refDistance: {default: 1},
  46239. rolloffFactor: {default: 1},
  46240. src: {type: 'audio'},
  46241. volume: {default: 1}
  46242. },
  46243. multiple: true,
  46244. init: function () {
  46245. var self = this;
  46246. this.listener = null;
  46247. this.audioLoader = new THREE.AudioLoader();
  46248. this.pool = new THREE.Group();
  46249. this.loaded = false;
  46250. this.mustPlay = false;
  46251. // Don't pass evt because playSound takes a function as parameter.
  46252. this.playSoundBound = function () { self.playSound(); };
  46253. },
  46254. update: function (oldData) {
  46255. var data = this.data;
  46256. var i;
  46257. var sound;
  46258. var srcChanged = data.src !== oldData.src;
  46259. // Create new sound if not yet created or changing `src`.
  46260. if (srcChanged) {
  46261. if (!data.src) { return; }
  46262. this.setupSound();
  46263. }
  46264. for (i = 0; i < this.pool.children.length; i++) {
  46265. sound = this.pool.children[i];
  46266. if (data.positional) {
  46267. sound.setDistanceModel(data.distanceModel);
  46268. sound.setMaxDistance(data.maxDistance);
  46269. sound.setRefDistance(data.refDistance);
  46270. sound.setRolloffFactor(data.rolloffFactor);
  46271. }
  46272. sound.setLoop(data.loop);
  46273. sound.setVolume(data.volume);
  46274. sound.isPaused = false;
  46275. }
  46276. if (data.on !== oldData.on) {
  46277. this.updateEventListener(oldData.on);
  46278. }
  46279. // All sound values set. Load in `src`.
  46280. if (srcChanged) {
  46281. var self = this;
  46282. this.loaded = false;
  46283. this.audioLoader.load(data.src, function (buffer) {
  46284. for (i = 0; i < self.pool.children.length; i++) {
  46285. sound = self.pool.children[i];
  46286. sound.setBuffer(buffer);
  46287. }
  46288. self.loaded = true;
  46289. // Remove this key from cache, otherwise we can't play it again
  46290. THREE.Cache.remove(data.src);
  46291. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46292. self.el.emit('sound-loaded', self.evtDetail, false);
  46293. });
  46294. }
  46295. },
  46296. pause: function () {
  46297. this.stopSound();
  46298. this.removeEventListener();
  46299. },
  46300. play: function () {
  46301. if (this.data.autoplay) { this.playSound(); }
  46302. this.updateEventListener();
  46303. },
  46304. remove: function () {
  46305. var i;
  46306. var sound;
  46307. this.removeEventListener();
  46308. if (this.el.getObject3D(this.attrName)) {
  46309. this.el.removeObject3D(this.attrName);
  46310. }
  46311. try {
  46312. for (i = 0; i < this.pool.children.length; i++) {
  46313. sound = this.pool.children[i];
  46314. sound.disconnect();
  46315. }
  46316. } catch (e) {
  46317. // disconnect() will throw if it was never connected initially.
  46318. warn('Audio source not properly disconnected');
  46319. }
  46320. },
  46321. /**
  46322. * Update listener attached to the user defined on event.
  46323. */
  46324. updateEventListener: function (oldEvt) {
  46325. var el = this.el;
  46326. if (oldEvt) { el.removeEventListener(oldEvt, this.playSoundBound); }
  46327. el.addEventListener(this.data.on, this.playSoundBound);
  46328. },
  46329. removeEventListener: function () {
  46330. this.el.removeEventListener(this.data.on, this.playSoundBound);
  46331. },
  46332. /**
  46333. * Removes current sound object, creates new sound object, adds to entity.
  46334. *
  46335. * @returns {object} sound
  46336. */
  46337. setupSound: function () {
  46338. var el = this.el;
  46339. var i;
  46340. var sceneEl = el.sceneEl;
  46341. var self = this;
  46342. var sound;
  46343. if (this.pool.children.length > 0) {
  46344. this.stopSound();
  46345. el.removeObject3D('sound');
  46346. }
  46347. // Only want one AudioListener. Cache it on the scene.
  46348. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46349. sceneEl.audioListener = listener;
  46350. if (sceneEl.camera) {
  46351. sceneEl.camera.add(listener);
  46352. }
  46353. // Wait for camera if necessary.
  46354. sceneEl.addEventListener('camera-set-active', function (evt) {
  46355. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46356. });
  46357. // Create [poolSize] audio instances and attach them to pool
  46358. this.pool = new THREE.Group();
  46359. for (i = 0; i < this.data.poolSize; i++) {
  46360. sound = this.data.positional
  46361. ? new THREE.PositionalAudio(listener)
  46362. : new THREE.Audio(listener);
  46363. this.pool.add(sound);
  46364. }
  46365. el.setObject3D(this.attrName, this.pool);
  46366. for (i = 0; i < this.pool.children.length; i++) {
  46367. sound = this.pool.children[i];
  46368. sound.onEnded = function () {
  46369. this.isPlaying = false;
  46370. self.el.emit('sound-ended', self.evtDetail, false);
  46371. };
  46372. }
  46373. },
  46374. /**
  46375. * Pause all the sounds in the pool.
  46376. */
  46377. pauseSound: function () {
  46378. var i;
  46379. var sound;
  46380. this.isPlaying = false;
  46381. for (i = 0; i < this.pool.children.length; i++) {
  46382. sound = this.pool.children[i];
  46383. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) {
  46384. continue;
  46385. }
  46386. sound.isPaused = true;
  46387. sound.pause();
  46388. }
  46389. },
  46390. /**
  46391. * Look for an unused sound in the pool and play it if found.
  46392. */
  46393. playSound: function (processSound) {
  46394. var found;
  46395. var i;
  46396. var sound;
  46397. if (!this.loaded) {
  46398. warn('Sound not loaded yet. It will be played once it finished loading');
  46399. this.mustPlay = true;
  46400. return;
  46401. }
  46402. found = false;
  46403. this.isPlaying = true;
  46404. for (i = 0; i < this.pool.children.length; i++) {
  46405. sound = this.pool.children[i];
  46406. if (!sound.isPlaying && sound.buffer && !found) {
  46407. if (processSound) { processSound(sound); }
  46408. sound.play();
  46409. sound.isPaused = false;
  46410. found = true;
  46411. continue;
  46412. }
  46413. }
  46414. if (!found) {
  46415. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46416. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  46417. return;
  46418. }
  46419. this.mustPlay = false;
  46420. },
  46421. /**
  46422. * Stop all the sounds in the pool.
  46423. */
  46424. stopSound: function () {
  46425. var i;
  46426. var sound;
  46427. this.isPlaying = false;
  46428. for (i = 0; i < this.pool.children.length; i++) {
  46429. sound = this.pool.children[i];
  46430. if (!sound.source || !sound.source.buffer) { return; }
  46431. sound.stop();
  46432. }
  46433. }
  46434. });
  46435. },{"../core/component":103,"../lib/three":151,"../utils/debug":172}],86:[function(_dereq_,module,exports){
  46436. var createTextGeometry = _dereq_('three-bmfont-text');
  46437. var loadBMFont = _dereq_('load-bmfont');
  46438. var registerComponent = _dereq_('../core/component').registerComponent;
  46439. var coreShader = _dereq_('../core/shader');
  46440. var THREE = _dereq_('../lib/three');
  46441. var utils = _dereq_('../utils/');
  46442. var error = utils.debug('components:text:error');
  46443. var shaders = coreShader.shaders;
  46444. var warn = utils.debug('components:text:warn');
  46445. // 1 to match other A-Frame default widths.
  46446. var DEFAULT_WIDTH = 1;
  46447. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46448. var MAX_ANISOTROPY = 16;
  46449. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46450. var FONTS = {
  46451. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46452. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46453. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46454. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46455. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46456. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46457. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46458. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46459. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46460. };
  46461. var MSDF_FONTS = ['roboto'];
  46462. var DEFAULT_FONT = 'roboto';
  46463. module.exports.FONTS = FONTS;
  46464. var cache = new PromiseCache();
  46465. var fontWidthFactors = {};
  46466. var textures = {};
  46467. // Regular expression for detecting a URLs with a protocol prefix.
  46468. var protocolRe = /^\w+:/;
  46469. /**
  46470. * SDF-based text component.
  46471. * Based on https://github.com/Jam3/three-bmfont-text.
  46472. *
  46473. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46474. * original `sdf` shader.
  46475. */
  46476. module.exports.Component = registerComponent('text', {
  46477. multiple: true,
  46478. schema: {
  46479. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46480. alphaTest: {default: 0.5},
  46481. // `anchor` defaults to center to match geometries.
  46482. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46483. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46484. color: {type: 'color', default: '#FFF'},
  46485. font: {type: 'string', default: DEFAULT_FONT},
  46486. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46487. fontImage: {type: 'string'},
  46488. // `height` has no default, will be populated at layout.
  46489. height: {type: 'number'},
  46490. letterSpacing: {type: 'number', default: 0},
  46491. // `lineHeight` defaults to font's `lineHeight` value.
  46492. lineHeight: {type: 'number'},
  46493. // `negate` must be true for fonts generated with older versions of msdfgen (white background).
  46494. negate: {type: 'boolean', default: true},
  46495. opacity: {type: 'number', default: 1.0},
  46496. shader: {default: 'sdf', oneOf: shaders},
  46497. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46498. tabSize: {default: 4},
  46499. transparent: {default: true},
  46500. value: {type: 'string'},
  46501. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46502. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46503. width: {type: 'number'},
  46504. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46505. wrapCount: {type: 'number', default: 40},
  46506. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46507. wrapPixels: {type: 'number'},
  46508. // `xOffset` to add padding.
  46509. xOffset: {type: 'number', default: 0},
  46510. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46511. yOffset: {type: 'number', default: 0},
  46512. // `zOffset` will provide a small z offset to avoid z-fighting.
  46513. zOffset: {type: 'number', default: 0.001}
  46514. },
  46515. init: function () {
  46516. this.shaderData = {};
  46517. this.geometry = createTextGeometry();
  46518. this.createOrUpdateMaterial();
  46519. this.mesh = new THREE.Mesh(this.geometry, this.material);
  46520. this.el.setObject3D(this.attrName, this.mesh);
  46521. },
  46522. update: function (oldData) {
  46523. var data = this.data;
  46524. var font = this.currentFont;
  46525. if (textures[data.font]) {
  46526. this.texture = textures[data.font];
  46527. } else {
  46528. // Create texture per font.
  46529. this.texture = textures[data.font] = new THREE.Texture();
  46530. this.texture.anisotropy = MAX_ANISOTROPY;
  46531. }
  46532. // Update material.
  46533. this.createOrUpdateMaterial();
  46534. // New font. `updateFont` will later change data and layout.
  46535. if (oldData.font !== data.font) {
  46536. this.updateFont();
  46537. return;
  46538. }
  46539. // Update geometry and layout.
  46540. if (font) {
  46541. this.updateGeometry(this.geometry, font);
  46542. this.updateLayout();
  46543. }
  46544. },
  46545. /**
  46546. * Clean up geometry, material, texture, mesh, objects.
  46547. */
  46548. remove: function () {
  46549. this.geometry.dispose();
  46550. this.geometry = null;
  46551. this.el.removeObject3D(this.attrName);
  46552. this.material.dispose();
  46553. this.material = null;
  46554. this.texture.dispose();
  46555. this.texture = null;
  46556. if (this.shaderObject) {
  46557. delete this.shaderObject;
  46558. }
  46559. },
  46560. /**
  46561. * Update the shader of the material.
  46562. */
  46563. createOrUpdateMaterial: function () {
  46564. var data = this.data;
  46565. var hasChangedShader;
  46566. var material = this.material;
  46567. var NewShader;
  46568. var shaderData = this.shaderData;
  46569. var shaderName;
  46570. // Infer shader if using a stock font (or from `-msdf` filename convention).
  46571. shaderName = data.shader;
  46572. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  46573. shaderName = 'msdf';
  46574. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  46575. shaderName = 'sdf';
  46576. }
  46577. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  46578. shaderData.alphaTest = data.alphaTest;
  46579. shaderData.color = data.color;
  46580. shaderData.map = this.texture;
  46581. shaderData.opacity = data.opacity;
  46582. shaderData.side = parseSide(data.side);
  46583. shaderData.transparent = data.transparent;
  46584. shaderData.negate = data.negate;
  46585. // Shader has not changed, do an update.
  46586. if (!hasChangedShader) {
  46587. // Update shader material.
  46588. this.shaderObject.update(shaderData);
  46589. // Apparently, was not set on `init` nor `update`.
  46590. material.transparent = shaderData.transparent;
  46591. material.side = shaderData.side;
  46592. return;
  46593. }
  46594. // Shader has changed. Create a shader material.
  46595. NewShader = createShader(this.el, shaderName, shaderData);
  46596. this.material = NewShader.material;
  46597. this.shaderObject = NewShader.shader;
  46598. // Set new shader material.
  46599. this.material.side = shaderData.side;
  46600. if (this.mesh) { this.mesh.material = this.material; }
  46601. },
  46602. /**
  46603. * Load font for geometry, load font image for material, and apply.
  46604. */
  46605. updateFont: function () {
  46606. var data = this.data;
  46607. var el = this.el;
  46608. var fontSrc;
  46609. var geometry = this.geometry;
  46610. var self = this;
  46611. if (!data.font) { warn('No font specified. Using the default font.'); }
  46612. // Make invisible during font swap.
  46613. this.mesh.visible = false;
  46614. // Look up font URL to use, and perform cached load.
  46615. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  46616. cache.get(fontSrc, function doLoadFont () {
  46617. return loadFont(fontSrc, data.yOffset);
  46618. }).then(function setFont (font) {
  46619. var fontImgSrc;
  46620. if (font.pages.length !== 1) {
  46621. throw new Error('Currently only single-page bitmap fonts are supported.');
  46622. }
  46623. if (!fontWidthFactors[fontSrc]) {
  46624. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  46625. }
  46626. // Update geometry given font metrics.
  46627. self.updateGeometry(geometry, font);
  46628. // Set font and update layout.
  46629. self.currentFont = font;
  46630. self.updateLayout();
  46631. // Look up font image URL to use, and perform cached load.
  46632. fontImgSrc = self.getFontImageSrc();
  46633. cache.get(fontImgSrc, function () {
  46634. return loadTexture(fontImgSrc);
  46635. }).then(function (image) {
  46636. // Make mesh visible and apply font image as texture.
  46637. var texture = self.texture;
  46638. texture.image = image;
  46639. texture.needsUpdate = true;
  46640. textures[data.font] = texture;
  46641. self.texture = texture;
  46642. self.mesh.visible = true;
  46643. el.emit('textfontset', {font: data.font, fontObj: font});
  46644. }).catch(function (err) {
  46645. error(err.message);
  46646. error(err.stack);
  46647. });
  46648. }).catch(function (err) {
  46649. error(err.message);
  46650. error(err.stack);
  46651. });
  46652. },
  46653. getFontImageSrc: function () {
  46654. if (this.data.fontImage) { return this.data.fontImage; }
  46655. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  46656. var imageSrc = this.currentFont.pages[0];
  46657. // If the image URL contains a non-HTTP(S) protocol, assume it's an absolute
  46658. // path on disk and try to infer the path from the font source instead.
  46659. if (imageSrc.match(protocolRe) && imageSrc.indexOf('http') !== 0) {
  46660. return fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  46661. }
  46662. return THREE.LoaderUtils.extractUrlBase(fontSrc) + imageSrc;
  46663. },
  46664. /**
  46665. * Update layout with anchor, alignment, baseline, and considering any meshes.
  46666. */
  46667. updateLayout: function () {
  46668. var anchor;
  46669. var baseline;
  46670. var el = this.el;
  46671. var data = this.data;
  46672. var geometry = this.geometry;
  46673. var geometryComponent;
  46674. var height;
  46675. var layout;
  46676. var mesh = this.mesh;
  46677. var textRenderWidth;
  46678. var textScale;
  46679. var width;
  46680. var x;
  46681. var y;
  46682. if (!geometry.layout) { return; }
  46683. // Determine width to use (defined width, geometry's width, or default width).
  46684. geometryComponent = el.getAttribute('geometry');
  46685. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  46686. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  46687. // Note that experimental factor will never be correct for variable width fonts.
  46688. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  46689. this.currentFont.widthFactor);
  46690. textScale = width / textRenderWidth;
  46691. // Determine height to use.
  46692. layout = geometry.layout;
  46693. height = textScale * (layout.height + layout.descender);
  46694. // Update geometry dimensions to match text layout if width and height are set to 0.
  46695. // For example, scales a plane to fit text.
  46696. if (geometryComponent && geometryComponent.primitive === 'plane') {
  46697. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  46698. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  46699. }
  46700. // Calculate X position to anchor text left, center, or right.
  46701. anchor = data.anchor === 'align' ? data.align : data.anchor;
  46702. if (anchor === 'left') {
  46703. x = 0;
  46704. } else if (anchor === 'right') {
  46705. x = -1 * layout.width;
  46706. } else if (anchor === 'center') {
  46707. x = -1 * layout.width / 2;
  46708. } else {
  46709. throw new TypeError('Invalid text.anchor property value', anchor);
  46710. }
  46711. // Calculate Y position to anchor text top, center, or bottom.
  46712. baseline = data.baseline;
  46713. if (baseline === 'bottom') {
  46714. y = 0;
  46715. } else if (baseline === 'top') {
  46716. y = -1 * layout.height + layout.ascender;
  46717. } else if (baseline === 'center') {
  46718. y = -1 * layout.height / 2;
  46719. } else {
  46720. throw new TypeError('Invalid text.baseline property value', baseline);
  46721. }
  46722. // Position and scale mesh to apply layout.
  46723. mesh.position.x = x * textScale + data.xOffset;
  46724. mesh.position.y = y * textScale;
  46725. // Place text slightly in front to avoid Z-fighting.
  46726. mesh.position.z = data.zOffset;
  46727. mesh.scale.set(textScale, -1 * textScale, textScale);
  46728. },
  46729. /**
  46730. * Grab font from the constant.
  46731. * Set as a method for test stubbing purposes.
  46732. */
  46733. lookupFont: function (key) {
  46734. return FONTS[key];
  46735. },
  46736. /**
  46737. * Update the text geometry using `three-bmfont-text.update`.
  46738. */
  46739. updateGeometry: (function () {
  46740. var geometryUpdateBase = {};
  46741. var geometryUpdateData = {};
  46742. var newLineRegex = /\\n/g;
  46743. var tabRegex = /\\t/g;
  46744. return function (geometry, font) {
  46745. var data = this.data;
  46746. geometryUpdateData.font = font;
  46747. geometryUpdateData.lineHeight = data.lineHeight && isFinite(data.lineHeight)
  46748. ? data.lineHeight
  46749. : font.common.lineHeight;
  46750. geometryUpdateData.text = data.value.toString().replace(newLineRegex, '\n')
  46751. .replace(tabRegex, '\t');
  46752. geometryUpdateData.width = computeWidth(data.wrapPixels, data.wrapCount,
  46753. font.widthFactor);
  46754. geometry.update(utils.extend(geometryUpdateBase, data, geometryUpdateData));
  46755. };
  46756. })()
  46757. });
  46758. /**
  46759. * Due to using negative scale, we return the opposite side specified.
  46760. * https://github.com/mrdoob/three.js/pull/12787/
  46761. */
  46762. function parseSide (side) {
  46763. switch (side) {
  46764. case 'back': {
  46765. return THREE.FrontSide;
  46766. }
  46767. case 'double': {
  46768. return THREE.DoubleSide;
  46769. }
  46770. default: {
  46771. return THREE.BackSide;
  46772. }
  46773. }
  46774. }
  46775. /**
  46776. * @returns {Promise}
  46777. */
  46778. function loadFont (src, yOffset) {
  46779. return new Promise(function (resolve, reject) {
  46780. loadBMFont(src, function (err, font) {
  46781. if (err) {
  46782. error('Error loading font', src);
  46783. reject(err);
  46784. return;
  46785. }
  46786. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  46787. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  46788. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  46789. resolve(font);
  46790. });
  46791. });
  46792. }
  46793. /**
  46794. * @returns {Promise}
  46795. */
  46796. function loadTexture (src) {
  46797. return new Promise(function (resolve, reject) {
  46798. new THREE.ImageLoader().load(src, function (image) {
  46799. resolve(image);
  46800. }, undefined, function () {
  46801. error('Error loading font image', src);
  46802. reject(null);
  46803. });
  46804. });
  46805. }
  46806. function createShader (el, shaderName, data) {
  46807. var shader;
  46808. var shaderObject;
  46809. // Set up Shader.
  46810. shaderObject = new shaders[shaderName].Shader();
  46811. shaderObject.el = el;
  46812. shaderObject.init(data);
  46813. shaderObject.update(data);
  46814. // Get material.
  46815. shader = shaderObject.material;
  46816. // Apparently, was not set on `init` nor `update`.
  46817. shader.transparent = data.transparent;
  46818. return {
  46819. material: shader,
  46820. shader: shaderObject
  46821. };
  46822. }
  46823. /**
  46824. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  46825. * Note that experimental factor will never be correct for variable width fonts.
  46826. */
  46827. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  46828. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  46829. }
  46830. /**
  46831. * Compute default font width factor to use.
  46832. */
  46833. function computeFontWidthFactor (font) {
  46834. var sum = 0;
  46835. var digitsum = 0;
  46836. var digits = 0;
  46837. font.chars.map(function (ch) {
  46838. sum += ch.xadvance;
  46839. if (ch.id >= 48 && ch.id <= 57) {
  46840. digits++;
  46841. digitsum += ch.xadvance;
  46842. }
  46843. });
  46844. return digits ? digitsum / digits : sum / font.chars.length;
  46845. }
  46846. /**
  46847. * Get or create a promise given a key and promise generator.
  46848. * @todo Move to a utility and use in other parts of A-Frame.
  46849. */
  46850. function PromiseCache () {
  46851. var cache = this.cache = {};
  46852. this.get = function (key, promiseGenerator) {
  46853. if (key in cache) {
  46854. return cache[key];
  46855. }
  46856. cache[key] = promiseGenerator();
  46857. return cache[key];
  46858. };
  46859. }
  46860. },{"../core/component":103,"../core/shader":113,"../lib/three":151,"../utils/":176,"load-bmfont":23,"three-bmfont-text":41}],87:[function(_dereq_,module,exports){
  46861. var registerComponent = _dereq_('../core/component').registerComponent;
  46862. var controllerUtils = _dereq_('../utils/tracked-controls');
  46863. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  46864. var THREE = _dereq_('../lib/three');
  46865. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  46866. // Vector from eyes to elbow (divided by user height).
  46867. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  46868. // Vector from eyes to elbow (divided by user height).
  46869. var FOREARM = {x: 0, y: 0, z: -0.175};
  46870. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  46871. var EMPTY_DAYDREAM_TOUCHES = {touches: []};
  46872. var EVENTS = {
  46873. AXISMOVE: 'axismove',
  46874. BUTTONCHANGED: 'buttonchanged',
  46875. BUTTONDOWN: 'buttondown',
  46876. BUTTONUP: 'buttonup',
  46877. TOUCHSTART: 'touchstart',
  46878. TOUCHEND: 'touchend'
  46879. };
  46880. /**
  46881. * Tracked controls component.
  46882. * Wrap the gamepad API for pose and button states.
  46883. * Select the appropriate controller and apply pose to the entity.
  46884. * Observe button states and emit appropriate events.
  46885. *
  46886. * @property {number} controller - Index of controller in array returned by Gamepad API.
  46887. * Only used if hand property is not set.
  46888. * @property {string} id - Selected controller among those returned by Gamepad API.
  46889. * @property {number} hand - If multiple controllers found with id, choose the one with the
  46890. * given value for hand. If set, we ignore 'controller' property
  46891. */
  46892. module.exports.Component = registerComponent('tracked-controls-webvr', {
  46893. schema: {
  46894. autoHide: {default: true},
  46895. controller: {default: 0},
  46896. id: {type: 'string', default: ''},
  46897. hand: {type: 'string', default: ''},
  46898. idPrefix: {type: 'string', default: ''},
  46899. orientationOffset: {type: 'vec3'},
  46900. // Arm model parameters when not 6DoF.
  46901. armModel: {default: true},
  46902. headElement: {type: 'selector'}
  46903. },
  46904. init: function () {
  46905. // Copy variables back to tracked-controls for backwards compatibility.
  46906. // Some 3rd components rely on them.
  46907. this.axis = this.el.components['tracked-controls'].axis = [0, 0, 0];
  46908. this.buttonStates = this.el.components['tracked-controls'].buttonStates = {};
  46909. this.changedAxes = [];
  46910. this.targetControllerNumber = this.data.controller;
  46911. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  46912. this.deltaControllerPosition = new THREE.Vector3();
  46913. this.controllerQuaternion = new THREE.Quaternion();
  46914. this.controllerEuler = new THREE.Euler();
  46915. this.updateGamepad();
  46916. this.buttonEventDetails = {};
  46917. },
  46918. tick: function (time, delta) {
  46919. var mesh = this.el.getObject3D('mesh');
  46920. // Update mesh animations.
  46921. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  46922. this.updateGamepad();
  46923. this.updatePose();
  46924. this.updateButtons();
  46925. },
  46926. /**
  46927. * Return default user height to use for non-6DOF arm model.
  46928. */
  46929. defaultUserHeight: function () {
  46930. return DEFAULT_CAMERA_HEIGHT;
  46931. },
  46932. /**
  46933. * Return head element to use for non-6DOF arm model.
  46934. */
  46935. getHeadElement: function () {
  46936. return this.data.headElement || this.el.sceneEl.camera.el;
  46937. },
  46938. /**
  46939. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  46940. */
  46941. updateGamepad: function () {
  46942. var data = this.data;
  46943. var controller = controllerUtils.findMatchingControllerWebVR(
  46944. this.system.controllers,
  46945. data.id,
  46946. data.idPrefix,
  46947. data.hand,
  46948. data.controller
  46949. );
  46950. this.controller = controller;
  46951. // Legacy handle to the controller for old components.
  46952. this.el.components['tracked-controls'].controller = controller;
  46953. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  46954. },
  46955. /**
  46956. * Applies an artificial arm model to simulate elbow to wrist positioning
  46957. * based on the orientation of the controller.
  46958. *
  46959. * @param {object} controllerPosition - Existing vector to update with controller position.
  46960. */
  46961. applyArmModel: function (controllerPosition) {
  46962. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  46963. var controller = this.controller;
  46964. var controllerEuler = this.controllerEuler;
  46965. var controllerQuaternion = this.controllerQuaternion;
  46966. var deltaControllerPosition = this.deltaControllerPosition;
  46967. var hand;
  46968. var headEl;
  46969. var headObject3D;
  46970. var pose;
  46971. var userHeight;
  46972. headEl = this.getHeadElement();
  46973. headObject3D = headEl.object3D;
  46974. userHeight = this.defaultUserHeight();
  46975. pose = controller.pose;
  46976. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  46977. // Use camera position as head position.
  46978. controllerPosition.copy(headObject3D.position);
  46979. // Set offset for degenerate "arm model" to elbow.
  46980. deltaControllerPosition.set(
  46981. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  46982. EYES_TO_ELBOW.y, // Lower than our eyes.
  46983. EYES_TO_ELBOW.z); // Slightly out in front.
  46984. // Scale offset by user height.
  46985. deltaControllerPosition.multiplyScalar(userHeight);
  46986. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  46987. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  46988. // Apply rotated offset to position.
  46989. controllerPosition.add(deltaControllerPosition);
  46990. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  46991. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  46992. // Scale offset by user height.
  46993. deltaControllerPosition.multiplyScalar(userHeight);
  46994. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  46995. if (pose.orientation) {
  46996. controllerQuaternion.fromArray(pose.orientation);
  46997. } else {
  46998. controllerQuaternion.copy(headObject3D.quaternion);
  46999. }
  47000. controllerEuler.setFromQuaternion(controllerQuaternion);
  47001. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  47002. deltaControllerPosition.applyEuler(controllerEuler);
  47003. // Apply rotated offset to position.
  47004. controllerPosition.add(deltaControllerPosition);
  47005. },
  47006. /**
  47007. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  47008. */
  47009. updatePose: function () {
  47010. var controller = this.controller;
  47011. var data = this.data;
  47012. var object3D = this.el.object3D;
  47013. var pose;
  47014. var vrDisplay = this.system.vrDisplay;
  47015. var standingMatrix;
  47016. if (!controller) { return; }
  47017. // Compose pose from Gamepad.
  47018. pose = controller.pose;
  47019. if (pose.position) {
  47020. object3D.position.fromArray(pose.position);
  47021. } else {
  47022. // Controller not 6DOF, apply arm model.
  47023. if (data.armModel) { this.applyArmModel(object3D.position); }
  47024. }
  47025. if (pose.orientation) {
  47026. object3D.quaternion.fromArray(pose.orientation);
  47027. }
  47028. // Apply transforms, if 6DOF and in VR.
  47029. if (vrDisplay && pose.position) {
  47030. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  47031. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  47032. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  47033. object3D.matrix.decompose(object3D.position, object3D.quaternion, object3D.scale);
  47034. }
  47035. object3D.rotateX(this.data.orientationOffset.x * THREE.Math.DEG2RAD);
  47036. object3D.rotateY(this.data.orientationOffset.y * THREE.Math.DEG2RAD);
  47037. object3D.rotateZ(this.data.orientationOffset.z * THREE.Math.DEG2RAD);
  47038. },
  47039. /**
  47040. * Handle button changes including axes, presses, touches, values.
  47041. */
  47042. updateButtons: function () {
  47043. var buttonState;
  47044. var controller = this.controller;
  47045. var id;
  47046. if (!controller) { return; }
  47047. // Check every button.
  47048. for (id = 0; id < controller.buttons.length; ++id) {
  47049. // Initialize button state.
  47050. if (!this.buttonStates[id]) {
  47051. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  47052. }
  47053. if (!this.buttonEventDetails[id]) {
  47054. this.buttonEventDetails[id] = {id: id, state: this.buttonStates[id]};
  47055. }
  47056. buttonState = controller.buttons[id];
  47057. this.handleButton(id, buttonState);
  47058. }
  47059. // Check axes.
  47060. this.handleAxes();
  47061. },
  47062. /**
  47063. * Handle presses and touches for a single button.
  47064. *
  47065. * @param {number} id - Index of button in Gamepad button array.
  47066. * @param {number} buttonState - Value of button state from 0 to 1.
  47067. * @returns {boolean} Whether button has changed in any way.
  47068. */
  47069. handleButton: function (id, buttonState) {
  47070. var changed;
  47071. changed = this.handlePress(id, buttonState) |
  47072. this.handleTouch(id, buttonState) |
  47073. this.handleValue(id, buttonState);
  47074. if (!changed) { return false; }
  47075. this.el.emit(EVENTS.BUTTONCHANGED, this.buttonEventDetails[id], false);
  47076. return true;
  47077. },
  47078. /**
  47079. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  47080. * Compare each component of the axis to the previous value to determine change.
  47081. *
  47082. * @returns {boolean} Whether axes changed.
  47083. */
  47084. handleAxes: function () {
  47085. var changed = false;
  47086. var controllerAxes = this.controller.axes;
  47087. var i;
  47088. var previousAxis = this.axis;
  47089. var changedAxes = this.changedAxes;
  47090. // Check if axis changed.
  47091. this.changedAxes.length = 0;
  47092. for (i = 0; i < controllerAxes.length; ++i) {
  47093. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  47094. if (changedAxes[i]) { changed = true; }
  47095. }
  47096. if (!changed) { return false; }
  47097. this.axis.length = 0;
  47098. for (i = 0; i < controllerAxes.length; i++) {
  47099. this.axis.push(controllerAxes[i]);
  47100. }
  47101. this.el.emit(EVENTS.AXISMOVE, this.axisMoveEventDetail, false);
  47102. return true;
  47103. },
  47104. /**
  47105. * Determine whether a button press has occured and emit events as appropriate.
  47106. *
  47107. * @param {string} id - ID of the button to check.
  47108. * @param {object} buttonState - State of the button to check.
  47109. * @returns {boolean} Whether button press state changed.
  47110. */
  47111. handlePress: function (id, buttonState) {
  47112. var evtName;
  47113. var previousButtonState = this.buttonStates[id];
  47114. // Not changed.
  47115. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47116. evtName = buttonState.pressed ? EVENTS.BUTTONDOWN : EVENTS.BUTTONUP;
  47117. this.el.emit(evtName, this.buttonEventDetails[id], false);
  47118. previousButtonState.pressed = buttonState.pressed;
  47119. return true;
  47120. },
  47121. /**
  47122. * Determine whether a button touch has occured and emit events as appropriate.
  47123. *
  47124. * @param {string} id - ID of the button to check.
  47125. * @param {object} buttonState - State of the button to check.
  47126. * @returns {boolean} Whether button touch state changed.
  47127. */
  47128. handleTouch: function (id, buttonState) {
  47129. var evtName;
  47130. var previousButtonState = this.buttonStates[id];
  47131. // Not changed.
  47132. if (buttonState.touched === previousButtonState.touched) { return false; }
  47133. evtName = buttonState.touched ? EVENTS.TOUCHSTART : EVENTS.TOUCHEND;
  47134. this.el.emit(evtName, this.buttonEventDetails[id], false, EMPTY_DAYDREAM_TOUCHES);
  47135. previousButtonState.touched = buttonState.touched;
  47136. return true;
  47137. },
  47138. /**
  47139. * Determine whether a button value has changed.
  47140. *
  47141. * @param {string} id - Id of the button to check.
  47142. * @param {object} buttonState - State of the button to check.
  47143. * @returns {boolean} Whether button value changed.
  47144. */
  47145. handleValue: function (id, buttonState) {
  47146. var previousButtonState = this.buttonStates[id];
  47147. // Not changed.
  47148. if (buttonState.value === previousButtonState.value) { return false; }
  47149. previousButtonState.value = buttonState.value;
  47150. return true;
  47151. }
  47152. });
  47153. },{"../constants":95,"../core/component":103,"../lib/three":151,"../utils/tracked-controls":184}],88:[function(_dereq_,module,exports){
  47154. var controllerUtils = _dereq_('../utils/tracked-controls');
  47155. var registerComponent = _dereq_('../core/component').registerComponent;
  47156. module.exports.Component = registerComponent('tracked-controls-webxr', {
  47157. schema: {
  47158. hand: {type: 'string', default: ''}
  47159. },
  47160. init: function () {
  47161. this.addSessionEventListeners = this.addSessionEventListeners.bind(this);
  47162. this.updateController = this.updateController.bind(this);
  47163. this.emitButtonUpEvent = this.emitButtonUpEvent.bind(this);
  47164. this.emitButtonDownEvent = this.emitButtonDownEvent.bind(this);
  47165. this.buttonEventDetails = {id: 'trigger', state: {pressed: false}};
  47166. },
  47167. play: function () {
  47168. var sceneEl = this.el.sceneEl;
  47169. this.updateController();
  47170. this.addSessionEventListeners();
  47171. sceneEl.addEventListener('enter-vr', this.addSessionEventListeners);
  47172. sceneEl.addEventListener('controllersupdated', this.updateController);
  47173. },
  47174. pause: function () {
  47175. var sceneEl = this.el.sceneEl;
  47176. this.removeSessionEventListeners();
  47177. sceneEl.removeEventListener('enter-vr', this.addSessionEventListeners);
  47178. sceneEl.removeEventListener('controllersupdated', this.updateController);
  47179. },
  47180. addSessionEventListeners: function () {
  47181. var sceneEl = this.el.sceneEl;
  47182. if (!sceneEl.xrSession) { return; }
  47183. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  47184. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  47185. },
  47186. removeSessionEventListeners: function () {
  47187. var sceneEl = this.el.sceneEl;
  47188. if (!sceneEl.xrSession) { return; }
  47189. sceneEl.xrSession.addEventListener('selectstart', this.emitButtonDownEvent);
  47190. sceneEl.xrSession.addEventListener('selectend', this.emitButtonUpEvent);
  47191. },
  47192. emitButtonDownEvent: function (evt) {
  47193. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  47194. this.buttonEventDetails.state.pressed = true;
  47195. this.el.emit('buttondown', this.buttonEventDetails);
  47196. this.el.emit('buttonchanged', this.buttonEventDetails);
  47197. this.el.emit('triggerdown');
  47198. },
  47199. emitButtonUpEvent: function (evt) {
  47200. if (!this.controller || evt.inputSource.handedness !== this.data.hand) { return; }
  47201. this.buttonEventDetails.state.pressed = false;
  47202. this.el.emit('buttonup', this.buttonEventDetails);
  47203. this.el.emit('buttonchanged', this.buttonEventDetails);
  47204. this.el.emit('triggerup');
  47205. },
  47206. /**
  47207. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  47208. */
  47209. updateController: function () {
  47210. this.controller = controllerUtils.findMatchingControllerWebXR(
  47211. this.system.controllers,
  47212. this.data.hand
  47213. );
  47214. // Legacy handle to the controller for old components.
  47215. this.el.components['tracked-controls'].controller = this.controller;
  47216. if (this.data.autoHide) { this.el.object3D.visible = !!this.controller; }
  47217. },
  47218. tick: function () {
  47219. var pose;
  47220. var sceneEl = this.el.sceneEl;
  47221. var object3D = this.el.object3D;
  47222. if (!this.controller || !sceneEl.frame) { return; }
  47223. pose = sceneEl.frame.getInputPose(this.controller, sceneEl.frameOfReference);
  47224. if (!pose) { return; }
  47225. object3D.matrix.elements = pose.targetRay.transformMatrix;
  47226. object3D.matrix.decompose(object3D.position, object3D.rotation, object3D.scale);
  47227. }
  47228. });
  47229. },{"../core/component":103,"../utils/tracked-controls":184}],89:[function(_dereq_,module,exports){
  47230. var registerComponent = _dereq_('../core/component').registerComponent;
  47231. /**
  47232. * Tracked controls.
  47233. * Abstract controls that decide if the WebVR or WebXR version is going to be applied.
  47234. *
  47235. * @property {number} controller - Index of controller in array returned by Gamepad API.
  47236. * Only used if hand property is not set.
  47237. * @property {string} id - Selected controller among those returned by Gamepad API.
  47238. * @property {number} hand - If multiple controllers found with id, choose the one with the
  47239. * given value for hand. If set, we ignore 'controller' property
  47240. */
  47241. module.exports.Component = registerComponent('tracked-controls', {
  47242. schema: {
  47243. autoHide: {default: true},
  47244. controller: {default: 0},
  47245. id: {type: 'string', default: ''},
  47246. hand: {type: 'string', default: ''},
  47247. idPrefix: {type: 'string', default: ''},
  47248. orientationOffset: {type: 'vec3'},
  47249. // Arm model parameters when not 6DoF.
  47250. armModel: {default: true},
  47251. headElement: {type: 'selector'}
  47252. },
  47253. update: function () {
  47254. var data = this.data;
  47255. var el = this.el;
  47256. if (el.sceneEl.hasWebXR) {
  47257. el.setAttribute('tracked-controls-webxr', data);
  47258. } else {
  47259. el.setAttribute('tracked-controls-webvr', data);
  47260. }
  47261. }
  47262. });
  47263. },{"../core/component":103}],90:[function(_dereq_,module,exports){
  47264. var registerComponent = _dereq_('../core/component').registerComponent;
  47265. /**
  47266. * Visibility component.
  47267. */
  47268. module.exports.Component = registerComponent('visible', {
  47269. schema: {default: true},
  47270. update: function () {
  47271. this.el.object3D.visible = this.data;
  47272. }
  47273. });
  47274. },{"../core/component":103}],91:[function(_dereq_,module,exports){
  47275. var registerComponent = _dereq_('../core/component').registerComponent;
  47276. var bind = _dereq_('../utils/bind');
  47277. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47278. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47279. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47280. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47281. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47282. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47283. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47284. /**
  47285. * Vive controls.
  47286. * Interface with Vive controllers and map Gamepad events to controller buttons:
  47287. * trackpad, trigger, grip, menu, system
  47288. * Load a controller model and highlight the pressed buttons.
  47289. */
  47290. module.exports.Component = registerComponent('vive-controls', {
  47291. schema: {
  47292. hand: {default: 'left'},
  47293. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47294. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47295. model: {default: true},
  47296. orientationOffset: {type: 'vec3'}
  47297. },
  47298. /**
  47299. * Button IDs:
  47300. * 0 - trackpad
  47301. * 1 - trigger (intensity value from 0.5 to 1)
  47302. * 2 - grip
  47303. * 3 - menu (dispatch but better for menu options)
  47304. * 4 - system (never dispatched on this layer)
  47305. */
  47306. mapping: {
  47307. axes: {trackpad: [0, 1]},
  47308. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47309. },
  47310. init: function () {
  47311. var self = this;
  47312. this.controllerPresent = false;
  47313. this.lastControllerCheck = 0;
  47314. this.onButtonChanged = bind(this.onButtonChanged, this);
  47315. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47316. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47317. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47318. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47319. this.previousButtonValues = {};
  47320. this.rendererSystem = this.el.sceneEl.systems.renderer;
  47321. this.bindMethods();
  47322. },
  47323. play: function () {
  47324. this.checkIfControllerPresent();
  47325. this.addControllersUpdateListener();
  47326. },
  47327. pause: function () {
  47328. this.removeEventListeners();
  47329. this.removeControllersUpdateListener();
  47330. },
  47331. bindMethods: function () {
  47332. this.onModelLoaded = bind(this.onModelLoaded, this);
  47333. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47334. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47335. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47336. this.onAxisMoved = bind(this.onAxisMoved, this);
  47337. },
  47338. addEventListeners: function () {
  47339. var el = this.el;
  47340. el.addEventListener('buttonchanged', this.onButtonChanged);
  47341. el.addEventListener('buttondown', this.onButtonDown);
  47342. el.addEventListener('buttonup', this.onButtonUp);
  47343. el.addEventListener('touchend', this.onButtonTouchEnd);
  47344. el.addEventListener('touchstart', this.onButtonTouchStart);
  47345. el.addEventListener('model-loaded', this.onModelLoaded);
  47346. el.addEventListener('axismove', this.onAxisMoved);
  47347. this.controllerEventsActive = true;
  47348. },
  47349. removeEventListeners: function () {
  47350. var el = this.el;
  47351. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47352. el.removeEventListener('buttondown', this.onButtonDown);
  47353. el.removeEventListener('buttonup', this.onButtonUp);
  47354. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47355. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47356. el.removeEventListener('model-loaded', this.onModelLoaded);
  47357. el.removeEventListener('axismove', this.onAxisMoved);
  47358. this.controllerEventsActive = false;
  47359. },
  47360. /**
  47361. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  47362. * var isPresent = checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  47363. { hand: data.hand });
  47364. * Until then, use hardcoded index.
  47365. */
  47366. checkIfControllerPresent: function () {
  47367. var data = this.data;
  47368. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47369. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  47370. },
  47371. injectTrackedControls: function () {
  47372. var el = this.el;
  47373. var data = this.data;
  47374. // If we have an OpenVR Gamepad, use the fixed mapping.
  47375. el.setAttribute('tracked-controls', {
  47376. idPrefix: GAMEPAD_ID_PREFIX,
  47377. // Hand IDs: 1 = right, 0 = left, 2 = anything else.
  47378. controller: data.hand === 'right' ? 1 : data.hand === 'left' ? 0 : 2,
  47379. orientationOffset: data.orientationOffset
  47380. });
  47381. // Load model.
  47382. if (!this.data.model) { return; }
  47383. this.el.setAttribute('obj-model', {
  47384. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47385. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47386. });
  47387. },
  47388. addControllersUpdateListener: function () {
  47389. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47390. },
  47391. removeControllersUpdateListener: function () {
  47392. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47393. },
  47394. onControllersUpdate: function () {
  47395. this.checkIfControllerPresent();
  47396. },
  47397. /**
  47398. * Rotate the trigger button based on how hard the trigger is pressed.
  47399. */
  47400. onButtonChanged: function (evt) {
  47401. var button = this.mapping.buttons[evt.detail.id];
  47402. var buttonMeshes = this.buttonMeshes;
  47403. var analogValue;
  47404. if (!button) { return; }
  47405. if (button === 'trigger') {
  47406. analogValue = evt.detail.state.value;
  47407. // Update trigger rotation depending on button value.
  47408. if (buttonMeshes && buttonMeshes.trigger) {
  47409. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47410. }
  47411. }
  47412. // Pass along changed event with button state, using button mapping for convenience.
  47413. this.el.emit(button + 'changed', evt.detail.state);
  47414. },
  47415. onModelLoaded: function (evt) {
  47416. var buttonMeshes;
  47417. var controllerObject3D = evt.detail.model;
  47418. var self = this;
  47419. if (!this.data.model) { return; }
  47420. // Store button meshes object to be able to change their colors.
  47421. buttonMeshes = this.buttonMeshes = {};
  47422. buttonMeshes.grip = {
  47423. left: controllerObject3D.getObjectByName('leftgrip'),
  47424. right: controllerObject3D.getObjectByName('rightgrip')
  47425. };
  47426. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47427. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47428. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47429. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47430. // Set default colors.
  47431. Object.keys(buttonMeshes).forEach(function (buttonName) {
  47432. self.setButtonColor(buttonName, self.data.buttonColor);
  47433. });
  47434. // Offset pivot point.
  47435. controllerObject3D.position.set(0, -0.015, 0.04);
  47436. },
  47437. onAxisMoved: function (evt) {
  47438. emitIfAxesChanged(this, this.mapping.axes, evt);
  47439. },
  47440. updateModel: function (buttonName, evtName) {
  47441. var color;
  47442. var isTouch;
  47443. if (!this.data.model) { return; }
  47444. isTouch = evtName.indexOf('touch') !== -1;
  47445. // Don't change color for trackpad touch.
  47446. if (isTouch) { return; }
  47447. // Update colors.
  47448. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47449. this.setButtonColor(buttonName, color);
  47450. },
  47451. setButtonColor: function (buttonName, color) {
  47452. var buttonMeshes = this.buttonMeshes;
  47453. var rendererSystem = this.rendererSystem;
  47454. if (!buttonMeshes) { return; }
  47455. // Need to do both left and right sides for grip.
  47456. if (buttonName === 'grip') {
  47457. buttonMeshes.grip.left.material.color.set(color);
  47458. buttonMeshes.grip.right.material.color.set(color);
  47459. rendererSystem.applyColorCorrection(buttonMeshes.grip.left.material.color);
  47460. rendererSystem.applyColorCorrection(buttonMeshes.grip.right.material.color);
  47461. return;
  47462. }
  47463. buttonMeshes[buttonName].material.color.set(color);
  47464. rendererSystem.applyColorCorrection(buttonMeshes[buttonName].material.color);
  47465. }
  47466. });
  47467. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],92:[function(_dereq_,module,exports){
  47468. var registerComponent = _dereq_('../core/component').registerComponent;
  47469. var bind = _dereq_('../utils/bind');
  47470. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47471. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47472. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47473. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47474. var GAMEPAD_ID_PREFIX = 'HTC Vive Focus';
  47475. var VIVE_FOCUS_CONTROLLER_MODEL_URL = 'https://cdn.aframe.io/controllers/vive/focus-controller/focus-controller.gltf';
  47476. /**
  47477. * Vive Focus controls.
  47478. * Interface with Vive Focus controller and map Gamepad events to
  47479. * controller buttons: trackpad, trigger
  47480. * Load a controller model and highlight the pressed buttons.
  47481. */
  47482. module.exports.Component = registerComponent('vive-focus-controls', {
  47483. schema: {
  47484. hand: {default: ''}, // This informs the degenerate arm model.
  47485. buttonTouchedColor: {type: 'color', default: '#BBBBBB'},
  47486. buttonHighlightColor: {type: 'color', default: '#7A7A7A'},
  47487. model: {default: true},
  47488. orientationOffset: {type: 'vec3'},
  47489. armModel: {default: true}
  47490. },
  47491. /**
  47492. * Button IDs:
  47493. * 0 - trackpad
  47494. * 1 - trigger
  47495. */
  47496. mapping: {
  47497. axes: {trackpad: [0, 1]},
  47498. buttons: ['trigger', 'trackpad']
  47499. },
  47500. bindMethods: function () {
  47501. this.onModelLoaded = bind(this.onModelLoaded, this);
  47502. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47503. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47504. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47505. this.onAxisMoved = bind(this.onAxisMoved, this);
  47506. },
  47507. init: function () {
  47508. var self = this;
  47509. this.onButtonChanged = bind(this.onButtonChanged, this);
  47510. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47511. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47512. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47513. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47514. this.controllerPresent = false;
  47515. this.lastControllerCheck = 0;
  47516. this.bindMethods();
  47517. },
  47518. addEventListeners: function () {
  47519. var el = this.el;
  47520. el.addEventListener('buttonchanged', this.onButtonChanged);
  47521. el.addEventListener('buttondown', this.onButtonDown);
  47522. el.addEventListener('buttonup', this.onButtonUp);
  47523. el.addEventListener('touchstart', this.onButtonTouchStart);
  47524. el.addEventListener('touchend', this.onButtonTouchEnd);
  47525. el.addEventListener('model-loaded', this.onModelLoaded);
  47526. el.addEventListener('axismove', this.onAxisMoved);
  47527. this.controllerEventsActive = true;
  47528. this.addControllersUpdateListener();
  47529. },
  47530. removeEventListeners: function () {
  47531. var el = this.el;
  47532. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47533. el.removeEventListener('buttondown', this.onButtonDown);
  47534. el.removeEventListener('buttonup', this.onButtonUp);
  47535. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47536. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47537. el.removeEventListener('model-loaded', this.onModelLoaded);
  47538. el.removeEventListener('axismove', this.onAxisMoved);
  47539. this.controllerEventsActive = false;
  47540. this.removeControllersUpdateListener();
  47541. },
  47542. checkIfControllerPresent: function () {
  47543. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  47544. this.data.hand ? {hand: this.data.hand} : {});
  47545. },
  47546. play: function () {
  47547. this.checkIfControllerPresent();
  47548. this.addControllersUpdateListener();
  47549. },
  47550. pause: function () {
  47551. this.removeEventListeners();
  47552. this.removeControllersUpdateListener();
  47553. },
  47554. injectTrackedControls: function () {
  47555. var el = this.el;
  47556. var data = this.data;
  47557. el.setAttribute('tracked-controls', {
  47558. armModel: data.armModel,
  47559. idPrefix: GAMEPAD_ID_PREFIX,
  47560. orientationOffset: data.orientationOffset
  47561. });
  47562. if (!this.data.model) { return; }
  47563. this.el.setAttribute('gltf-model', VIVE_FOCUS_CONTROLLER_MODEL_URL);
  47564. },
  47565. addControllersUpdateListener: function () {
  47566. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47567. },
  47568. removeControllersUpdateListener: function () {
  47569. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47570. },
  47571. onControllersUpdate: function () {
  47572. this.checkIfControllerPresent();
  47573. },
  47574. onModelLoaded: function (evt) {
  47575. var controllerObject3D = evt.detail.model;
  47576. var buttonMeshes;
  47577. if (!this.data.model) { return; }
  47578. buttonMeshes = this.buttonMeshes = {};
  47579. buttonMeshes.trigger = controllerObject3D.getObjectByName('BumperKey');
  47580. buttonMeshes.triggerPressed = controllerObject3D.getObjectByName('BumperKey_Press');
  47581. if (buttonMeshes.triggerPressed) {
  47582. buttonMeshes.triggerPressed.visible = false;
  47583. }
  47584. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad');
  47585. buttonMeshes.trackpadPressed = controllerObject3D.getObjectByName('TouchPad_Press');
  47586. if (buttonMeshes.trackpadPressed) {
  47587. buttonMeshes.trackpadPressed.visible = false;
  47588. }
  47589. },
  47590. // No analog buttons, only emits 0/1 values
  47591. onButtonChanged: function (evt) {
  47592. var button = this.mapping.buttons[evt.detail.id];
  47593. if (!button) return;
  47594. // Pass along changed event with button state, using button mapping for convenience.
  47595. this.el.emit(button + 'changed', evt.detail.state);
  47596. },
  47597. onAxisMoved: function (evt) {
  47598. emitIfAxesChanged(this, this.mapping.axes, evt);
  47599. },
  47600. updateModel: function (buttonName, evtName) {
  47601. if (!this.data.model) { return; }
  47602. this.updateButtonModel(buttonName, evtName);
  47603. },
  47604. updateButtonModel: function (buttonName, state) {
  47605. var buttonMeshes = this.buttonMeshes;
  47606. var pressedName = buttonName + 'Pressed';
  47607. if (!buttonMeshes || !buttonMeshes[buttonName] || !buttonMeshes[pressedName]) {
  47608. return;
  47609. }
  47610. var color;
  47611. switch (state) {
  47612. case 'down':
  47613. color = this.data.buttonHighlightColor;
  47614. break;
  47615. case 'touchstart':
  47616. color = this.data.buttonTouchedColor;
  47617. break;
  47618. }
  47619. if (color) {
  47620. buttonMeshes[pressedName].material.color.set(color);
  47621. }
  47622. buttonMeshes[pressedName].visible = !!color;
  47623. buttonMeshes[buttonName].visible = !color;
  47624. }
  47625. });
  47626. },{"../core/component":103,"../utils/bind":170,"../utils/tracked-controls":184}],93:[function(_dereq_,module,exports){
  47627. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47628. var registerComponent = _dereq_('../core/component').registerComponent;
  47629. var THREE = _dereq_('../lib/three');
  47630. var utils = _dereq_('../utils/');
  47631. var bind = utils.bind;
  47632. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47633. var CLAMP_VELOCITY = 0.00001;
  47634. var MAX_DELTA = 0.2;
  47635. var KEYS = [
  47636. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  47637. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  47638. ];
  47639. /**
  47640. * WASD component to control entities using WASD keys.
  47641. */
  47642. module.exports.Component = registerComponent('wasd-controls', {
  47643. schema: {
  47644. acceleration: {default: 65},
  47645. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47646. adEnabled: {default: true},
  47647. adInverted: {default: false},
  47648. enabled: {default: true},
  47649. fly: {default: false},
  47650. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47651. wsEnabled: {default: true},
  47652. wsInverted: {default: false}
  47653. },
  47654. init: function () {
  47655. // To keep track of the pressed keys.
  47656. this.keys = {};
  47657. this.easing = 1.1;
  47658. this.velocity = new THREE.Vector3();
  47659. // Bind methods and add event listeners.
  47660. this.onBlur = bind(this.onBlur, this);
  47661. this.onFocus = bind(this.onFocus, this);
  47662. this.onKeyDown = bind(this.onKeyDown, this);
  47663. this.onKeyUp = bind(this.onKeyUp, this);
  47664. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47665. this.attachVisibilityEventListeners();
  47666. },
  47667. tick: function (time, delta) {
  47668. var data = this.data;
  47669. var el = this.el;
  47670. var velocity = this.velocity;
  47671. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  47672. isEmptyObject(this.keys)) { return; }
  47673. // Update velocity.
  47674. delta = delta / 1000;
  47675. this.updateVelocity(delta);
  47676. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47677. // Get movement vector and translate position.
  47678. el.object3D.position.add(this.getMovementVector(delta));
  47679. },
  47680. remove: function () {
  47681. this.removeKeyEventListeners();
  47682. this.removeVisibilityEventListeners();
  47683. },
  47684. play: function () {
  47685. this.attachKeyEventListeners();
  47686. },
  47687. pause: function () {
  47688. this.keys = {};
  47689. this.removeKeyEventListeners();
  47690. },
  47691. updateVelocity: function (delta) {
  47692. var acceleration;
  47693. var adAxis;
  47694. var adSign;
  47695. var data = this.data;
  47696. var keys = this.keys;
  47697. var velocity = this.velocity;
  47698. var wsAxis;
  47699. var wsSign;
  47700. adAxis = data.adAxis;
  47701. wsAxis = data.wsAxis;
  47702. // If FPS too low, reset velocity.
  47703. if (delta > MAX_DELTA) {
  47704. velocity[adAxis] = 0;
  47705. velocity[wsAxis] = 0;
  47706. return;
  47707. }
  47708. // https://gamedev.stackexchange.com/questions/151383/frame-rate-independant-movement-with-acceleration
  47709. var scaledEasing = Math.pow(1 / this.easing, delta * 60);
  47710. // Velocity Easing.
  47711. if (velocity[adAxis] !== 0) {
  47712. velocity[adAxis] -= velocity[adAxis] * scaledEasing;
  47713. }
  47714. if (velocity[wsAxis] !== 0) {
  47715. velocity[wsAxis] -= velocity[wsAxis] * scaledEasing;
  47716. }
  47717. // Clamp velocity easing.
  47718. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47719. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47720. if (!data.enabled) { return; }
  47721. // Update velocity using keys pressed.
  47722. acceleration = data.acceleration;
  47723. if (data.adEnabled) {
  47724. adSign = data.adInverted ? -1 : 1;
  47725. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47726. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47727. }
  47728. if (data.wsEnabled) {
  47729. wsSign = data.wsInverted ? -1 : 1;
  47730. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47731. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47732. }
  47733. },
  47734. getMovementVector: (function () {
  47735. var directionVector = new THREE.Vector3(0, 0, 0);
  47736. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47737. return function (delta) {
  47738. var rotation = this.el.getAttribute('rotation');
  47739. var velocity = this.velocity;
  47740. var xRotation;
  47741. directionVector.copy(velocity);
  47742. directionVector.multiplyScalar(delta);
  47743. // Absolute.
  47744. if (!rotation) { return directionVector; }
  47745. xRotation = this.data.fly ? rotation.x : 0;
  47746. // Transform direction relative to heading.
  47747. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  47748. directionVector.applyEuler(rotationEuler);
  47749. return directionVector;
  47750. };
  47751. })(),
  47752. attachVisibilityEventListeners: function () {
  47753. window.addEventListener('blur', this.onBlur);
  47754. window.addEventListener('focus', this.onFocus);
  47755. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47756. },
  47757. removeVisibilityEventListeners: function () {
  47758. window.removeEventListener('blur', this.onBlur);
  47759. window.removeEventListener('focus', this.onFocus);
  47760. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47761. },
  47762. attachKeyEventListeners: function () {
  47763. window.addEventListener('keydown', this.onKeyDown);
  47764. window.addEventListener('keyup', this.onKeyUp);
  47765. },
  47766. removeKeyEventListeners: function () {
  47767. window.removeEventListener('keydown', this.onKeyDown);
  47768. window.removeEventListener('keyup', this.onKeyUp);
  47769. },
  47770. onBlur: function () {
  47771. this.pause();
  47772. },
  47773. onFocus: function () {
  47774. this.play();
  47775. },
  47776. onVisibilityChange: function () {
  47777. if (document.hidden) {
  47778. this.onBlur();
  47779. } else {
  47780. this.onFocus();
  47781. }
  47782. },
  47783. onKeyDown: function (event) {
  47784. var code;
  47785. if (!shouldCaptureKeyEvent(event)) { return; }
  47786. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47787. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  47788. },
  47789. onKeyUp: function (event) {
  47790. var code;
  47791. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47792. delete this.keys[code];
  47793. }
  47794. });
  47795. function isEmptyObject (keys) {
  47796. var key;
  47797. for (key in keys) { return false; }
  47798. return true;
  47799. }
  47800. },{"../constants":95,"../core/component":103,"../lib/three":151,"../utils/":176}],94:[function(_dereq_,module,exports){
  47801. /* global THREE */
  47802. var registerComponent = _dereq_('../core/component').registerComponent;
  47803. var bind = _dereq_('../utils/bind');
  47804. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47805. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47806. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47807. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47808. var utils = _dereq_('../utils/');
  47809. var debug = utils.debug('components:windows-motion-controls:debug');
  47810. var warn = utils.debug('components:windows-motion-controls:warn');
  47811. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  47812. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  47813. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  47814. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  47815. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  47816. /**
  47817. * Windows Motion Controller controls.
  47818. * Interface with Windows Motion Controller controllers and map Gamepad events to
  47819. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  47820. * Load a controller model and transform the pressed buttons.
  47821. */
  47822. module.exports.Component = registerComponent('windows-motion-controls', {
  47823. schema: {
  47824. hand: {default: DEFAULT_HANDEDNESS},
  47825. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  47826. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  47827. pair: {default: 0},
  47828. // If true, loads the controller glTF asset.
  47829. model: {default: true},
  47830. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  47831. hideDisconnected: {default: true}
  47832. },
  47833. mapping: {
  47834. // A-Frame specific semantic axis names
  47835. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  47836. // A-Frame specific semantic button names
  47837. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  47838. // A mapping of the semantic name to node name in the glTF model file,
  47839. // that should be transformed by axis value.
  47840. // This array mirrors the browser Gamepad.axes array, such that
  47841. // the mesh corresponding to axis 0 is in this array index 0.
  47842. axisMeshNames: [
  47843. 'THUMBSTICK_X',
  47844. 'THUMBSTICK_Y',
  47845. 'TOUCHPAD_TOUCH_X',
  47846. 'TOUCHPAD_TOUCH_Y'
  47847. ],
  47848. // A mapping of the semantic name to button node name in the glTF model file,
  47849. // that should be transformed by button value.
  47850. buttonMeshNames: {
  47851. 'trigger': 'SELECT',
  47852. 'menu': 'MENU',
  47853. 'grip': 'GRASP',
  47854. 'thumbstick': 'THUMBSTICK_PRESS',
  47855. 'trackpad': 'TOUCHPAD_PRESS'
  47856. },
  47857. pointingPoseMeshName: 'POINTING_POSE'
  47858. },
  47859. bindMethods: function () {
  47860. this.onModelError = bind(this.onModelError, this);
  47861. this.onModelLoaded = bind(this.onModelLoaded, this);
  47862. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47863. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47864. this.onAxisMoved = bind(this.onAxisMoved, this);
  47865. },
  47866. init: function () {
  47867. var self = this;
  47868. var el = this.el;
  47869. this.onButtonChanged = bind(this.onButtonChanged, this);
  47870. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47871. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47872. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47873. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47874. this.onControllerConnected = function () { self.setModelVisibility(true); };
  47875. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  47876. this.controllerPresent = false;
  47877. this.lastControllerCheck = 0;
  47878. this.previousButtonValues = {};
  47879. this.bindMethods();
  47880. // Cache for submeshes that we have looked up by name.
  47881. this.loadedMeshInfo = {
  47882. buttonMeshes: null,
  47883. axisMeshes: null
  47884. };
  47885. // Pointing poses
  47886. this.rayOrigin = {
  47887. origin: new THREE.Vector3(),
  47888. direction: new THREE.Vector3(0, 0, -1),
  47889. createdFromMesh: false
  47890. };
  47891. el.addEventListener('controllerconnected', this.onControllerConnected);
  47892. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  47893. },
  47894. addEventListeners: function () {
  47895. var el = this.el;
  47896. el.addEventListener('buttonchanged', this.onButtonChanged);
  47897. el.addEventListener('buttondown', this.onButtonDown);
  47898. el.addEventListener('buttonup', this.onButtonUp);
  47899. el.addEventListener('touchstart', this.onButtonTouchStart);
  47900. el.addEventListener('touchend', this.onButtonTouchEnd);
  47901. el.addEventListener('axismove', this.onAxisMoved);
  47902. el.addEventListener('model-error', this.onModelError);
  47903. el.addEventListener('model-loaded', this.onModelLoaded);
  47904. this.controllerEventsActive = true;
  47905. },
  47906. removeEventListeners: function () {
  47907. var el = this.el;
  47908. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47909. el.removeEventListener('buttondown', this.onButtonDown);
  47910. el.removeEventListener('buttonup', this.onButtonUp);
  47911. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47912. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47913. el.removeEventListener('axismove', this.onAxisMoved);
  47914. el.removeEventListener('model-error', this.onModelError);
  47915. el.removeEventListener('model-loaded', this.onModelLoaded);
  47916. this.controllerEventsActive = false;
  47917. },
  47918. checkIfControllerPresent: function () {
  47919. checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  47920. hand: this.data.hand,
  47921. index: this.data.pair
  47922. });
  47923. },
  47924. play: function () {
  47925. this.checkIfControllerPresent();
  47926. this.addControllersUpdateListener();
  47927. },
  47928. pause: function () {
  47929. this.removeEventListeners();
  47930. this.removeControllersUpdateListener();
  47931. },
  47932. updateControllerModel: function () {
  47933. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  47934. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  47935. this.modelReady();
  47936. return;
  47937. }
  47938. var sourceUrl = this.createControllerModelUrl();
  47939. this.loadModel(sourceUrl);
  47940. },
  47941. /**
  47942. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  47943. * art assets.
  47944. */
  47945. createControllerModelUrl: function (forceDefault) {
  47946. // Determine the device specific folder based on the ID suffix
  47947. var trackedControlsComponent = this.el.components['tracked-controls'];
  47948. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  47949. var device = 'default';
  47950. var hand = this.data.hand;
  47951. var filename;
  47952. if (controller) {
  47953. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  47954. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  47955. // In this case, we want to load the universal model, so need to get the '' from the controller.
  47956. hand = controller.hand;
  47957. if (!forceDefault) {
  47958. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  47959. device = ((match && match[0]) || device);
  47960. }
  47961. }
  47962. // Hand
  47963. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  47964. // Final url
  47965. return MODEL_BASE_URL + device + '/' + filename;
  47966. },
  47967. injectTrackedControls: function () {
  47968. var data = this.data;
  47969. this.el.setAttribute('tracked-controls', {
  47970. idPrefix: GAMEPAD_ID_PREFIX,
  47971. controller: data.pair,
  47972. hand: data.hand,
  47973. armModel: false
  47974. });
  47975. this.updateControllerModel();
  47976. },
  47977. addControllersUpdateListener: function () {
  47978. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47979. },
  47980. removeControllersUpdateListener: function () {
  47981. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47982. },
  47983. onControllersUpdate: function () {
  47984. this.checkIfControllerPresent();
  47985. },
  47986. onModelError: function (evt) {
  47987. var defaultUrl = this.createControllerModelUrl(true);
  47988. if (evt.detail.src !== defaultUrl) {
  47989. warn('Failed to load controller model for device, attempting to load default.');
  47990. this.loadModel(defaultUrl);
  47991. } else {
  47992. warn('Failed to load default controller model.');
  47993. }
  47994. },
  47995. loadModel: function (url) {
  47996. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  47997. // removed and re-loaded if the given url changes.
  47998. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  47999. },
  48000. onModelLoaded: function (evt) {
  48001. var rootNode = this.controllerModel = evt.detail.model;
  48002. var loadedMeshInfo = this.loadedMeshInfo;
  48003. var i;
  48004. var meshName;
  48005. var mesh;
  48006. var meshInfo;
  48007. debug('Processing model');
  48008. // Reset the caches
  48009. loadedMeshInfo.buttonMeshes = {};
  48010. loadedMeshInfo.axisMeshes = {};
  48011. // Cache our meshes so we aren't traversing the hierarchy per frame
  48012. if (rootNode) {
  48013. // Button Meshes
  48014. for (i = 0; i < this.mapping.buttons.length; i++) {
  48015. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  48016. if (!meshName) {
  48017. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  48018. continue;
  48019. }
  48020. mesh = rootNode.getObjectByName(meshName);
  48021. if (!mesh) {
  48022. warn('Missing button mesh with name: ' + meshName);
  48023. continue;
  48024. }
  48025. meshInfo = {
  48026. index: i,
  48027. value: getImmediateChildByName(mesh, 'VALUE'),
  48028. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  48029. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  48030. };
  48031. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  48032. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  48033. } else {
  48034. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  48035. warn('Missing button submesh under mesh with name: ' + meshName +
  48036. '(VALUE: ' + !!meshInfo.value +
  48037. ', PRESSED: ' + !!meshInfo.pressed +
  48038. ', UNPRESSED:' + !!meshInfo.unpressed +
  48039. ')');
  48040. }
  48041. }
  48042. // Axis Meshes
  48043. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  48044. meshName = this.mapping.axisMeshNames[i];
  48045. if (!meshName) {
  48046. debug('Skipping unknown axis at index: ' + i);
  48047. continue;
  48048. }
  48049. mesh = rootNode.getObjectByName(meshName);
  48050. if (!mesh) {
  48051. warn('Missing axis mesh with name: ' + meshName);
  48052. continue;
  48053. }
  48054. meshInfo = {
  48055. index: i,
  48056. value: getImmediateChildByName(mesh, 'VALUE'),
  48057. min: getImmediateChildByName(mesh, 'MIN'),
  48058. max: getImmediateChildByName(mesh, 'MAX')
  48059. };
  48060. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  48061. loadedMeshInfo.axisMeshes[i] = meshInfo;
  48062. } else {
  48063. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  48064. warn('Missing axis submesh under mesh with name: ' + meshName +
  48065. '(VALUE: ' + !!meshInfo.value +
  48066. ', MIN: ' + !!meshInfo.min +
  48067. ', MAX:' + !!meshInfo.max +
  48068. ')');
  48069. }
  48070. }
  48071. this.calculateRayOriginFromMesh(rootNode);
  48072. // Determine if the model has to be visible or not.
  48073. this.setModelVisibility();
  48074. }
  48075. debug('Model load complete.');
  48076. // Look through only immediate children. This will return null if no mesh exists with the given name.
  48077. function getImmediateChildByName (object3d, value) {
  48078. for (var i = 0, l = object3d.children.length; i < l; i++) {
  48079. var obj = object3d.children[i];
  48080. if (obj && obj['name'] === value) {
  48081. return obj;
  48082. }
  48083. }
  48084. return undefined;
  48085. }
  48086. },
  48087. calculateRayOriginFromMesh: (function () {
  48088. var quaternion = new THREE.Quaternion();
  48089. return function (rootNode) {
  48090. var mesh;
  48091. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  48092. // in the glTF (assumes that root node is at world origin)
  48093. this.rayOrigin.origin.set(0, 0, 0);
  48094. this.rayOrigin.direction.set(0, 0, -1);
  48095. this.rayOrigin.createdFromMesh = true;
  48096. // Try to read Pointing pose from the source model
  48097. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  48098. if (mesh) {
  48099. var parent = rootNode.parent;
  48100. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  48101. if (parent) {
  48102. rootNode.parent = null;
  48103. rootNode.updateMatrixWorld(true);
  48104. rootNode.parent = parent;
  48105. }
  48106. mesh.getWorldPosition(this.rayOrigin.origin);
  48107. mesh.getWorldQuaternion(quaternion);
  48108. this.rayOrigin.direction.applyQuaternion(quaternion);
  48109. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  48110. if (parent) {
  48111. rootNode.updateMatrixWorld(true);
  48112. }
  48113. } else {
  48114. debug('Mesh does not contain pointing origin data, defaulting to none.');
  48115. }
  48116. // Emit event stating that our pointing ray is now accurate.
  48117. this.modelReady();
  48118. };
  48119. })(),
  48120. lerpAxisTransform: (function () {
  48121. var quaternion = new THREE.Quaternion();
  48122. return function (axis, axisValue) {
  48123. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  48124. if (!axisMeshInfo) return;
  48125. var min = axisMeshInfo.min;
  48126. var max = axisMeshInfo.max;
  48127. var target = axisMeshInfo.value;
  48128. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  48129. var lerpValue = axisValue * 0.5 + 0.5;
  48130. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  48131. target.position.lerpVectors(min.position, max.position, lerpValue);
  48132. };
  48133. })(),
  48134. lerpButtonTransform: (function () {
  48135. var quaternion = new THREE.Quaternion();
  48136. return function (buttonName, buttonValue) {
  48137. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  48138. if (!buttonMeshInfo) return;
  48139. var min = buttonMeshInfo.unpressed;
  48140. var max = buttonMeshInfo.pressed;
  48141. var target = buttonMeshInfo.value;
  48142. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  48143. target.position.lerpVectors(min.position, max.position, buttonValue);
  48144. };
  48145. })(),
  48146. modelReady: function () {
  48147. this.el.emit('controllermodelready', {
  48148. name: 'windows-motion-controls',
  48149. model: this.data.model,
  48150. rayOrigin: this.rayOrigin
  48151. });
  48152. },
  48153. onButtonChanged: function (evt) {
  48154. var buttonName = this.mapping.buttons[evt.detail.id];
  48155. if (buttonName) {
  48156. // Update the button mesh transform
  48157. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  48158. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  48159. }
  48160. // Only emit events for buttons that we know how to map from index to name
  48161. this.el.emit(buttonName + 'changed', evt.detail.state);
  48162. }
  48163. },
  48164. onAxisMoved: function (evt) {
  48165. var numAxes = this.mapping.axisMeshNames.length;
  48166. // Only attempt to update meshes if we have valid data.
  48167. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  48168. for (var axis = 0; axis < numAxes; axis++) {
  48169. // Update the button mesh transform
  48170. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  48171. }
  48172. }
  48173. emitIfAxesChanged(this, this.mapping.axes, evt);
  48174. },
  48175. setModelVisibility: function (visible) {
  48176. var model = this.el.getObject3D('mesh');
  48177. visible = visible !== undefined ? visible : this.modelVisible;
  48178. this.modelVisible = visible;
  48179. if (!model) { return; }
  48180. model.visible = visible;
  48181. }
  48182. });
  48183. },{"../constants":95,"../core/component":103,"../utils/":176,"../utils/bind":170,"../utils/tracked-controls":184}],95:[function(_dereq_,module,exports){
  48184. module.exports = {
  48185. AFRAME_INJECTED: 'aframe-injected',
  48186. DEFAULT_CAMERA_HEIGHT: 1.6,
  48187. DEFAULT_HANDEDNESS: 'right',
  48188. keyboardevent: _dereq_('./keyboardevent')
  48189. };
  48190. },{"./keyboardevent":96}],96:[function(_dereq_,module,exports){
  48191. module.exports = {
  48192. // Tiny KeyboardEvent.code polyfill.
  48193. KEYCODE_TO_CODE: {
  48194. '38': 'ArrowUp',
  48195. '37': 'ArrowLeft',
  48196. '40': 'ArrowDown',
  48197. '39': 'ArrowRight',
  48198. '87': 'KeyW',
  48199. '65': 'KeyA',
  48200. '83': 'KeyS',
  48201. '68': 'KeyD'
  48202. }
  48203. };
  48204. },{}],97:[function(_dereq_,module,exports){
  48205. var ANode = _dereq_('./a-node');
  48206. var bind = _dereq_('../utils/bind');
  48207. var debug = _dereq_('../utils/debug');
  48208. var registerElement = _dereq_('./a-register-element').registerElement;
  48209. var THREE = _dereq_('../lib/three');
  48210. var fileLoader = new THREE.FileLoader();
  48211. var warn = debug('core:a-assets:warn');
  48212. /**
  48213. * Asset management system. Handles blocking on asset loading.
  48214. */
  48215. module.exports = registerElement('a-assets', {
  48216. prototype: Object.create(ANode.prototype, {
  48217. createdCallback: {
  48218. value: function () {
  48219. this.isAssets = true;
  48220. this.fileLoader = fileLoader;
  48221. this.timeout = null;
  48222. }
  48223. },
  48224. attachedCallback: {
  48225. value: function () {
  48226. var self = this;
  48227. var i;
  48228. var loaded = [];
  48229. var mediaEl;
  48230. var mediaEls;
  48231. var imgEl;
  48232. var imgEls;
  48233. var timeout;
  48234. if (!this.parentNode.isScene) {
  48235. throw new Error('<a-assets> must be a child of a <a-scene>.');
  48236. }
  48237. // Wait for <img>s.
  48238. imgEls = this.querySelectorAll('img');
  48239. for (i = 0; i < imgEls.length; i++) {
  48240. imgEl = fixUpMediaElement(imgEls[i]);
  48241. loaded.push(new Promise(function (resolve, reject) {
  48242. // Set in cache because we won't be needing to call three.js loader if we have.
  48243. // a loaded media element.
  48244. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  48245. imgEl.onload = resolve;
  48246. imgEl.onerror = reject;
  48247. }));
  48248. }
  48249. // Wait for <audio>s and <video>s.
  48250. mediaEls = this.querySelectorAll('audio, video');
  48251. for (i = 0; i < mediaEls.length; i++) {
  48252. mediaEl = fixUpMediaElement(mediaEls[i]);
  48253. if (!mediaEl.src && !mediaEl.srcObject) {
  48254. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  48255. }
  48256. loaded.push(mediaElementLoaded(mediaEl));
  48257. }
  48258. // Trigger loaded for scene to start rendering.
  48259. Promise.all(loaded).then(bind(this.load, this));
  48260. // Timeout to start loading anyways.
  48261. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  48262. this.timeout = setTimeout(function () {
  48263. if (self.hasLoaded) { return; }
  48264. warn('Asset loading timed out in ', timeout, 'ms');
  48265. self.emit('timeout');
  48266. self.load();
  48267. }, timeout);
  48268. }
  48269. },
  48270. detachedCallback: {
  48271. value: function () {
  48272. if (this.timeout) { clearTimeout(this.timeout); }
  48273. }
  48274. },
  48275. load: {
  48276. value: function () {
  48277. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  48278. return el.isAssetItem && el.hasAttribute('src');
  48279. });
  48280. }
  48281. }
  48282. })
  48283. });
  48284. /**
  48285. * Preload using XHRLoader for any type of asset.
  48286. */
  48287. registerElement('a-asset-item', {
  48288. prototype: Object.create(ANode.prototype, {
  48289. createdCallback: {
  48290. value: function () {
  48291. this.data = null;
  48292. this.isAssetItem = true;
  48293. }
  48294. },
  48295. attachedCallback: {
  48296. value: function () {
  48297. var self = this;
  48298. var src = this.getAttribute('src');
  48299. fileLoader.setResponseType(
  48300. this.getAttribute('response-type') || inferResponseType(src));
  48301. fileLoader.load(src, function handleOnLoad (response) {
  48302. self.data = response;
  48303. /*
  48304. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  48305. previous one closes, the second request never finishes.
  48306. setTimeout finishes the first request and lets the logic triggered by load open
  48307. subsequent requests.
  48308. setTimeout can be removed once the fix for the bug below ships:
  48309. 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
  48310. */
  48311. setTimeout(function load () { ANode.prototype.load.call(self); });
  48312. }, function handleOnProgress (xhr) {
  48313. self.emit('progress', {
  48314. loadedBytes: xhr.loaded,
  48315. totalBytes: xhr.total,
  48316. xhr: xhr
  48317. });
  48318. }, function handleOnError (xhr) {
  48319. self.emit('error', {xhr: xhr});
  48320. });
  48321. }
  48322. }
  48323. })
  48324. });
  48325. /**
  48326. * Create a Promise that resolves once the media element has finished buffering.
  48327. *
  48328. * @param {Element} el - HTMLMediaElement.
  48329. * @returns {Promise}
  48330. */
  48331. function mediaElementLoaded (el) {
  48332. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  48333. return;
  48334. }
  48335. // If media specifies autoplay or preload, wait until media is completely buffered.
  48336. return new Promise(function (resolve, reject) {
  48337. if (el.readyState === 4) { return resolve(); } // Already loaded.
  48338. if (el.error) { return reject(); } // Error.
  48339. el.addEventListener('loadeddata', checkProgress, false);
  48340. el.addEventListener('progress', checkProgress, false);
  48341. el.addEventListener('error', reject, false);
  48342. function checkProgress () {
  48343. // Add up the seconds buffered.
  48344. var secondsBuffered = 0;
  48345. for (var i = 0; i < el.buffered.length; i++) {
  48346. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  48347. }
  48348. // Compare seconds buffered to media duration.
  48349. if (secondsBuffered >= el.duration) {
  48350. // Set in cache because we won't be needing to call three.js loader if we have.
  48351. // a loaded media element.
  48352. // Store video elements only. three.js loader is used for audio elements.
  48353. // See assetParse too.
  48354. if (el.tagName === 'VIDEO') {
  48355. THREE.Cache.files[el.getAttribute('src')] = el;
  48356. }
  48357. resolve();
  48358. }
  48359. }
  48360. });
  48361. }
  48362. /**
  48363. * Automatically add attributes to media elements where convenient.
  48364. * crossorigin, playsinline.
  48365. */
  48366. function fixUpMediaElement (mediaEl) {
  48367. // Cross-origin.
  48368. var newMediaEl = setCrossOrigin(mediaEl);
  48369. // Plays inline for mobile.
  48370. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  48371. newMediaEl.setAttribute('playsinline', '');
  48372. newMediaEl.setAttribute('webkit-playsinline', '');
  48373. }
  48374. if (newMediaEl !== mediaEl) {
  48375. mediaEl.parentNode.appendChild(newMediaEl);
  48376. mediaEl.parentNode.removeChild(mediaEl);
  48377. }
  48378. return newMediaEl;
  48379. }
  48380. /**
  48381. * Automatically set `crossorigin` if not defined on the media element.
  48382. * If it is not defined, we must create and re-append a new media element <img> and
  48383. * have the browser re-request it with `crossorigin` set.
  48384. *
  48385. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  48386. * @returns {Element} Media element to be used to listen to for loaded events.
  48387. */
  48388. function setCrossOrigin (mediaEl) {
  48389. var newMediaEl;
  48390. var src;
  48391. // Already has crossorigin set.
  48392. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  48393. src = mediaEl.getAttribute('src');
  48394. if (src !== null) {
  48395. // Does not have protocol.
  48396. if (src.indexOf('://') === -1) { return mediaEl; }
  48397. // Determine if cross origin is actually needed.
  48398. if (extractDomain(src) === window.location.host) { return mediaEl; }
  48399. }
  48400. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  48401. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  48402. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  48403. mediaEl.crossOrigin = 'anonymous';
  48404. newMediaEl = mediaEl.cloneNode(true);
  48405. return newMediaEl;
  48406. }
  48407. /**
  48408. * Extract domain out of URL.
  48409. *
  48410. * @param {string} url
  48411. * @returns {string}
  48412. */
  48413. function extractDomain (url) {
  48414. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  48415. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  48416. // Find and remove port number.
  48417. return domain.substring(0, domain.indexOf(':'));
  48418. }
  48419. /**
  48420. * Infer response-type attribute from src.
  48421. * Default is text(default XMLHttpRequest.responseType)
  48422. * but we use arraybuffer for .gltf and .glb files
  48423. * because of THREE.GLTFLoader specification.
  48424. *
  48425. * @param {string} src
  48426. * @returns {string}
  48427. */
  48428. function inferResponseType (src) {
  48429. var dotLastIndex = src.lastIndexOf('.');
  48430. if (dotLastIndex >= 0) {
  48431. var extension = src.slice(dotLastIndex, src.length);
  48432. if (extension === '.gltf' || extension === '.glb') {
  48433. return 'arraybuffer';
  48434. }
  48435. }
  48436. return 'text';
  48437. }
  48438. module.exports.inferResponseType = inferResponseType;
  48439. },{"../lib/three":151,"../utils/bind":170,"../utils/debug":172,"./a-node":101,"./a-register-element":102}],98:[function(_dereq_,module,exports){
  48440. var debug = _dereq_('../utils/debug');
  48441. var registerElement = _dereq_('./a-register-element').registerElement;
  48442. var warn = debug('core:cubemap:warn');
  48443. /**
  48444. * Cubemap element that handles validation and exposes list of URLs.
  48445. * Does not listen to updates.
  48446. */
  48447. module.exports = registerElement('a-cubemap', {
  48448. prototype: Object.create(window.HTMLElement.prototype, {
  48449. /**
  48450. * Calculates this.srcs.
  48451. */
  48452. attachedCallback: {
  48453. value: function () {
  48454. this.srcs = this.validate();
  48455. },
  48456. writable: window.debug
  48457. },
  48458. /**
  48459. * Checks for exactly six elements with [src].
  48460. * Does not check explicitly for <img>s in case user does not want
  48461. * prefetching.
  48462. *
  48463. * @returns {Array|null} - six URLs if valid, else null.
  48464. */
  48465. validate: {
  48466. value: function () {
  48467. var elements = this.querySelectorAll('[src]');
  48468. var i;
  48469. var srcs = [];
  48470. if (elements.length === 6) {
  48471. for (i = 0; i < elements.length; i++) {
  48472. srcs.push(elements[i].getAttribute('src'));
  48473. }
  48474. return srcs;
  48475. }
  48476. // Else if there are not six elements, throw a warning.
  48477. warn(
  48478. '<a-cubemap> did not contain exactly six elements each with a ' +
  48479. '`src` attribute.');
  48480. },
  48481. writable: window.debug
  48482. }
  48483. })
  48484. });
  48485. },{"../utils/debug":172,"./a-register-element":102}],99:[function(_dereq_,module,exports){
  48486. var ANode = _dereq_('./a-node');
  48487. var COMPONENTS = _dereq_('./component').components;
  48488. var registerElement = _dereq_('./a-register-element').registerElement;
  48489. var THREE = _dereq_('../lib/three');
  48490. var utils = _dereq_('../utils/');
  48491. var AEntity;
  48492. var debug = utils.debug('core:a-entity:debug');
  48493. var warn = utils.debug('core:a-entity:warn');
  48494. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48495. var OBJECT3D_COMPONENTS = ['position', 'rotation', 'scale', 'visible'];
  48496. var ONCE = {once: true};
  48497. /**
  48498. * Entity is a container object that components are plugged into to comprise everything in
  48499. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  48500. *
  48501. * To be able to take components, the scene element inherits from the entity definition.
  48502. *
  48503. * @member {object} components - entity's currently initialized components.
  48504. * @member {object} object3D - three.js object.
  48505. * @member {array} states
  48506. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  48507. */
  48508. var proto = Object.create(ANode.prototype, {
  48509. createdCallback: {
  48510. value: function () {
  48511. this.components = {};
  48512. // To avoid double initializations and infinite loops.
  48513. this.initializingComponents = {};
  48514. this.componentsToUpdate = {};
  48515. this.isEntity = true;
  48516. this.isPlaying = false;
  48517. this.object3D = new THREE.Group();
  48518. this.object3D.el = this;
  48519. this.object3DMap = {};
  48520. this.parentEl = null;
  48521. this.rotationObj = {};
  48522. this.states = [];
  48523. }
  48524. },
  48525. /**
  48526. * Handle changes coming from the browser DOM inspector.
  48527. */
  48528. attributeChangedCallback: {
  48529. value: function (attr, oldVal, newVal) {
  48530. var component = this.components[attr];
  48531. // If the empty string is passed by the component initialization
  48532. // logic we ignore the component update.
  48533. if (component && component.justInitialized && newVal === '') {
  48534. delete component.justInitialized;
  48535. return;
  48536. }
  48537. // When a component is removed after calling el.removeAttribute('material')
  48538. if (!component && newVal === null) { return; }
  48539. this.setEntityAttribute(attr, oldVal, newVal);
  48540. }
  48541. },
  48542. /**
  48543. * Add to parent, load, play.
  48544. */
  48545. attachedCallback: {
  48546. value: function () {
  48547. var assetsEl; // Asset management system element.
  48548. var sceneEl = this.sceneEl;
  48549. var self = this; // Component.
  48550. this.addToParent();
  48551. // Don't .load() scene on attachedCallback.
  48552. if (this.isScene) { return; }
  48553. // Gracefully not error when outside of <a-scene> (e.g., tests).
  48554. if (!sceneEl) {
  48555. this.load();
  48556. return;
  48557. }
  48558. // Wait for asset management system to finish before loading.
  48559. assetsEl = sceneEl.querySelector('a-assets');
  48560. if (assetsEl && !assetsEl.hasLoaded) {
  48561. assetsEl.addEventListener('loaded', function () { self.load(); });
  48562. return;
  48563. }
  48564. this.load();
  48565. }
  48566. },
  48567. /**
  48568. * Tell parent to remove this element's object3D from its object3D.
  48569. * Do not call on scene element because that will cause a call to document.body.remove().
  48570. */
  48571. detachedCallback: {
  48572. value: function () {
  48573. var componentName;
  48574. if (!this.parentEl) { return; }
  48575. // Remove components.
  48576. for (componentName in this.components) {
  48577. this.removeComponent(componentName, false);
  48578. }
  48579. if (this.isScene) { return; }
  48580. this.removeFromParent();
  48581. ANode.prototype.detachedCallback.call(this);
  48582. // Remove cyclic reference.
  48583. this.object3D.el = null;
  48584. }
  48585. },
  48586. getObject3D: {
  48587. value: function (type) {
  48588. return this.object3DMap[type];
  48589. }
  48590. },
  48591. /**
  48592. * Set a THREE.Object3D into the map.
  48593. *
  48594. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  48595. * @param {object} obj - A THREE.Object3D.
  48596. */
  48597. setObject3D: {
  48598. value: function (type, obj) {
  48599. var oldObj;
  48600. var self = this;
  48601. if (!(obj instanceof THREE.Object3D)) {
  48602. throw new Error(
  48603. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  48604. 'THREE.Object3D.'
  48605. );
  48606. }
  48607. // Remove existing object of the type.
  48608. oldObj = this.getObject3D(type);
  48609. if (oldObj) { this.object3D.remove(oldObj); }
  48610. // Set references to A-Frame entity.
  48611. obj.el = this;
  48612. if (obj.children.length) {
  48613. obj.traverse(function bindEl (child) {
  48614. child.el = self;
  48615. });
  48616. }
  48617. // Add.
  48618. this.object3D.add(obj);
  48619. this.object3DMap[type] = obj;
  48620. this.emit('object3dset', {object: obj, type: type});
  48621. }
  48622. },
  48623. /**
  48624. * Remove object from scene and entity object3D map.
  48625. */
  48626. removeObject3D: {
  48627. value: function (type) {
  48628. var obj = this.getObject3D(type);
  48629. if (!obj) {
  48630. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  48631. return;
  48632. }
  48633. this.object3D.remove(obj);
  48634. delete this.object3DMap[type];
  48635. this.emit('object3dremove', {type: type});
  48636. }
  48637. },
  48638. /**
  48639. * Gets or creates an object3D of a given type.
  48640. *
  48641. * @param {string} type - Type of the object3D.
  48642. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  48643. * @returns {object}
  48644. */
  48645. getOrCreateObject3D: {
  48646. value: function (type, Constructor) {
  48647. var object3D = this.getObject3D(type);
  48648. if (!object3D && Constructor) {
  48649. object3D = new Constructor();
  48650. this.setObject3D(type, object3D);
  48651. }
  48652. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  48653. 'and `object3dset` event instead.');
  48654. return object3D;
  48655. }
  48656. },
  48657. /**
  48658. * Add child entity.
  48659. *
  48660. * @param {Element} el - Child entity.
  48661. */
  48662. add: {
  48663. value: function (el) {
  48664. if (!el.object3D) {
  48665. throw new Error("Trying to add an element that doesn't have an `object3D`");
  48666. }
  48667. this.object3D.add(el.object3D);
  48668. this.emit('child-attached', {el: el});
  48669. }
  48670. },
  48671. /**
  48672. * Tell parentNode to add this entity to itself.
  48673. */
  48674. addToParent: {
  48675. value: function () {
  48676. var parentNode = this.parentEl = this.parentNode;
  48677. // `!parentNode` check primarily for unit tests.
  48678. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  48679. parentNode.add(this);
  48680. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  48681. }
  48682. },
  48683. /**
  48684. * Tell parentNode to remove this entity from itself.
  48685. */
  48686. removeFromParent: {
  48687. value: function () {
  48688. var parentEl = this.parentEl;
  48689. this.parentEl.remove(this);
  48690. this.attachedToParent = false;
  48691. this.parentEl = null;
  48692. parentEl.emit('child-detached', {el: this});
  48693. }
  48694. },
  48695. load: {
  48696. value: function () {
  48697. var self = this;
  48698. if (this.hasLoaded || !this.parentEl) { return; }
  48699. ANode.prototype.load.call(this, function entityLoadCallback () {
  48700. // Check if entity was detached while it was waiting to load.
  48701. if (!self.parentEl) { return; }
  48702. self.updateComponents();
  48703. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  48704. });
  48705. },
  48706. writable: window.debug
  48707. },
  48708. /**
  48709. * Remove child entity.
  48710. *
  48711. * @param {Element} el - Child entity.
  48712. */
  48713. remove: {
  48714. value: function (el) {
  48715. if (el) {
  48716. this.object3D.remove(el.object3D);
  48717. } else {
  48718. this.parentNode.removeChild(this);
  48719. }
  48720. }
  48721. },
  48722. /**
  48723. * @returns {array} Direct children that are entities.
  48724. */
  48725. getChildEntities: {
  48726. value: function () {
  48727. var children = this.children;
  48728. var childEntities = [];
  48729. for (var i = 0; i < children.length; i++) {
  48730. var child = children[i];
  48731. if (child instanceof AEntity) {
  48732. childEntities.push(child);
  48733. }
  48734. }
  48735. return childEntities;
  48736. }
  48737. },
  48738. /**
  48739. * Initialize component.
  48740. *
  48741. * @param {string} attrName - Attribute name asociated to the component.
  48742. * @param {object} data - Component data
  48743. * @param {boolean} isDependency - True if the component is a dependency.
  48744. */
  48745. initComponent: {
  48746. value: function (attrName, data, isDependency) {
  48747. var component;
  48748. var componentId;
  48749. var componentInfo;
  48750. var componentName;
  48751. var isComponentDefined;
  48752. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  48753. componentName = componentInfo[0];
  48754. componentId = componentInfo.length > 2
  48755. ? componentInfo.slice(1).join('__')
  48756. : componentInfo[1];
  48757. // Not a registered component.
  48758. if (!COMPONENTS[componentName]) { return; }
  48759. // Component is not a dependency and is undefined.
  48760. // If a component is a dependency, then it is okay to have no data.
  48761. isComponentDefined = checkComponentDefined(this, attrName) ||
  48762. data !== undefined;
  48763. if (!isComponentDefined && !isDependency) { return; }
  48764. // Component already initialized.
  48765. if (attrName in this.components) { return; }
  48766. // Initialize dependencies first
  48767. this.initComponentDependencies(componentName);
  48768. // If component name has an id we check component type multiplic
  48769. if (componentId && !COMPONENTS[componentName].multiple) {
  48770. throw new Error('Trying to initialize multiple ' +
  48771. 'components of type `' + componentName +
  48772. '`. There can only be one component of this type per entity.');
  48773. }
  48774. component = new COMPONENTS[componentName].Component(this, data, componentId);
  48775. if (this.isPlaying) { component.play(); }
  48776. // Components are reflected in the DOM as attributes but the state is not shown
  48777. // hence we set the attribute to empty string.
  48778. // The flag justInitialized is for attributeChangedCallback to not overwrite
  48779. // the component with the empty string.
  48780. if (!this.hasAttribute(attrName)) {
  48781. component.justInitialized = true;
  48782. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  48783. }
  48784. debug('Component initialized: %s', attrName);
  48785. },
  48786. writable: window.debug
  48787. },
  48788. /**
  48789. * Initialize dependencies of a component.
  48790. *
  48791. * @param {string} name - Root component name.
  48792. */
  48793. initComponentDependencies: {
  48794. value: function (name) {
  48795. var self = this;
  48796. var component = COMPONENTS[name];
  48797. var dependencies;
  48798. var i;
  48799. // Not a component.
  48800. if (!component) { return; }
  48801. // No dependencies.
  48802. dependencies = COMPONENTS[name].dependencies;
  48803. if (!dependencies) { return; }
  48804. // Initialize dependencies.
  48805. for (i = 0; i < dependencies.length; i++) {
  48806. // Call getAttribute to initialize the data from the DOM.
  48807. self.initComponent(
  48808. dependencies[i],
  48809. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  48810. true
  48811. );
  48812. }
  48813. }
  48814. },
  48815. removeComponent: {
  48816. value: function (name, destroy) {
  48817. var component;
  48818. component = this.components[name];
  48819. if (!component) { return; }
  48820. // Wait for component to initialize.
  48821. if (!component.initialized) {
  48822. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  48823. if (evt.detail.name !== name) { return; }
  48824. this.removeComponent(name, destroy);
  48825. this.removeEventListener('componentinitialized', tryRemoveLater);
  48826. });
  48827. return;
  48828. }
  48829. component.pause();
  48830. component.remove();
  48831. // Keep component attached to entity in case of just full entity detach.
  48832. if (destroy) {
  48833. component.destroy();
  48834. delete this.components[name];
  48835. }
  48836. this.emit('componentremoved', component.evtDetail, false);
  48837. },
  48838. writable: window.debug
  48839. },
  48840. /**
  48841. * Initialize or update all components.
  48842. * Build data using initial components, defined attributes, mixins, and defaults.
  48843. * Update default components before the rest.
  48844. *
  48845. * @member {function} getExtraComponents - Can be implemented to include component data
  48846. * from other sources (e.g., implemented by primitives).
  48847. */
  48848. updateComponents: {
  48849. value: function () {
  48850. var data;
  48851. var extraComponents;
  48852. var i;
  48853. var name;
  48854. var componentsToUpdate = this.componentsToUpdate;
  48855. if (!this.hasLoaded) { return; }
  48856. // Gather mixin-defined components.
  48857. for (i = 0; i < this.mixinEls.length; i++) {
  48858. for (name in this.mixinEls[i].componentCache) {
  48859. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48860. }
  48861. }
  48862. // Gather from extra initial component data if defined (e.g., primitives).
  48863. if (this.getExtraComponents) {
  48864. extraComponents = this.getExtraComponents();
  48865. for (name in extraComponents) {
  48866. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48867. }
  48868. }
  48869. // Gather entity-defined components.
  48870. for (i = 0; i < this.attributes.length; ++i) {
  48871. name = this.attributes[i].name;
  48872. if (OBJECT3D_COMPONENTS.indexOf(name) !== -1) { continue; }
  48873. if (isComponent(name)) { componentsToUpdate[name] = true; }
  48874. }
  48875. // object3D components first (position, rotation, scale, visible).
  48876. for (i = 0; i < OBJECT3D_COMPONENTS.length; i++) {
  48877. name = OBJECT3D_COMPONENTS[i];
  48878. if (!this.hasAttribute(name)) { continue; }
  48879. this.updateComponent(name, this.getDOMAttribute(name));
  48880. }
  48881. // Initialize or update rest of components.
  48882. for (name in componentsToUpdate) {
  48883. data = mergeComponentData(this.getDOMAttribute(name),
  48884. extraComponents && extraComponents[name]);
  48885. this.updateComponent(name, data);
  48886. delete componentsToUpdate[name];
  48887. }
  48888. },
  48889. writable: window.debug
  48890. },
  48891. /**
  48892. * Initialize, update, or remove a single component.
  48893. *
  48894. * When initializing, we set the component on `this.components`.
  48895. *
  48896. * @param {string} attr - Component name.
  48897. * @param {object} attrValue - Value of the DOM attribute.
  48898. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  48899. */
  48900. updateComponent: {
  48901. value: function (attr, attrValue, clobber) {
  48902. var component = this.components[attr];
  48903. if (component) {
  48904. // Remove component.
  48905. if (attrValue === null && !checkComponentDefined(this, attr)) {
  48906. this.removeComponent(attr, true);
  48907. return;
  48908. }
  48909. // Component already initialized. Update component.
  48910. component.updateProperties(attrValue, clobber);
  48911. return;
  48912. }
  48913. // Component not yet initialized. Initialize component.
  48914. this.initComponent(attr, attrValue, false);
  48915. }
  48916. },
  48917. /**
  48918. * If `attr` is a component name, detach the component from the entity.
  48919. *
  48920. * If `propertyName` is given, reset the component property value to its default.
  48921. *
  48922. * @param {string} attr - Attribute name, which could also be a component name.
  48923. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  48924. */
  48925. removeAttribute: {
  48926. value: function (attr, propertyName) {
  48927. var component = this.components[attr];
  48928. // Remove component.
  48929. if (component && propertyName === undefined) {
  48930. this.removeComponent(attr, true);
  48931. }
  48932. // Reset component property value.
  48933. if (component && propertyName !== undefined) {
  48934. component.resetProperty(propertyName);
  48935. return;
  48936. }
  48937. // Remove mixins.
  48938. if (attr === 'mixin') {
  48939. this.mixinUpdate('');
  48940. }
  48941. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  48942. }
  48943. },
  48944. /**
  48945. * Start dynamic behavior associated with entity such as dynamic components and animations.
  48946. * Tell all children entities to also play.
  48947. */
  48948. play: {
  48949. value: function () {
  48950. var entities;
  48951. var i;
  48952. var key;
  48953. // Already playing.
  48954. if (this.isPlaying || !this.hasLoaded) { return; }
  48955. this.isPlaying = true;
  48956. // Wake up all components.
  48957. for (key in this.components) { this.components[key].play(); }
  48958. // Tell all child entities to play.
  48959. entities = this.getChildEntities();
  48960. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  48961. this.emit('play');
  48962. },
  48963. writable: true
  48964. },
  48965. /**
  48966. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  48967. * Tell all children entities to also pause.
  48968. */
  48969. pause: {
  48970. value: function () {
  48971. var entities;
  48972. var i;
  48973. var key;
  48974. if (!this.isPlaying) { return; }
  48975. this.isPlaying = false;
  48976. // Sleep all components.
  48977. for (key in this.components) { this.components[key].pause(); }
  48978. // Tell all child entities to pause.
  48979. entities = this.getChildEntities();
  48980. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  48981. this.emit('pause');
  48982. },
  48983. writable: true
  48984. },
  48985. /**
  48986. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  48987. *
  48988. * @param {string} attr
  48989. * @param {string} oldVal
  48990. * @param {string|object} newVal
  48991. */
  48992. setEntityAttribute: {
  48993. value: function (attr, oldVal, newVal) {
  48994. if (COMPONENTS[attr] || this.components[attr]) {
  48995. this.updateComponent(attr, newVal);
  48996. return;
  48997. }
  48998. if (attr === 'mixin') {
  48999. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  49000. if (newVal === this.computedMixinStr) { return; }
  49001. this.mixinUpdate(newVal, oldVal);
  49002. }
  49003. }
  49004. },
  49005. /**
  49006. * When mixins updated, trigger init or optimized-update of relevant components.
  49007. */
  49008. mixinUpdate: {
  49009. value: (function () {
  49010. var componentsUpdated = [];
  49011. return function (newMixins, oldMixins) {
  49012. var component;
  49013. var mixinEl;
  49014. var mixinIds;
  49015. var i;
  49016. var self = this;
  49017. if (!this.hasLoaded) {
  49018. this.addEventListener('loaded', function () {
  49019. self.mixinUpdate(newMixins, oldMixins);
  49020. }, ONCE);
  49021. return;
  49022. }
  49023. oldMixins = oldMixins || this.getAttribute('mixin');
  49024. mixinIds = this.updateMixins(newMixins, oldMixins);
  49025. // Loop over current mixins.
  49026. componentsUpdated.length = 0;
  49027. for (i = 0; i < this.mixinEls.length; i++) {
  49028. for (component in this.mixinEls[i].componentCache) {
  49029. if (componentsUpdated.indexOf(component) === -1) {
  49030. if (this.components[component]) {
  49031. // Update. Just rebuild data.
  49032. this.components[component].handleMixinUpdate();
  49033. } else {
  49034. // Init. buildData will gather mixin values.
  49035. this.initComponent(component, null);
  49036. }
  49037. componentsUpdated.push(component);
  49038. }
  49039. }
  49040. }
  49041. // Loop over old mixins to call for data rebuild.
  49042. for (i = 0; i < mixinIds.oldMixinIds.length; i++) {
  49043. mixinEl = document.getElementById(mixinIds.oldMixinIds[i]);
  49044. if (!mixinEl) { continue; }
  49045. for (component in mixinEl.componentCache) {
  49046. if (componentsUpdated.indexOf(component) === -1) {
  49047. if (this.components[component]) {
  49048. if (this.getDOMAttribute(component)) {
  49049. // Update component if explicitly defined.
  49050. this.components[component].handleMixinUpdate();
  49051. } else {
  49052. // Remove component if not explicitly defined.
  49053. this.removeComponent(component, true);
  49054. }
  49055. }
  49056. }
  49057. }
  49058. }
  49059. };
  49060. })()
  49061. },
  49062. /**
  49063. * setAttribute can:
  49064. *
  49065. * 1. Set a single property of a multi-property component.
  49066. * 2. Set multiple properties of a multi-property component.
  49067. * 3. Replace properties of a multi-property component.
  49068. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  49069. *
  49070. * @param {string} attrName - Component or attribute name.
  49071. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  49072. * object of properties.
  49073. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  49074. * it is a boolean indicating whether to clobber previous values (defaults to false).
  49075. */
  49076. setAttribute: {
  49077. value: (function () {
  49078. var singlePropUpdate = {};
  49079. return function (attrName, arg1, arg2) {
  49080. var newAttrValue;
  49081. var clobber;
  49082. var componentName;
  49083. var delimiterIndex;
  49084. var isDebugMode;
  49085. var key;
  49086. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  49087. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  49088. // Not a component. Normal set attribute.
  49089. if (!COMPONENTS[componentName]) {
  49090. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  49091. ANode.prototype.setAttribute.call(this, attrName, arg1);
  49092. return;
  49093. }
  49094. // Initialize component first if not yet initialized.
  49095. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  49096. this.updateComponent(
  49097. attrName,
  49098. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  49099. }
  49100. // Determine new attributes from the arguments
  49101. if (typeof arg2 !== 'undefined' &&
  49102. typeof arg1 === 'string' &&
  49103. arg1.length > 0 &&
  49104. typeof utils.styleParser.parse(arg1) === 'string') {
  49105. // Update a single property of a multi-property component
  49106. for (key in singlePropUpdate) { delete singlePropUpdate[key]; }
  49107. newAttrValue = singlePropUpdate;
  49108. newAttrValue[arg1] = arg2;
  49109. clobber = false;
  49110. } else {
  49111. // Update with a value, object, or CSS-style property string, with the possiblity
  49112. // of clobbering previous values.
  49113. newAttrValue = arg1;
  49114. clobber = (arg2 === true);
  49115. }
  49116. // Update component
  49117. this.updateComponent(attrName, newAttrValue, clobber);
  49118. // In debug mode, write component data up to the DOM.
  49119. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  49120. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  49121. };
  49122. })(),
  49123. writable: window.debug
  49124. },
  49125. /**
  49126. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  49127. *
  49128. * @param {bool} recursive - Also flushToDOM on the children.
  49129. **/
  49130. flushToDOM: {
  49131. value: function (recursive) {
  49132. var components = this.components;
  49133. var child;
  49134. var children = this.children;
  49135. var i;
  49136. var key;
  49137. // Flush entity's components to DOM.
  49138. for (key in components) {
  49139. components[key].flushToDOM();
  49140. }
  49141. // Recurse.
  49142. if (!recursive) { return; }
  49143. for (i = 0; i < children.length; ++i) {
  49144. child = children[i];
  49145. if (!child.flushToDOM) { continue; }
  49146. child.flushToDOM(recursive);
  49147. }
  49148. }
  49149. },
  49150. /**
  49151. * If `attr` is a component, returns ALL component data including applied mixins and
  49152. * defaults.
  49153. *
  49154. * If `attr` is not a component, fall back to HTML getAttribute.
  49155. *
  49156. * @param {string} attr
  49157. * @returns {object|string} Object if component, else string.
  49158. */
  49159. getAttribute: {
  49160. value: function (attr) {
  49161. // If component, return component data.
  49162. var component;
  49163. if (attr === 'position') { return this.object3D.position; }
  49164. if (attr === 'rotation') { return getRotation(this); }
  49165. if (attr === 'scale') { return this.object3D.scale; }
  49166. if (attr === 'visible') { return this.object3D.visible; }
  49167. component = this.components[attr];
  49168. if (component) { return component.data; }
  49169. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49170. },
  49171. writable: window.debug
  49172. },
  49173. /**
  49174. * If `attr` is a component, returns JUST the component data defined on the entity.
  49175. * Like a partial version of `getComputedAttribute` as returned component data
  49176. * does not include applied mixins or defaults.
  49177. *
  49178. * If `attr` is not a component, fall back to HTML getAttribute.
  49179. *
  49180. * @param {string} attr
  49181. * @returns {object|string} Object if component, else string.
  49182. */
  49183. getDOMAttribute: {
  49184. value: function (attr) {
  49185. // If cached value exists, return partial component data.
  49186. var component = this.components[attr];
  49187. if (component) { return component.attrValue; }
  49188. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49189. },
  49190. writable: window.debug
  49191. },
  49192. addState: {
  49193. value: function (state) {
  49194. if (this.is(state)) { return; }
  49195. this.states.push(state);
  49196. this.emit('stateadded', state);
  49197. }
  49198. },
  49199. removeState: {
  49200. value: function (state) {
  49201. var stateIndex = this.states.indexOf(state);
  49202. if (stateIndex === -1) { return; }
  49203. this.states.splice(stateIndex, 1);
  49204. this.emit('stateremoved', state);
  49205. }
  49206. },
  49207. /**
  49208. * Checks if the element is in a given state. e.g. el.is('alive');
  49209. * @type {string} state - Name of the state we want to check
  49210. */
  49211. is: {
  49212. value: function (state) {
  49213. return this.states.indexOf(state) !== -1;
  49214. }
  49215. },
  49216. /**
  49217. * Open Inspector to this entity.
  49218. */
  49219. inspect: {
  49220. value: function () {
  49221. this.sceneEl.components.inspector.openInspector(this);
  49222. }
  49223. },
  49224. /**
  49225. * Clean up memory and return memory to object pools.
  49226. */
  49227. destroy: {
  49228. value: function () {
  49229. var key;
  49230. if (this.parentNode) {
  49231. warn('Entity can only be destroyed if detached from scenegraph.');
  49232. return;
  49233. }
  49234. for (key in this.components) {
  49235. this.components[key].destroy();
  49236. }
  49237. }
  49238. }
  49239. });
  49240. /**
  49241. * Check if a component is *defined* for an entity, including defaults and mixins.
  49242. * Does not check whether the component has been *initialized* for an entity.
  49243. *
  49244. * @param {string} el - Entity.
  49245. * @param {string} name - Component name.
  49246. * @returns {boolean}
  49247. */
  49248. function checkComponentDefined (el, name) {
  49249. // Check if element contains the component.
  49250. if (el.components[name] && el.components[name].attrValue) { return true; }
  49251. return isComponentMixedIn(name, el.mixinEls);
  49252. }
  49253. /**
  49254. * Check if any mixins contains a component.
  49255. *
  49256. * @param {string} name - Component name.
  49257. * @param {array} mixinEls - Array of <a-mixin>s.
  49258. */
  49259. function isComponentMixedIn (name, mixinEls) {
  49260. var i;
  49261. var inMixin = false;
  49262. for (i = 0; i < mixinEls.length; ++i) {
  49263. inMixin = mixinEls[i].hasAttribute(name);
  49264. if (inMixin) { break; }
  49265. }
  49266. return inMixin;
  49267. }
  49268. /**
  49269. * Given entity defined value, merge in extra data if necessary.
  49270. * Handle both single and multi-property components.
  49271. *
  49272. * @param {string} attrValue - Entity data.
  49273. * @param extraData - Entity data from another source to merge in.
  49274. */
  49275. function mergeComponentData (attrValue, extraData) {
  49276. // Extra data not defined, just return attrValue.
  49277. if (!extraData) { return attrValue; }
  49278. // Merge multi-property data.
  49279. if (extraData.constructor === Object) {
  49280. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  49281. }
  49282. // Return data, precendence to the defined value.
  49283. return attrValue || extraData;
  49284. }
  49285. function isComponent (componentName) {
  49286. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  49287. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  49288. }
  49289. if (!COMPONENTS[componentName]) { return false; }
  49290. return true;
  49291. }
  49292. function getRotation (entityEl) {
  49293. var radToDeg = THREE.Math.radToDeg;
  49294. var rotation = entityEl.object3D.rotation;
  49295. var rotationObj = entityEl.rotationObj;
  49296. rotationObj.x = radToDeg(rotation.x);
  49297. rotationObj.y = radToDeg(rotation.y);
  49298. rotationObj.z = radToDeg(rotation.z);
  49299. return rotationObj;
  49300. }
  49301. AEntity = registerElement('a-entity', {prototype: proto});
  49302. module.exports = AEntity;
  49303. },{"../lib/three":151,"../utils/":176,"./a-node":101,"./a-register-element":102,"./component":103}],100:[function(_dereq_,module,exports){
  49304. var ANode = _dereq_('./a-node');
  49305. var registerElement = _dereq_('./a-register-element').registerElement;
  49306. var components = _dereq_('./component').components;
  49307. var utils = _dereq_('../utils');
  49308. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49309. /**
  49310. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  49311. * are component names and the values are already parsed by the component.
  49312. */
  49313. module.exports = registerElement('a-mixin', {
  49314. prototype: Object.create(ANode.prototype, {
  49315. createdCallback: {
  49316. value: function () {
  49317. this.componentCache = {};
  49318. this.id = this.getAttribute('id');
  49319. this.isMixin = true;
  49320. }
  49321. },
  49322. attributeChangedCallback: {
  49323. value: function (attr, oldVal, newVal) {
  49324. this.cacheAttribute(attr, newVal);
  49325. this.updateEntities();
  49326. }
  49327. },
  49328. attachedCallback: {
  49329. value: function () {
  49330. this.sceneEl = this.closestScene();
  49331. this.cacheAttributes();
  49332. this.updateEntities();
  49333. this.load();
  49334. }
  49335. },
  49336. /**
  49337. * setAttribute that parses and caches component values.
  49338. */
  49339. setAttribute: {
  49340. value: function (attr, value) {
  49341. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  49342. this.cacheAttribute(attr, value);
  49343. }
  49344. },
  49345. /**
  49346. * If `attr` is a component, then parse the value using the schema and store it.
  49347. */
  49348. cacheAttribute: {
  49349. value: function (attr, value) {
  49350. var component;
  49351. var componentName;
  49352. // Get component data.
  49353. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  49354. component = components[componentName];
  49355. if (!component) { return; }
  49356. if (value === undefined) {
  49357. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  49358. }
  49359. this.componentCache[attr] = component.parseAttrValueForCache(value);
  49360. }
  49361. },
  49362. /**
  49363. * If `attr` is a component, then grab pre-parsed value from the cache.
  49364. * Else do a normal getAttribute.
  49365. */
  49366. getAttribute: {
  49367. value: function (attr) {
  49368. return this.componentCache[attr] ||
  49369. window.HTMLElement.prototype.getAttribute.call(this, attr);
  49370. }
  49371. },
  49372. /**
  49373. * Parse and cache every component defined on the mixin.
  49374. */
  49375. cacheAttributes: {
  49376. value: function () {
  49377. var attributes = this.attributes;
  49378. var attrName;
  49379. var i;
  49380. for (i = 0; i < attributes.length; i++) {
  49381. attrName = attributes[i].name;
  49382. this.cacheAttribute(attrName);
  49383. }
  49384. }
  49385. },
  49386. /**
  49387. * For entities that already have been loaded by the time the mixin was attached, tell
  49388. * those entities to register the mixin and refresh their component data.
  49389. */
  49390. updateEntities: {
  49391. value: function () {
  49392. var entity;
  49393. var entities;
  49394. var i;
  49395. if (!this.sceneEl) { return; }
  49396. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  49397. for (i = 0; i < entities.length; i++) {
  49398. entity = entities[i];
  49399. if (!entity.hasLoaded || entity.isMixin) { continue; }
  49400. entity.mixinUpdate(this.id);
  49401. }
  49402. }
  49403. }
  49404. })
  49405. });
  49406. },{"../utils":176,"./a-node":101,"./a-register-element":102,"./component":103}],101:[function(_dereq_,module,exports){
  49407. /* global CustomEvent */
  49408. var registerElement = _dereq_('./a-register-element').registerElement;
  49409. var isNode = _dereq_('./a-register-element').isNode;
  49410. var utils = _dereq_('../utils/');
  49411. var warn = utils.debug('core:a-node:warn');
  49412. var error = utils.debug('core:a-node:error');
  49413. /**
  49414. * Base class for A-Frame that manages loading of objects.
  49415. *
  49416. * Nodes can be modified using mixins.
  49417. * Nodes emit a `loaded` event when they and their children have initialized.
  49418. */
  49419. module.exports = registerElement('a-node', {
  49420. prototype: Object.create(window.HTMLElement.prototype, {
  49421. createdCallback: {
  49422. value: function () {
  49423. this.computedMixinStr = '';
  49424. this.hasLoaded = false;
  49425. this.isNode = true;
  49426. this.mixinEls = [];
  49427. },
  49428. writable: window.debug
  49429. },
  49430. attachedCallback: {
  49431. value: function () {
  49432. var mixins;
  49433. this.sceneEl = this.closestScene();
  49434. if (!this.sceneEl) {
  49435. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  49436. 'scene. Append this element to `<a-scene>` instead.');
  49437. }
  49438. this.hasLoaded = false;
  49439. this.emit('nodeready', undefined, false);
  49440. if (!this.isMixin) {
  49441. mixins = this.getAttribute('mixin');
  49442. if (mixins) { this.updateMixins(mixins); }
  49443. }
  49444. },
  49445. writable: window.debug
  49446. },
  49447. /**
  49448. * Handle mixin.
  49449. */
  49450. attributeChangedCallback: {
  49451. value: function (attr, oldVal, newVal) {
  49452. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  49453. if (newVal === this.computedMixinStr) { return; }
  49454. if (attr === 'mixin' && !this.isMixin) {
  49455. this.updateMixins(newVal, oldVal);
  49456. }
  49457. }
  49458. },
  49459. /**
  49460. * Returns the first scene by traversing up the tree starting from and
  49461. * including receiver element.
  49462. */
  49463. closestScene: {
  49464. value: function closest () {
  49465. var element = this;
  49466. while (element) {
  49467. if (element.isScene) { break; }
  49468. element = element.parentElement;
  49469. }
  49470. return element;
  49471. }
  49472. },
  49473. /**
  49474. * Returns first element matching a selector by traversing up the tree starting
  49475. * from and including receiver element.
  49476. *
  49477. * @param {string} selector - Selector of element to find.
  49478. */
  49479. closest: {
  49480. value: function closest (selector) {
  49481. var matches = this.matches || this.mozMatchesSelector ||
  49482. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  49483. var element = this;
  49484. while (element) {
  49485. if (matches.call(element, selector)) { break; }
  49486. element = element.parentElement;
  49487. }
  49488. return element;
  49489. }
  49490. },
  49491. detachedCallback: {
  49492. value: function () {
  49493. this.hasLoaded = false;
  49494. }
  49495. },
  49496. /**
  49497. * Wait for children to load, if any.
  49498. * Then emit `loaded` event and set `hasLoaded`.
  49499. */
  49500. load: {
  49501. value: function (cb, childFilter) {
  49502. var children;
  49503. var childrenLoaded;
  49504. var self = this;
  49505. if (this.hasLoaded) { return; }
  49506. // Default to waiting for all nodes.
  49507. childFilter = childFilter || isNode;
  49508. // Wait for children to load (if any), then load.
  49509. children = this.getChildren();
  49510. childrenLoaded = children.filter(childFilter).map(function (child) {
  49511. return new Promise(function waitForLoaded (resolve) {
  49512. if (child.hasLoaded) { return resolve(); }
  49513. child.addEventListener('loaded', resolve);
  49514. });
  49515. });
  49516. Promise.all(childrenLoaded).then(function emitLoaded () {
  49517. self.hasLoaded = true;
  49518. if (cb) { cb(); }
  49519. self.emit('loaded', undefined, false);
  49520. }).catch(function (err) {
  49521. error('Failure loading node: ', err);
  49522. });
  49523. },
  49524. writable: true
  49525. },
  49526. getChildren: {
  49527. value: function () {
  49528. return Array.prototype.slice.call(this.children, 0);
  49529. }
  49530. },
  49531. /**
  49532. * Unregister old mixins and listeners.
  49533. * Register new mixins and listeners.
  49534. * Registering means to update `this.mixinEls` with listeners.
  49535. */
  49536. updateMixins: {
  49537. value: (function () {
  49538. var newMixinIdArray = [];
  49539. var oldMixinIdArray = [];
  49540. var mixinIds = {};
  49541. return function (newMixins, oldMixins) {
  49542. var i;
  49543. var newMixinIds;
  49544. var oldMixinIds;
  49545. newMixinIdArray.length = 0;
  49546. oldMixinIdArray.length = 0;
  49547. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  49548. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  49549. mixinIds.newMixinIds = newMixinIds;
  49550. mixinIds.oldMixinIds = oldMixinIds;
  49551. // Unregister old mixins.
  49552. for (i = 0; i < oldMixinIds.length; i++) {
  49553. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  49554. this.unregisterMixin(oldMixinIds[i]);
  49555. }
  49556. }
  49557. // Register new mixins.
  49558. this.computedMixinStr = '';
  49559. this.mixinEls.length = 0;
  49560. for (i = 0; i < newMixinIds.length; i++) {
  49561. this.registerMixin(document.getElementById(newMixinIds[i]));
  49562. }
  49563. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  49564. // update.
  49565. if (this.computedMixinStr) {
  49566. this.computedMixinStr = this.computedMixinStr.trim();
  49567. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  49568. this.computedMixinStr);
  49569. }
  49570. return mixinIds;
  49571. };
  49572. })()
  49573. },
  49574. /**
  49575. * From mixin ID, add mixin element to `mixinEls`.
  49576. *
  49577. * @param {Element} mixinEl
  49578. */
  49579. registerMixin: {
  49580. value: function (mixinEl) {
  49581. var compositedMixinIds;
  49582. var i;
  49583. var mixin;
  49584. if (!mixinEl) { return; }
  49585. // Register composited mixins (if mixin has mixins).
  49586. mixin = mixinEl.getAttribute('mixin');
  49587. if (mixin) {
  49588. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  49589. for (i = 0; i < compositedMixinIds.length; i++) {
  49590. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  49591. }
  49592. }
  49593. // Register mixin.
  49594. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  49595. this.mixinEls.push(mixinEl);
  49596. }
  49597. },
  49598. setAttribute: {
  49599. value: function (attr, newValue) {
  49600. if (attr === 'mixin') { this.updateMixins(newValue); }
  49601. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  49602. }
  49603. },
  49604. unregisterMixin: {
  49605. value: function (mixinId) {
  49606. var i;
  49607. var mixinEls = this.mixinEls;
  49608. var mixinEl;
  49609. for (i = 0; i < mixinEls.length; ++i) {
  49610. mixinEl = mixinEls[i];
  49611. if (mixinId === mixinEl.id) {
  49612. mixinEls.splice(i, 1);
  49613. break;
  49614. }
  49615. }
  49616. }
  49617. },
  49618. /**
  49619. * Emit a DOM event.
  49620. *
  49621. * @param {string} name - Name of event.
  49622. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  49623. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  49624. * @param {object} [extraData] - Extra data to pass to the event, if any.
  49625. */
  49626. emit: {
  49627. value: (function () {
  49628. var data = {};
  49629. return function (name, detail, bubbles, extraData) {
  49630. if (bubbles === undefined) { bubbles = true; }
  49631. data.bubbles = !!bubbles;
  49632. data.detail = detail;
  49633. // If extra data is present, we need to create a new object.
  49634. if (extraData) { data = utils.extend({}, extraData, data); }
  49635. this.dispatchEvent(new CustomEvent(name, data));
  49636. };
  49637. })(),
  49638. writable: window.debug
  49639. }
  49640. })
  49641. });
  49642. },{"../utils/":176,"./a-register-element":102}],102:[function(_dereq_,module,exports){
  49643. /*
  49644. ------------------------------------------------------------
  49645. ------------- WARNING WARNING WARNING WARNING --------------
  49646. ------------------------------------------------------------
  49647. This module wraps registerElement to deal with components that inherit from
  49648. `ANode` and `AEntity`. It's a pass through in any other case.
  49649. It wraps some of the prototype methods of the created element to make sure
  49650. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  49651. are also invoked. The method in the base prototype is always called before the one
  49652. in the derived prototype.
  49653. */
  49654. // Polyfill `document.registerElement`.
  49655. _dereq_('document-register-element');
  49656. var ANode; // Must declare before AEntity. Initialized at the bottom.
  49657. var AEntity;
  49658. var knownTags = module.exports.knownTags = {};
  49659. function addTagName (tagName) {
  49660. knownTags[tagName.toLowerCase()] = true;
  49661. }
  49662. /**
  49663. * Return whether the element type is one of our known registered ones.
  49664. *
  49665. * @param {string} node - The name of the tag to register.
  49666. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  49667. */
  49668. module.exports.isNode = function (node) {
  49669. return node.tagName.toLowerCase() in knownTags || node.isNode;
  49670. };
  49671. /**
  49672. * @param {string} tagName - The name of the tag to register.
  49673. * @param {object} obj - The prototype of the new element.
  49674. * @returns {object} The prototype of the new element.
  49675. */
  49676. module.exports.registerElement = function (tagName, obj) {
  49677. var proto = Object.getPrototypeOf(obj.prototype);
  49678. var newObj = obj;
  49679. var isANode = ANode && proto === ANode.prototype;
  49680. var isAEntity = AEntity && proto === AEntity.prototype;
  49681. if (isANode || isAEntity) { addTagName(tagName); }
  49682. // Wrap if element inherits from `ANode`.
  49683. if (isANode) {
  49684. newObj = wrapANodeMethods(obj.prototype);
  49685. newObj = {prototype: Object.create(proto, newObj)};
  49686. }
  49687. // Wrap if element inherits from `AEntity`.
  49688. if (isAEntity) {
  49689. newObj = wrapAEntityMethods(obj.prototype);
  49690. newObj = {prototype: Object.create(proto, newObj)};
  49691. }
  49692. // Give all functions their proper name.
  49693. Object.getOwnPropertyNames(newObj.prototype).forEach(function (propName) {
  49694. var propVal = newObj.prototype[propName];
  49695. if (typeof propVal === 'function') {
  49696. propVal.displayName = propName;
  49697. }
  49698. });
  49699. return document.registerElement(tagName, newObj);
  49700. };
  49701. /**
  49702. * Wrap some obj methods to call those on `ANode` base prototype.
  49703. *
  49704. * @param {object} obj - Object that contains the methods that will be wrapped.
  49705. * @return {object} An object with the same properties as the input parameter but
  49706. * with some of methods wrapped.
  49707. */
  49708. function wrapANodeMethods (obj) {
  49709. var newObj = {};
  49710. var ANodeMethods = [
  49711. 'attachedCallback',
  49712. 'attributeChangedCallback',
  49713. 'createdCallback',
  49714. 'detachedCallback'
  49715. ];
  49716. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49717. copyProperties(obj, newObj);
  49718. return newObj;
  49719. }
  49720. /**
  49721. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  49722. *
  49723. * @param {object} obj - The objects that contains the methods that will be wrapped.
  49724. * @return {object} - An object with the same properties as the input parameter but
  49725. * with some of methods wrapped.
  49726. */
  49727. function wrapAEntityMethods (obj) {
  49728. var newObj = {};
  49729. var ANodeMethods = [
  49730. 'attachedCallback',
  49731. 'attributeChangedCallback',
  49732. 'createdCallback',
  49733. 'detachedCallback'
  49734. ];
  49735. var AEntityMethods = [
  49736. 'attachedCallback',
  49737. 'attributeChangedCallback',
  49738. 'createdCallback',
  49739. 'detachedCallback'
  49740. ];
  49741. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49742. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  49743. // Copies the remaining properties into the new object.
  49744. copyProperties(obj, newObj);
  49745. return newObj;
  49746. }
  49747. /**
  49748. * Wrap a list a methods to ensure that those in the base prototype are called
  49749. * before the derived one.
  49750. *
  49751. * @param {object} targetObj - Object that will contain the wrapped methods.
  49752. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  49753. * @param {object} derivedObject - Object that inherits from the baseObj.
  49754. * @param {object} baseObj - Object that derivedObj inherits from.
  49755. */
  49756. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  49757. methodList.forEach(function (methodName) {
  49758. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  49759. });
  49760. }
  49761. module.exports.wrapMethods = wrapMethods;
  49762. /**
  49763. * Wrap one method to ensure that the one in the base prototype is called before
  49764. * the one in the derived one.
  49765. *
  49766. * @param {object} obj - Object that will contain the wrapped method.
  49767. * @param {string} methodName - The name of the method that will be wrapped.
  49768. * @param {object} derivedObject - Object that inherits from the baseObj.
  49769. * @param {object} baseObj - Object that derivedObj inherits from.
  49770. */
  49771. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  49772. var derivedMethod = derivedObj[methodName];
  49773. var baseMethod = baseObj[methodName];
  49774. // Derived prototype does not define method, no need to wrap.
  49775. if (!derivedMethod || !baseMethod) { return; }
  49776. // Derived prototype doesn't override the one in the base one, no need to wrap.
  49777. if (derivedMethod === baseMethod) { return; }
  49778. // Wrap to ensure the base method is called before the one in the derived prototype.
  49779. obj[methodName] = {
  49780. value: function wrappedMethod () {
  49781. baseMethod.apply(this, arguments);
  49782. return derivedMethod.apply(this, arguments);
  49783. },
  49784. writable: window.debug
  49785. };
  49786. }
  49787. /**
  49788. * It copies the properties from source to destination object if they don't
  49789. * exist already.
  49790. *
  49791. * @param {object} source - The object where properties are copied from.
  49792. * @param {type} destination - The object where properties are copied to.
  49793. */
  49794. function copyProperties (source, destination) {
  49795. var props = Object.getOwnPropertyNames(source);
  49796. props.forEach(function (prop) {
  49797. var desc;
  49798. if (!destination[prop]) {
  49799. desc = Object.getOwnPropertyDescriptor(source, prop);
  49800. destination[prop] = {value: source[prop], writable: desc.writable};
  49801. }
  49802. });
  49803. }
  49804. ANode = _dereq_('./a-node');
  49805. AEntity = _dereq_('./a-entity');
  49806. },{"./a-entity":99,"./a-node":101,"document-register-element":11}],103:[function(_dereq_,module,exports){
  49807. /* global Node */
  49808. var schema = _dereq_('./schema');
  49809. var scenes = _dereq_('./scene/scenes');
  49810. var systems = _dereq_('./system');
  49811. var utils = _dereq_('../utils/');
  49812. var components = module.exports.components = {}; // Keep track of registered components.
  49813. var parseProperties = schema.parseProperties;
  49814. var parseProperty = schema.parseProperty;
  49815. var processSchema = schema.process;
  49816. var isSingleProp = schema.isSingleProperty;
  49817. var stringifyProperties = schema.stringifyProperties;
  49818. var stringifyProperty = schema.stringifyProperty;
  49819. var styleParser = utils.styleParser;
  49820. var warn = utils.debug('core:component:warn');
  49821. var aframeScript = document.currentScript;
  49822. var upperCaseRegExp = new RegExp('[A-Z]+');
  49823. // Object pools by component, created upon registration.
  49824. var objectPools = {};
  49825. /**
  49826. * Component class definition.
  49827. *
  49828. * Components configure appearance, modify behavior, or add functionality to
  49829. * entities. The behavior and appearance of an entity can be changed at runtime
  49830. * by adding, removing, or updating components. Entities do not share instances
  49831. * of components.
  49832. *
  49833. * @member {object} el - Reference to the entity element.
  49834. * @member {string} attrValue - Value of the corresponding HTML attribute.
  49835. * @member {object} data - Component data populated by parsing the
  49836. * mapped attribute of the component plus applying defaults and mixins.
  49837. */
  49838. var Component = module.exports.Component = function (el, attrValue, id) {
  49839. var self = this;
  49840. this.el = el;
  49841. this.id = id;
  49842. this.attrName = this.name + (id ? '__' + id : '');
  49843. this.evtDetail = {id: this.id, name: this.name};
  49844. this.initialized = false;
  49845. this.isSingleProperty = isSingleProp(this.schema);
  49846. this.isSinglePropertyObject = this.isSingleProperty &&
  49847. isObject(parseProperty(undefined, this.schema)) &&
  49848. !(this.schema.default instanceof window.HTMLElement);
  49849. this.isObjectBased = !this.isSingleProperty || this.isSinglePropertyObject;
  49850. this.el.components[this.attrName] = this;
  49851. this.objectPool = objectPools[this.name];
  49852. eventsBind(this, this.events);
  49853. // Store component data from previous update call.
  49854. this.attrValue = undefined;
  49855. if (this.isObjectBased) {
  49856. this.nextData = this.objectPool.use();
  49857. // Drop any properties added by dynamic schemas in previous use
  49858. utils.objectPool.removeUnusedKeys(this.nextData, this.schema);
  49859. this.oldData = this.objectPool.use();
  49860. utils.objectPool.removeUnusedKeys(this.oldData, this.schema);
  49861. this.previousOldData = this.objectPool.use();
  49862. utils.objectPool.removeUnusedKeys(this.previousOldData, this.schema);
  49863. this.parsingAttrValue = this.objectPool.use();
  49864. utils.objectPool.removeUnusedKeys(this.parsingAttrValue, this.schema);
  49865. } else {
  49866. this.nextData = undefined;
  49867. this.oldData = undefined;
  49868. this.previousOldData = undefined;
  49869. this.parsingAttrValue = undefined;
  49870. }
  49871. // Last value passed to updateProperties.
  49872. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  49873. el.emit('componentchanged', self.evtDetail, false);
  49874. }, 200);
  49875. this.updateProperties(attrValue);
  49876. };
  49877. Component.prototype = {
  49878. /**
  49879. * Contains the type schema and defaults for the data values.
  49880. * Data is coerced into the types of the values of the defaults.
  49881. */
  49882. schema: {},
  49883. /**
  49884. * Init handler. Similar to attachedCallback.
  49885. * Called during component initialization and is only run once.
  49886. * Components can use this to set initial state.
  49887. */
  49888. init: function () { /* no-op */ },
  49889. /**
  49890. * Map of event names to binded event handlers that will be lifecycle-handled.
  49891. * Will be detached on pause / remove.
  49892. * Will be attached on play.
  49893. */
  49894. events: {},
  49895. /**
  49896. * Update handler. Similar to attributeChangedCallback.
  49897. * Called whenever component's data changes.
  49898. * Also called on component initialization when the component receives initial data.
  49899. *
  49900. * @param {object} prevData - Previous attributes of the component.
  49901. */
  49902. update: function (prevData) { /* no-op */ },
  49903. updateSchema: undefined,
  49904. /**
  49905. * Tick handler.
  49906. * Called on each tick of the scene render loop.
  49907. * Affected by play and pause.
  49908. *
  49909. * @param {number} time - Scene tick time.
  49910. * @param {number} timeDelta - Difference in current render time and previous render time.
  49911. */
  49912. tick: undefined,
  49913. /**
  49914. * Tock handler.
  49915. * Called on each tock of the scene render loop.
  49916. * Affected by play and pause.
  49917. *
  49918. * @param {number} time - Scene tick time.
  49919. * @param {number} timeDelta - Difference in current render time and previous render time.
  49920. * @param {object} camera - Camera used to render the last frame.
  49921. */
  49922. tock: undefined,
  49923. /**
  49924. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  49925. */
  49926. play: function () { /* no-op */ },
  49927. /**
  49928. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  49929. */
  49930. pause: function () { /* no-op */ },
  49931. /**
  49932. * Remove handler. Similar to detachedCallback.
  49933. * Called whenever component is removed from the entity (i.e., removeAttribute).
  49934. * Components can use this to reset behavior on the entity.
  49935. */
  49936. remove: function () { /* no-op */ },
  49937. /**
  49938. * Parses each property based on property type.
  49939. * If component is single-property, then parses the single property value.
  49940. *
  49941. * @param {string} value - HTML attribute value.
  49942. * @param {boolean} silent - Suppress warning messages.
  49943. * @returns {object} Component data.
  49944. */
  49945. parse: function (value, silent) {
  49946. var schema = this.schema;
  49947. if (this.isSingleProperty) { return parseProperty(value, schema); }
  49948. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  49949. },
  49950. /**
  49951. * Stringify properties if necessary.
  49952. *
  49953. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  49954. * value (e.g., selector, vec3 property types).
  49955. *
  49956. * @param {object} data - Complete component data.
  49957. * @returns {string}
  49958. */
  49959. stringify: function (data) {
  49960. var schema = this.schema;
  49961. if (typeof data === 'string') { return data; }
  49962. if (this.isSingleProperty) { return stringifyProperty(data, schema); }
  49963. data = stringifyProperties(data, schema);
  49964. return styleParser.stringify(data);
  49965. },
  49966. /**
  49967. * Update the cache of the pre-parsed attribute value.
  49968. *
  49969. * @param {string} value - New data.
  49970. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  49971. */
  49972. updateCachedAttrValue: function (value, clobber) {
  49973. var newAttrValue;
  49974. var tempObject;
  49975. var property;
  49976. if (value === undefined) { return; }
  49977. // If null value is the new attribute value, make the attribute value falsy.
  49978. if (value === null) {
  49979. if (this.isObjectBased && this.attrValue) {
  49980. this.objectPool.recycle(this.attrValue);
  49981. }
  49982. this.attrValue = undefined;
  49983. return;
  49984. }
  49985. if (value instanceof Object && !(value instanceof window.HTMLElement)) {
  49986. // If value is an object, copy it to our pooled newAttrValue object to use to update
  49987. // the attrValue.
  49988. tempObject = this.objectPool.use();
  49989. newAttrValue = utils.extend(tempObject, value);
  49990. } else {
  49991. newAttrValue = this.parseAttrValueForCache(value);
  49992. }
  49993. // Merge new data with previous `attrValue` if updating and not clobbering.
  49994. if (this.isObjectBased && !clobber && this.attrValue) {
  49995. for (property in this.attrValue) {
  49996. if (newAttrValue[property] === undefined) {
  49997. newAttrValue[property] = this.attrValue[property];
  49998. }
  49999. }
  50000. }
  50001. // Update attrValue.
  50002. if (this.isObjectBased && !this.attrValue) {
  50003. this.attrValue = this.objectPool.use();
  50004. }
  50005. utils.objectPool.clearObject(this.attrValue);
  50006. this.attrValue = extendProperties(this.attrValue, newAttrValue, this.isObjectBased);
  50007. utils.objectPool.clearObject(tempObject);
  50008. },
  50009. /**
  50010. * Given an HTML attribute value parses the string based on the component schema.
  50011. * To avoid double parsings of strings into strings we store the original instead
  50012. * of the parsed one
  50013. *
  50014. * @param {string} value - HTML attribute value
  50015. */
  50016. parseAttrValueForCache: function (value) {
  50017. var parsedValue;
  50018. if (typeof value !== 'string') { return value; }
  50019. if (this.isSingleProperty) {
  50020. parsedValue = this.schema.parse(value);
  50021. /**
  50022. * To avoid bogus double parsings. Cached values will be parsed when building
  50023. * component data. For instance when parsing a src id to its url, we want to cache
  50024. * original string and not the parsed one (#monster -> models/monster.dae)
  50025. * so when building data we parse the expected value.
  50026. */
  50027. if (typeof parsedValue === 'string') { parsedValue = value; }
  50028. } else {
  50029. // Parse using the style parser to avoid double parsing of individual properties.
  50030. utils.objectPool.clearObject(this.parsingAttrValue);
  50031. parsedValue = styleParser.parse(value, this.parsingAttrValue);
  50032. }
  50033. return parsedValue;
  50034. },
  50035. /**
  50036. * Write cached attribute data to the entity DOM element.
  50037. *
  50038. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  50039. * default components.
  50040. */
  50041. flushToDOM: function (isDefault) {
  50042. var attrValue = isDefault ? this.data : this.attrValue;
  50043. if (attrValue === null || attrValue === undefined) { return; }
  50044. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  50045. this.stringify(attrValue));
  50046. },
  50047. /**
  50048. * Apply new component data if data has changed (from setAttribute).
  50049. *
  50050. * @param {string} attrValue - HTML attribute value.
  50051. * If undefined, use the cached attribute value and continue updating properties.
  50052. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  50053. */
  50054. updateProperties: function (attrValue, clobber) {
  50055. var el = this.el;
  50056. // Just cache the attribute if the entity has not loaded
  50057. // Components are not initialized until the entity has loaded
  50058. if (!el.hasLoaded) {
  50059. this.updateCachedAttrValue(attrValue);
  50060. return;
  50061. }
  50062. // Parse the attribute value.
  50063. // Cache current attrValue for future updates. Updates `this.attrValue`.
  50064. // `null` means no value on purpose, do not set a default value, let mixins take over.
  50065. if (attrValue !== null) {
  50066. attrValue = this.parseAttrValueForCache(attrValue);
  50067. }
  50068. // Cache current attrValue for future updates.
  50069. this.updateCachedAttrValue(attrValue, clobber);
  50070. if (this.initialized) {
  50071. this.updateComponent(attrValue, clobber);
  50072. this.callUpdateHandler();
  50073. } else {
  50074. this.initComponent();
  50075. }
  50076. },
  50077. initComponent: function () {
  50078. var el = this.el;
  50079. var initialOldData;
  50080. // Build data.
  50081. if (this.updateSchema) { this.updateSchema(this.buildData(this.attrValue, false, true)); }
  50082. this.data = this.buildData(this.attrValue);
  50083. // Component is being already initialized.
  50084. if (el.initializingComponents[this.name]) { return; }
  50085. // Prevent infinite loop in case of init method setting same component on the entity.
  50086. el.initializingComponents[this.name] = true;
  50087. // Initialize component.
  50088. this.init();
  50089. this.initialized = true;
  50090. delete el.initializingComponents[this.name];
  50091. // Store current data as previous data for future updates.
  50092. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  50093. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  50094. // Pass undefined to rest of types.
  50095. initialOldData = this.isObjectBased ? this.objectPool.use() : undefined;
  50096. this.update(initialOldData);
  50097. if (this.isObjectBased) { this.objectPool.recycle(initialOldData); }
  50098. // Play the component if the entity is playing.
  50099. if (el.isPlaying) { this.play(); }
  50100. el.emit('componentinitialized', this.evtDetail, false);
  50101. },
  50102. /**
  50103. * @param attrValue - Passed argument from setAttribute.
  50104. */
  50105. updateComponent: function (attrValue, clobber) {
  50106. var key;
  50107. var mayNeedSchemaUpdate;
  50108. if (clobber) {
  50109. // Clobber. Rebuild.
  50110. if (this.updateSchema) {
  50111. this.updateSchema(this.buildData(this.attrValue, true, true));
  50112. }
  50113. this.data = this.buildData(this.attrValue, true, false);
  50114. return;
  50115. }
  50116. // Apply new value to this.data in place since direct update.
  50117. if (this.isSingleProperty) {
  50118. if (this.isObjectBased) {
  50119. parseProperty(attrValue, this.schema);
  50120. }
  50121. // Single-property (already parsed).
  50122. this.data = attrValue;
  50123. return;
  50124. }
  50125. parseProperties(attrValue, this.schema, true, this.name);
  50126. // Check if we need to update schema.
  50127. if (this.schemaChangeKeys.length) {
  50128. for (key in attrValue) {
  50129. if (this.schema[key].schemaChange) {
  50130. mayNeedSchemaUpdate = true;
  50131. break;
  50132. }
  50133. }
  50134. }
  50135. if (mayNeedSchemaUpdate) {
  50136. // Rebuild data if need schema update.
  50137. if (this.updateSchema) {
  50138. this.updateSchema(this.buildData(this.attrValue, true, true));
  50139. }
  50140. this.data = this.buildData(this.attrValue, true, false);
  50141. return;
  50142. }
  50143. // Normal update.
  50144. for (key in attrValue) {
  50145. if (attrValue[key] === undefined) { continue; }
  50146. this.data[key] = attrValue[key];
  50147. }
  50148. },
  50149. /**
  50150. * Check if component should fire update and fire update lifecycle handler.
  50151. */
  50152. callUpdateHandler: function () {
  50153. var hasComponentChanged;
  50154. // Store the previous old data before we calculate the new oldData.
  50155. if (this.previousOldData instanceof Object) {
  50156. utils.objectPool.clearObject(this.previousOldData);
  50157. }
  50158. if (this.isObjectBased) {
  50159. copyData(this.previousOldData, this.oldData);
  50160. } else {
  50161. this.previousOldData = this.oldData;
  50162. }
  50163. hasComponentChanged = !utils.deepEqual(this.oldData, this.data);
  50164. // Don't update if properties haven't changed.
  50165. // Always update rotation, position, scale.
  50166. if (!this.isPositionRotationScale && !hasComponentChanged) { return; }
  50167. // Store current data as previous data for future updates.
  50168. // Reuse `this.oldData` object to try not to allocate another one.
  50169. if (this.oldData instanceof Object) { utils.objectPool.clearObject(this.oldData); }
  50170. this.oldData = extendProperties(this.oldData, this.data, this.isObjectBased);
  50171. // Update component with the previous old data.
  50172. this.update(this.previousOldData);
  50173. this.throttledEmitComponentChanged();
  50174. },
  50175. handleMixinUpdate: function () {
  50176. this.data = this.buildData(this.attrValue);
  50177. this.callUpdateHandler();
  50178. },
  50179. /**
  50180. * Reset value of a property to the property's default value.
  50181. * If single-prop component, reset value to component's default value.
  50182. *
  50183. * @param {string} propertyName - Name of property to reset.
  50184. */
  50185. resetProperty: function (propertyName) {
  50186. if (this.isObjectBased) {
  50187. if (!(propertyName in this.attrValue)) { return; }
  50188. delete this.attrValue[propertyName];
  50189. this.data[propertyName] = this.schema[propertyName].default;
  50190. } else {
  50191. this.attrValue = this.schema.default;
  50192. this.data = this.schema.default;
  50193. }
  50194. this.updateProperties(this.attrValue);
  50195. },
  50196. /**
  50197. * Extend schema of component given a partial schema.
  50198. *
  50199. * Some components might want to mutate their schema based on certain properties.
  50200. * e.g., Material component changes its schema based on `shader` to account for different
  50201. * uniforms
  50202. *
  50203. * @param {object} schemaAddon - Schema chunk that extend base schema.
  50204. */
  50205. extendSchema: function (schemaAddon) {
  50206. var extendedSchema;
  50207. // Clone base schema.
  50208. extendedSchema = utils.extend({}, components[this.name].schema);
  50209. // Extend base schema with new schema chunk.
  50210. utils.extend(extendedSchema, schemaAddon);
  50211. this.schema = processSchema(extendedSchema);
  50212. this.el.emit('schemachanged', this.evtDetail);
  50213. },
  50214. /**
  50215. * Build component data from the current state of the entity.data.
  50216. *
  50217. * Precedence:
  50218. * 1. Defaults data
  50219. * 2. Mixin data.
  50220. * 3. Attribute data.
  50221. *
  50222. * Finally coerce the data to the types of the defaults.
  50223. *
  50224. * @param {object} newData - Element new data.
  50225. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  50226. * @param {boolean} silent - Suppress warning messages.
  50227. * @return {object} The component data
  50228. */
  50229. buildData: function (newData, clobber, silent) {
  50230. var componentDefined;
  50231. var data;
  50232. var defaultValue;
  50233. var key;
  50234. var mixinData;
  50235. var nextData = this.nextData;
  50236. var schema = this.schema;
  50237. var i;
  50238. var mixinEls = this.el.mixinEls;
  50239. var previousData;
  50240. // Whether component has a defined value. For arrays, treat empty as not defined.
  50241. componentDefined = newData && newData.constructor === Array
  50242. ? newData.length
  50243. : newData !== undefined && newData !== null;
  50244. if (this.isObjectBased) { utils.objectPool.clearObject(nextData); }
  50245. // 1. Gather default values (lowest precendence).
  50246. if (this.isSingleProperty) {
  50247. if (this.isObjectBased) {
  50248. // If object-based single-prop, then copy over the data to our pooled object.
  50249. data = copyData(nextData, schema.default);
  50250. } else {
  50251. // If is plain single-prop, copy by value the default.
  50252. data = isObjectOrArray(schema.default)
  50253. ? utils.clone(schema.default)
  50254. : schema.default;
  50255. }
  50256. } else {
  50257. // Preserve previously set properties if clobber not enabled.
  50258. previousData = !clobber && this.attrValue;
  50259. // Clone default value if object so components don't share object
  50260. data = previousData instanceof Object
  50261. ? copyData(nextData, previousData)
  50262. : nextData;
  50263. // Apply defaults.
  50264. for (key in schema) {
  50265. defaultValue = schema[key].default;
  50266. if (data[key] !== undefined) { continue; }
  50267. // Clone default value if object so components don't share object
  50268. data[key] = isObjectOrArray(defaultValue)
  50269. ? utils.clone(defaultValue)
  50270. : defaultValue;
  50271. }
  50272. }
  50273. // 2. Gather mixin values.
  50274. for (i = 0; i < mixinEls.length; i++) {
  50275. mixinData = mixinEls[i].getAttribute(this.attrName);
  50276. if (!mixinData) { continue; }
  50277. data = extendProperties(data, mixinData, this.isObjectBased);
  50278. }
  50279. // 3. Gather attribute values (highest precendence).
  50280. if (componentDefined) {
  50281. if (this.isSingleProperty) {
  50282. // If object-based, copy the value to not modify the original.
  50283. if (isObject(newData)) {
  50284. copyData(this.parsingAttrValue, newData);
  50285. return parseProperty(this.parsingAttrValue, schema);
  50286. }
  50287. return parseProperty(newData, schema);
  50288. }
  50289. data = extendProperties(data, newData, this.isObjectBased);
  50290. } else {
  50291. // Parse and coerce using the schema.
  50292. if (this.isSingleProperty) { return parseProperty(data, schema); }
  50293. }
  50294. return parseProperties(data, schema, undefined, this.name, silent);
  50295. },
  50296. /**
  50297. * Attach events from component-defined events map.
  50298. */
  50299. eventsAttach: function () {
  50300. var eventName;
  50301. // Safety detach to prevent double-registration.
  50302. this.eventsDetach();
  50303. for (eventName in this.events) {
  50304. this.el.addEventListener(eventName, this.events[eventName]);
  50305. }
  50306. },
  50307. /**
  50308. * Detach events from component-defined events map.
  50309. */
  50310. eventsDetach: function () {
  50311. var eventName;
  50312. for (eventName in this.events) {
  50313. this.el.removeEventListener(eventName, this.events[eventName]);
  50314. }
  50315. },
  50316. /**
  50317. * Release and free memory.
  50318. */
  50319. destroy: function () {
  50320. this.objectPool.recycle(this.attrValue);
  50321. this.objectPool.recycle(this.oldData);
  50322. this.objectPool.recycle(this.parsingAttrValue);
  50323. this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  50324. }
  50325. };
  50326. function eventsBind (component, events) {
  50327. var eventName;
  50328. for (eventName in events) {
  50329. events[eventName] = events[eventName].bind(component);
  50330. }
  50331. }
  50332. // For testing.
  50333. if (window.debug) {
  50334. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  50335. }
  50336. /**
  50337. * Register a component to A-Frame.
  50338. *
  50339. * @param {string} name - Component name.
  50340. * @param {object} definition - Component schema and lifecycle method handlers.
  50341. * @returns {object} Component.
  50342. */
  50343. module.exports.registerComponent = function (name, definition) {
  50344. var NewComponent;
  50345. var propertyName;
  50346. var proto = {};
  50347. var schema;
  50348. var schemaIsSingleProp;
  50349. // Warning if component is statically registered after the scene.
  50350. if (document.currentScript && document.currentScript !== aframeScript) {
  50351. scenes.forEach(function checkPosition (sceneEl) {
  50352. // Okay to register component after the scene at runtime.
  50353. if (sceneEl.hasLoaded) { return; }
  50354. // Check that component is declared before the scene.
  50355. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  50356. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  50357. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  50358. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  50359. 'such that the component is available to entities during scene initialization.');
  50360. // For testing.
  50361. if (window.debug) { registrationOrderWarnings[name] = true; }
  50362. });
  50363. }
  50364. if (upperCaseRegExp.test(name) === true) {
  50365. warn('The component name `' + name + '` contains uppercase characters, but ' +
  50366. 'HTML will ignore the capitalization of attribute names. ' +
  50367. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  50368. }
  50369. if (name.indexOf('__') !== -1) {
  50370. throw new Error('The component name `' + name + '` is not allowed. ' +
  50371. 'The sequence __ (double underscore) is reserved to specify an id' +
  50372. ' for multiple components of the same type');
  50373. }
  50374. // Format definition object to prototype object.
  50375. Object.keys(definition).forEach(function (key) {
  50376. proto[key] = {
  50377. value: definition[key],
  50378. writable: true
  50379. };
  50380. });
  50381. if (components[name]) {
  50382. throw new Error('The component `' + name + '` has been already registered. ' +
  50383. 'Check that you are not loading two versions of the same component ' +
  50384. 'or two different components of the same name.');
  50385. }
  50386. NewComponent = function (el, attr, id) {
  50387. Component.call(this, el, attr, id);
  50388. };
  50389. NewComponent.prototype = Object.create(Component.prototype, proto);
  50390. NewComponent.prototype.name = name;
  50391. NewComponent.prototype.isPositionRotationScale =
  50392. name === 'position' || name === 'rotation' || name === 'scale';
  50393. NewComponent.prototype.constructor = NewComponent;
  50394. NewComponent.prototype.system = systems && systems.systems[name];
  50395. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  50396. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  50397. schema = utils.extend(processSchema(NewComponent.prototype.schema,
  50398. NewComponent.prototype.name));
  50399. schemaIsSingleProp = isSingleProp(NewComponent.prototype.schema);
  50400. // Keep track of keys that may potentially change the schema.
  50401. if (!schemaIsSingleProp) {
  50402. NewComponent.prototype.schemaChangeKeys = [];
  50403. for (propertyName in schema) {
  50404. if (schema[propertyName].schemaChange) {
  50405. NewComponent.prototype.schemaChangeKeys.push(propertyName);
  50406. }
  50407. }
  50408. }
  50409. // Create object pool for class of components.
  50410. objectPools[name] = utils.objectPool.createPool();
  50411. components[name] = {
  50412. Component: NewComponent,
  50413. dependencies: NewComponent.prototype.dependencies,
  50414. isSingleProp: schemaIsSingleProp,
  50415. multiple: NewComponent.prototype.multiple,
  50416. name: name,
  50417. parse: NewComponent.prototype.parse,
  50418. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  50419. schema: schema,
  50420. stringify: NewComponent.prototype.stringify,
  50421. type: NewComponent.prototype.type
  50422. };
  50423. return NewComponent;
  50424. };
  50425. /**
  50426. * Clone component data.
  50427. * Clone only the properties that are plain objects while keeping a reference for the rest.
  50428. *
  50429. * @param data - Component data to clone.
  50430. * @returns Cloned data.
  50431. */
  50432. function copyData (dest, sourceData) {
  50433. var parsedProperty;
  50434. var key;
  50435. for (key in sourceData) {
  50436. if (sourceData[key] === undefined) { continue; }
  50437. parsedProperty = sourceData[key];
  50438. dest[key] = isObjectOrArray(parsedProperty)
  50439. ? utils.clone(parsedProperty)
  50440. : parsedProperty;
  50441. }
  50442. return dest;
  50443. }
  50444. /**
  50445. * Object extending with checking for single-property schema.
  50446. *
  50447. * @param dest - Destination object or value.
  50448. * @param source - Source object or value
  50449. * @param {boolean} isObjectBased - Whether values are objects.
  50450. * @returns Overridden object or value.
  50451. */
  50452. function extendProperties (dest, source, isObjectBased) {
  50453. var key;
  50454. if (isObjectBased && source.constructor === Object) {
  50455. for (key in source) {
  50456. if (source[key] === undefined) { continue; }
  50457. if (source[key] && source[key].constructor === Object) {
  50458. dest[key] = utils.clone(source[key]);
  50459. } else {
  50460. dest[key] = source[key];
  50461. }
  50462. }
  50463. return dest;
  50464. }
  50465. return source;
  50466. }
  50467. /**
  50468. * Checks if a component has defined a method that needs to run every frame.
  50469. */
  50470. function hasBehavior (component) {
  50471. return component.tick || component.tock;
  50472. }
  50473. /**
  50474. * Wrapper for defined pause method.
  50475. * Pause component by removing tick behavior and calling user's pause method.
  50476. *
  50477. * @param pauseMethod {function}
  50478. */
  50479. function wrapPause (pauseMethod) {
  50480. return function pause () {
  50481. var sceneEl = this.el.sceneEl;
  50482. if (!this.isPlaying) { return; }
  50483. pauseMethod.call(this);
  50484. this.isPlaying = false;
  50485. this.eventsDetach();
  50486. // Remove tick behavior.
  50487. if (!hasBehavior(this)) { return; }
  50488. sceneEl.removeBehavior(this);
  50489. };
  50490. }
  50491. /**
  50492. * Wrapper for defined play method.
  50493. * Play component by adding tick behavior and calling user's play method.
  50494. *
  50495. * @param playMethod {function}
  50496. */
  50497. function wrapPlay (playMethod) {
  50498. return function play () {
  50499. var sceneEl = this.el.sceneEl;
  50500. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  50501. if (!this.initialized || !shouldPlay) { return; }
  50502. playMethod.call(this);
  50503. this.isPlaying = true;
  50504. this.eventsAttach();
  50505. // Add tick behavior.
  50506. if (!hasBehavior(this)) { return; }
  50507. sceneEl.addBehavior(this);
  50508. };
  50509. }
  50510. function isObject (value) {
  50511. return value && value.constructor === Object && !(value instanceof window.HTMLElement);
  50512. }
  50513. function isObjectOrArray (value) {
  50514. return value && (value.constructor === Object || value.constructor === Array) &&
  50515. !(value instanceof window.HTMLElement);
  50516. }
  50517. },{"../utils/":176,"./scene/scenes":110,"./schema":112,"./system":114}],104:[function(_dereq_,module,exports){
  50518. var schema = _dereq_('./schema');
  50519. var processSchema = schema.process;
  50520. var geometries = module.exports.geometries = {}; // Registered geometries.
  50521. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  50522. var THREE = _dereq_('../lib/three');
  50523. /**
  50524. * Geometry class definition.
  50525. *
  50526. * Geometries extend the geometry component API to create and register geometry types.
  50527. */
  50528. var Geometry = module.exports.Geometry = function () {};
  50529. Geometry.prototype = {
  50530. /**
  50531. * Contains the type schema and defaults for the data values.
  50532. * Data is coerced into the types of the values of the defaults.
  50533. */
  50534. schema: {},
  50535. /**
  50536. * Init handler. Similar to attachedCallback.
  50537. * Called during shader initialization and is only run once.
  50538. */
  50539. init: function (data) {
  50540. this.geometry = new THREE.Geometry();
  50541. return this.geometry;
  50542. },
  50543. /**
  50544. * Update handler. Similar to attributeChangedCallback.
  50545. * Called whenever the associated geometry data changes.
  50546. *
  50547. * @param {object} data - New geometry data.
  50548. */
  50549. update: function (data) { /* no-op */ }
  50550. };
  50551. /**
  50552. * Registers a geometry to A-Frame.
  50553. *
  50554. * @param {string} name - Geometry name.
  50555. * @param {object} definition - Geometry property and methods.
  50556. * @returns {object} Geometry.
  50557. */
  50558. module.exports.registerGeometry = function (name, definition) {
  50559. var NewGeometry;
  50560. var proto = {};
  50561. // Format definition object to prototype object.
  50562. Object.keys(definition).forEach(function expandDefinition (key) {
  50563. proto[key] = {
  50564. value: definition[key],
  50565. writable: true
  50566. };
  50567. });
  50568. if (geometries[name]) {
  50569. throw new Error('The geometry `' + name + '` has been already registered');
  50570. }
  50571. NewGeometry = function () { Geometry.call(this); };
  50572. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  50573. NewGeometry.prototype.name = name;
  50574. NewGeometry.prototype.constructor = NewGeometry;
  50575. geometries[name] = {
  50576. Geometry: NewGeometry,
  50577. schema: processSchema(NewGeometry.prototype.schema)
  50578. };
  50579. geometryNames.push(name);
  50580. return NewGeometry;
  50581. };
  50582. },{"../lib/three":151,"./schema":112}],105:[function(_dereq_,module,exports){
  50583. var coordinates = _dereq_('../utils/coordinates');
  50584. var debug = _dereq_('debug');
  50585. var error = debug('core:propertyTypes:warn');
  50586. var warn = debug('core:propertyTypes:warn');
  50587. var propertyTypes = module.exports.propertyTypes = {};
  50588. var nonCharRegex = /[,> .[\]:]/;
  50589. var urlRegex = /\url\((.+)\)/;
  50590. // Built-in property types.
  50591. registerPropertyType('audio', '', assetParse);
  50592. registerPropertyType('array', [], arrayParse, arrayStringify);
  50593. registerPropertyType('asset', '', assetParse);
  50594. registerPropertyType('boolean', false, boolParse);
  50595. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  50596. registerPropertyType('int', 0, intParse);
  50597. registerPropertyType('number', 0, numberParse);
  50598. registerPropertyType('map', '', assetParse);
  50599. registerPropertyType('model', '', assetParse);
  50600. registerPropertyType('selector', null, selectorParse, selectorStringify);
  50601. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  50602. registerPropertyType('src', '', srcParse);
  50603. registerPropertyType('string', '', defaultParse, defaultStringify);
  50604. registerPropertyType('time', 0, intParse);
  50605. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  50606. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  50607. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 1}, vecParse, coordinates.stringify);
  50608. /**
  50609. * Register a parser for re-use such that when someone uses `type` in the schema,
  50610. * `schema.process` will set the property `parse` and `stringify`.
  50611. *
  50612. * @param {string} type - Type name.
  50613. * @param [defaultValue=null] -
  50614. * Default value to use if component does not define default value.
  50615. * @param {function} [parse=defaultParse] - Parse string function.
  50616. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  50617. */
  50618. function registerPropertyType (type, defaultValue, parse, stringify) {
  50619. if ('type' in propertyTypes) {
  50620. error('Property type ' + type + ' is already registered.');
  50621. return;
  50622. }
  50623. propertyTypes[type] = {
  50624. default: defaultValue,
  50625. parse: parse || defaultParse,
  50626. stringify: stringify || defaultStringify
  50627. };
  50628. }
  50629. module.exports.registerPropertyType = registerPropertyType;
  50630. function arrayParse (value) {
  50631. if (Array.isArray(value)) { return value; }
  50632. if (!value || typeof value !== 'string') { return []; }
  50633. return value.split(',').map(trim);
  50634. function trim (str) { return str.trim(); }
  50635. }
  50636. function arrayStringify (value) {
  50637. return value.join(', ');
  50638. }
  50639. /**
  50640. * For general assets.
  50641. *
  50642. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  50643. * just string.
  50644. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  50645. * just string.
  50646. */
  50647. function assetParse (value) {
  50648. var el;
  50649. var parsedUrl;
  50650. // If an element was provided (e.g. canvas or video), just return it.
  50651. if (typeof value !== 'string') { return value; }
  50652. // Wrapped `url()` in case of data URI.
  50653. parsedUrl = value.match(urlRegex);
  50654. if (parsedUrl) { return parsedUrl[1]; }
  50655. // ID.
  50656. if (value.charAt(0) === '#') {
  50657. el = document.getElementById(value.substring(1));
  50658. if (el) {
  50659. // Pass through media elements. If we have the elements, we don't have to call
  50660. // three.js loaders which would re-request the assets.
  50661. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  50662. return el;
  50663. }
  50664. return el.getAttribute('src');
  50665. }
  50666. warn('"' + value + '" asset not found.');
  50667. return;
  50668. }
  50669. // Non-wrapped url().
  50670. return value;
  50671. }
  50672. function defaultParse (value) {
  50673. return value;
  50674. }
  50675. function defaultStringify (value) {
  50676. if (value === null) { return 'null'; }
  50677. return value.toString();
  50678. }
  50679. function boolParse (value) {
  50680. return value !== 'false' && value !== false;
  50681. }
  50682. function intParse (value) {
  50683. return parseInt(value, 10);
  50684. }
  50685. function numberParse (value) {
  50686. return parseFloat(value, 10);
  50687. }
  50688. function selectorParse (value) {
  50689. if (!value) { return null; }
  50690. if (typeof value !== 'string') { return value; }
  50691. if (value[0] === '#' && !nonCharRegex.test(value)) {
  50692. // When selecting element by ID only, use getElementById for better performance.
  50693. // Don't match like #myId .child.
  50694. return document.getElementById(value.substring(1));
  50695. }
  50696. return document.querySelector(value);
  50697. }
  50698. function selectorAllParse (value) {
  50699. if (!value) { return null; }
  50700. if (typeof value !== 'string') { return value; }
  50701. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  50702. }
  50703. function selectorStringify (value) {
  50704. if (value.getAttribute) {
  50705. return '#' + value.getAttribute('id');
  50706. }
  50707. return defaultStringify(value);
  50708. }
  50709. function selectorAllStringify (value) {
  50710. if (value instanceof Array) {
  50711. return value.map(function (element) {
  50712. return '#' + element.getAttribute('id');
  50713. }).join(', ');
  50714. }
  50715. return defaultStringify(value);
  50716. }
  50717. function srcParse (value) {
  50718. warn('`src` property type is deprecated. Use `asset` instead.');
  50719. return assetParse(value);
  50720. }
  50721. function vecParse (value) {
  50722. return coordinates.parse(value, this.default);
  50723. }
  50724. /**
  50725. * Validate the default values in a schema to match their type.
  50726. *
  50727. * @param {string} type - Property type name.
  50728. * @param defaultVal - Property type default value.
  50729. * @returns {boolean} Whether default value is accurate given the type.
  50730. */
  50731. function isValidDefaultValue (type, defaultVal) {
  50732. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  50733. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  50734. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  50735. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  50736. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  50737. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  50738. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  50739. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  50740. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  50741. if (type === 'selector' && typeof defaultVal !== 'string' &&
  50742. defaultVal !== null) { return false; }
  50743. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  50744. defaultVal !== null) { return false; }
  50745. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  50746. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  50747. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  50748. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  50749. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  50750. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  50751. return true;
  50752. }
  50753. module.exports.isValidDefaultValue = isValidDefaultValue;
  50754. /**
  50755. * Checks if default coordinates are valid.
  50756. *
  50757. * @param possibleCoordinates
  50758. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  50759. * @returns {boolean} Whether coordinates are parsed correctly.
  50760. */
  50761. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  50762. if (possibleCoordinates === null) { return true; }
  50763. if (typeof possibleCoordinates !== 'object') { return false; }
  50764. if (Object.keys(possibleCoordinates).length !== dimensions) {
  50765. return false;
  50766. } else {
  50767. var x = possibleCoordinates.x;
  50768. var y = possibleCoordinates.y;
  50769. var z = possibleCoordinates.z;
  50770. var w = possibleCoordinates.w;
  50771. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  50772. if (dimensions > 2 && typeof z !== 'number') { return false; }
  50773. if (dimensions > 3 && typeof w !== 'number') { return false; }
  50774. }
  50775. return true;
  50776. }
  50777. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  50778. },{"../utils/coordinates":171,"debug":8}],106:[function(_dereq_,module,exports){
  50779. /* global Promise, screen */
  50780. var initMetaTags = _dereq_('./metaTags').inject;
  50781. var initWakelock = _dereq_('./wakelock');
  50782. var loadingScreen = _dereq_('./loadingScreen');
  50783. var re = _dereq_('../a-register-element');
  50784. var scenes = _dereq_('./scenes');
  50785. var systems = _dereq_('../system').systems;
  50786. var THREE = _dereq_('../../lib/three');
  50787. var utils = _dereq_('../../utils/');
  50788. // Require after.
  50789. var AEntity = _dereq_('../a-entity');
  50790. var ANode = _dereq_('../a-node');
  50791. var initPostMessageAPI = _dereq_('./postMessage');
  50792. var bind = utils.bind;
  50793. var isIOS = utils.device.isIOS();
  50794. var isMobile = utils.device.isMobile();
  50795. var isWebXRAvailable = utils.device.isWebXRAvailable;
  50796. var registerElement = re.registerElement;
  50797. var warn = utils.debug('core:a-scene:warn');
  50798. /**
  50799. * Scene element, holds all entities.
  50800. *
  50801. * @member {array} behaviors - Component instances that have registered themselves to be
  50802. updated on every tick.
  50803. * @member {object} camera - three.js Camera object.
  50804. * @member {object} canvas
  50805. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  50806. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  50807. * @member {object} object3D - Root three.js Scene object.
  50808. * @member {object} renderer
  50809. * @member {bool} renderStarted
  50810. * @member {object} systems - Registered instantiated systems.
  50811. * @member {number} time
  50812. */
  50813. module.exports.AScene = registerElement('a-scene', {
  50814. prototype: Object.create(AEntity.prototype, {
  50815. createdCallback: {
  50816. value: function () {
  50817. this.clock = new THREE.Clock();
  50818. this.isIOS = isIOS;
  50819. this.isMobile = isMobile;
  50820. this.hasWebXR = isWebXRAvailable;
  50821. this.isScene = true;
  50822. this.object3D = new THREE.Scene();
  50823. var self = this;
  50824. this.object3D.onAfterRender = function (renderer, scene, camera) {
  50825. // THREE may swap the camera used for the rendering if in VR, so we pass it to tock
  50826. if (self.isPlaying) { self.tock(self.time, self.delta, camera); }
  50827. };
  50828. this.render = bind(this.render, this);
  50829. this.systems = {};
  50830. this.systemNames = [];
  50831. this.time = this.delta = 0;
  50832. this.behaviors = {tick: [], tock: []};
  50833. this.hasLoaded = false;
  50834. this.isPlaying = false;
  50835. this.originalHTML = this.innerHTML;
  50836. // Default components.
  50837. this.setAttribute('inspector', '');
  50838. this.setAttribute('keyboard-shortcuts', '');
  50839. this.setAttribute('screenshot', '');
  50840. this.setAttribute('vr-mode-ui', '');
  50841. }
  50842. },
  50843. addFullScreenStyles: {
  50844. value: function () {
  50845. document.documentElement.classList.add('a-fullscreen');
  50846. }
  50847. },
  50848. removeFullScreenStyles: {
  50849. value: function () {
  50850. document.documentElement.classList.remove('a-fullscreen');
  50851. }
  50852. },
  50853. attachedCallback: {
  50854. value: function () {
  50855. var self = this;
  50856. // Renderer initialization
  50857. setupCanvas(this);
  50858. this.setupRenderer();
  50859. this.resize();
  50860. this.addFullScreenStyles();
  50861. initPostMessageAPI(this);
  50862. initMetaTags(this);
  50863. initWakelock(this);
  50864. // Handler to exit VR (e.g., Oculus Browser back button).
  50865. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  50866. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50867. // Bind functions.
  50868. this.enterVRBound = function () { self.enterVR(); };
  50869. this.exitVRBound = function () { self.exitVR(); };
  50870. this.exitVRTrueBound = function () { self.exitVR(true); };
  50871. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  50872. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  50873. if (!isWebXRAvailable) {
  50874. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  50875. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  50876. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  50877. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50878. // Register for mouse restricted events while in VR
  50879. // (e.g. mouse no longer available on desktop 2D view)
  50880. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50881. // Register for mouse unrestricted events while in VR
  50882. // (e.g. mouse once again available on desktop 2D view)
  50883. window.addEventListener('vrdisplaypointerunrestricted',
  50884. this.pointerUnrestrictedBound);
  50885. }
  50886. // Camera set up by camera system.
  50887. this.addEventListener('cameraready', function () {
  50888. self.attachedCallbackPostCamera();
  50889. });
  50890. this.initSystems();
  50891. }
  50892. },
  50893. attachedCallbackPostCamera: {
  50894. value: function () {
  50895. var resize;
  50896. var self = this;
  50897. resize = bind(this.resize, this);
  50898. window.addEventListener('load', resize);
  50899. window.addEventListener('resize', function () {
  50900. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  50901. // where the window does not contain the correct viewport size
  50902. // after an orientation change. The window size is correct if the operation
  50903. // is postponed a few milliseconds.
  50904. // self.resize can be called directly once the bug above is fixed.
  50905. if (self.isIOS) {
  50906. setTimeout(resize, 100);
  50907. } else {
  50908. resize();
  50909. }
  50910. });
  50911. this.play();
  50912. // Add to scene index.
  50913. scenes.push(this);
  50914. },
  50915. writable: window.debug
  50916. },
  50917. /**
  50918. * Initialize all systems.
  50919. */
  50920. initSystems: {
  50921. value: function () {
  50922. var name;
  50923. // Initialize camera system first.
  50924. this.initSystem('camera');
  50925. for (name in systems) {
  50926. if (name === 'camera') { continue; }
  50927. this.initSystem(name);
  50928. }
  50929. }
  50930. },
  50931. /**
  50932. * Initialize a system.
  50933. */
  50934. initSystem: {
  50935. value: function (name) {
  50936. if (this.systems[name]) { return; }
  50937. this.systems[name] = new systems[name](this);
  50938. this.systemNames.push(name);
  50939. }
  50940. },
  50941. /**
  50942. * Shut down scene on detach.
  50943. */
  50944. detachedCallback: {
  50945. value: function () {
  50946. // Remove from scene index.
  50947. var sceneIndex = scenes.indexOf(this);
  50948. scenes.splice(sceneIndex, 1);
  50949. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  50950. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  50951. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  50952. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  50953. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  50954. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  50955. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  50956. }
  50957. },
  50958. /**
  50959. * Add ticks and tocks.
  50960. *
  50961. * @param {object} behavior - A component.
  50962. */
  50963. addBehavior: {
  50964. value: function (behavior) {
  50965. var behaviorArr;
  50966. var behaviors = this.behaviors;
  50967. var behaviorType;
  50968. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  50969. for (behaviorType in behaviors) {
  50970. if (!behavior[behaviorType]) { continue; }
  50971. behaviorArr = this.behaviors[behaviorType];
  50972. if (behaviorArr.indexOf(behavior) === -1) {
  50973. behaviorArr.push(behavior);
  50974. }
  50975. }
  50976. }
  50977. },
  50978. /**
  50979. * For tests.
  50980. */
  50981. getPointerLockElement: {
  50982. value: function () {
  50983. return document.pointerLockElement;
  50984. },
  50985. writable: window.debug
  50986. },
  50987. /**
  50988. * For tests.
  50989. */
  50990. checkHeadsetConnected: {
  50991. value: utils.device.checkHeadsetConnected,
  50992. writable: window.debug
  50993. },
  50994. /**
  50995. * Call `requestPresent` if WebVR or WebVR polyfill.
  50996. * Call `requestFullscreen` on desktop.
  50997. * Handle events, states, fullscreen styles.
  50998. *
  50999. * @returns {Promise}
  51000. */
  51001. enterVR: {
  51002. value: function () {
  51003. var self = this;
  51004. var vrDisplay;
  51005. var vrManager = self.renderer.vr;
  51006. // Don't enter VR if already in VR.
  51007. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  51008. // Has VR.
  51009. if (this.checkHeadsetConnected() || this.isMobile) {
  51010. vrDisplay = utils.device.getVRDisplay();
  51011. vrManager.enabled = true;
  51012. vrManager.setDevice(vrDisplay);
  51013. if (this.hasWebXR) {
  51014. // XR API.
  51015. if (this.xrSession) {
  51016. this.xrSession.removeEventListener('end', this.exitVRBound);
  51017. }
  51018. vrDisplay.requestSession({
  51019. immersive: true,
  51020. exclusive: true
  51021. }).then(function requestSuccess (xrSession) {
  51022. self.xrSession = xrSession;
  51023. vrManager.setSession(xrSession);
  51024. xrSession.addEventListener('end', self.exitVRBound);
  51025. xrSession.requestFrameOfReference('stage').then(function (frameOfReference) {
  51026. self.frameOfReference = frameOfReference;
  51027. });
  51028. enterVRSuccess();
  51029. });
  51030. } else {
  51031. if (vrDisplay.isPresenting &&
  51032. !window.hasNativeWebVRImplementation) {
  51033. enterVRSuccess();
  51034. return Promise.resolve();
  51035. }
  51036. var rendererSystem = this.getAttribute('renderer');
  51037. var presentationAttributes = {
  51038. highRefreshRate: rendererSystem.highRefreshRate,
  51039. foveationLevel: rendererSystem.foveationLevel
  51040. };
  51041. return vrDisplay.requestPresent([{
  51042. source: this.canvas,
  51043. attributes: presentationAttributes
  51044. }]).then(enterVRSuccess, enterVRFailure);
  51045. }
  51046. return Promise.resolve();
  51047. }
  51048. // No VR.
  51049. enterVRSuccess();
  51050. return Promise.resolve();
  51051. // Callback that happens on enter VR success or enter fullscreen (any API).
  51052. function enterVRSuccess () {
  51053. self.addState('vr-mode');
  51054. self.emit('enter-vr', {target: self});
  51055. // Lock to landscape orientation on mobile.
  51056. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  51057. screen.orientation.lock('landscape');
  51058. }
  51059. self.addFullScreenStyles();
  51060. // On mobile, the polyfill handles fullscreen.
  51061. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  51062. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  51063. // connected.
  51064. if (!self.isMobile && !self.checkHeadsetConnected()) {
  51065. requestFullscreen(self.canvas);
  51066. }
  51067. self.renderer.setAnimationLoop(self.render);
  51068. self.resize();
  51069. }
  51070. function enterVRFailure (err) {
  51071. if (err && err.message) {
  51072. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  51073. } else {
  51074. throw new Error('Failed to enter VR mode (`requestPresent`).');
  51075. }
  51076. }
  51077. },
  51078. writable: true
  51079. },
  51080. /**
  51081. * Call `exitPresent` if WebVR / WebXR or WebVR polyfill.
  51082. * Handle events, states, fullscreen styles.
  51083. *
  51084. * @returns {Promise}
  51085. */
  51086. exitVR: {
  51087. value: function () {
  51088. var self = this;
  51089. var vrDisplay;
  51090. var vrManager = this.renderer.vr;
  51091. // Don't exit VR if not in VR.
  51092. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  51093. // Handle exiting VR if not yet already and in a headset or polyfill.
  51094. if (this.checkHeadsetConnected() || this.isMobile) {
  51095. vrManager.enabled = false;
  51096. vrDisplay = utils.device.getVRDisplay();
  51097. if (this.hasWebXR) {
  51098. this.xrSession.removeEventListener('end', this.exitVRBound);
  51099. this.xrSession.end();
  51100. vrManager.setSession(null);
  51101. } else {
  51102. if (vrDisplay.isPresenting) {
  51103. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  51104. }
  51105. }
  51106. } else {
  51107. exitFullscreen();
  51108. }
  51109. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  51110. exitVRSuccess();
  51111. return Promise.resolve();
  51112. function exitVRSuccess () {
  51113. self.removeState('vr-mode');
  51114. // Lock to landscape orientation on mobile.
  51115. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  51116. screen.orientation.unlock();
  51117. }
  51118. // Exiting VR in embedded mode, no longer need fullscreen styles.
  51119. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  51120. self.resize();
  51121. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(self.canvas); }
  51122. self.emit('exit-vr', {target: self});
  51123. }
  51124. function exitVRFailure (err) {
  51125. if (err && err.message) {
  51126. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  51127. } else {
  51128. throw new Error('Failed to exit VR mode (`exitPresent`).');
  51129. }
  51130. }
  51131. },
  51132. writable: true
  51133. },
  51134. pointerRestricted: {
  51135. value: function () {
  51136. if (this.canvas) {
  51137. var pointerLockElement = this.getPointerLockElement();
  51138. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  51139. // Recreate pointer lock on the canvas, if taken on another element.
  51140. document.exitPointerLock();
  51141. }
  51142. if (this.canvas.requestPointerLock) {
  51143. this.canvas.requestPointerLock();
  51144. }
  51145. }
  51146. }
  51147. },
  51148. pointerUnrestricted: {
  51149. value: function () {
  51150. var pointerLockElement = this.getPointerLockElement();
  51151. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  51152. document.exitPointerLock();
  51153. }
  51154. }
  51155. },
  51156. /**
  51157. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  51158. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  51159. */
  51160. onVRPresentChange: {
  51161. value: function (evt) {
  51162. // Polyfill places display inside the detail property
  51163. var display = evt.display || evt.detail.display;
  51164. // Entering VR.
  51165. if (display.isPresenting) {
  51166. this.enterVR();
  51167. return;
  51168. }
  51169. // Exiting VR.
  51170. this.exitVR();
  51171. }
  51172. },
  51173. /**
  51174. * Wraps Entity.getAttribute to take into account for systems.
  51175. * If system exists, then return system data rather than possible component data.
  51176. */
  51177. getAttribute: {
  51178. value: function (attr) {
  51179. var system = this.systems[attr];
  51180. if (system) { return system.data; }
  51181. return AEntity.prototype.getAttribute.call(this, attr);
  51182. }
  51183. },
  51184. /**
  51185. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  51186. * what `getAttribute` is now. Now legacy code.
  51187. */
  51188. getComputedAttribute: {
  51189. value: function (attr) {
  51190. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  51191. this.getAttribute(attr);
  51192. }
  51193. },
  51194. /**
  51195. * Wraps Entity.getDOMAttribute to take into account for systems.
  51196. * If system exists, then return system data rather than possible component data.
  51197. */
  51198. getDOMAttribute: {
  51199. value: function (attr) {
  51200. var system = this.systems[attr];
  51201. if (system) { return system.data; }
  51202. return AEntity.prototype.getDOMAttribute.call(this, attr);
  51203. }
  51204. },
  51205. /**
  51206. * Wrap Entity.setAttribute to take into account for systems.
  51207. * If system exists, then skip component initialization checks and do a normal
  51208. * setAttribute.
  51209. */
  51210. setAttribute: {
  51211. value: function (attr, value, componentPropValue) {
  51212. var system = this.systems[attr];
  51213. if (system) {
  51214. ANode.prototype.setAttribute.call(this, attr, value);
  51215. system.updateProperties(value);
  51216. return;
  51217. }
  51218. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  51219. }
  51220. },
  51221. /**
  51222. * @param {object} behavior - A component.
  51223. */
  51224. removeBehavior: {
  51225. value: function (behavior) {
  51226. var behaviorArr;
  51227. var behaviorType;
  51228. var behaviors = this.behaviors;
  51229. var index;
  51230. // Check if behavior has tick and/or tock and remove the behavior from the appropriate
  51231. // array.
  51232. for (behaviorType in behaviors) {
  51233. if (!behavior[behaviorType]) { continue; }
  51234. behaviorArr = this.behaviors[behaviorType];
  51235. index = behaviorArr.indexOf(behavior);
  51236. if (index !== -1) { behaviorArr.splice(index, 1); }
  51237. }
  51238. }
  51239. },
  51240. resize: {
  51241. value: function () {
  51242. var camera = this.camera;
  51243. var canvas = this.canvas;
  51244. var embedded;
  51245. var isVRPresenting;
  51246. var size;
  51247. var vrDevice;
  51248. vrDevice = this.renderer.vr.getDevice();
  51249. isVRPresenting = this.renderer.vr.enabled && vrDevice && vrDevice.isPresenting;
  51250. // Do not update renderer, if a camera or a canvas have not been injected.
  51251. // In VR mode, three handles canvas resize based on the dimensions returned by
  51252. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  51253. // the window size, therefore should not be overwritten with the window's width and
  51254. // height, // except when in fullscreen mode.
  51255. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) {
  51256. return;
  51257. }
  51258. // Update camera.
  51259. embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  51260. size = getCanvasSize(canvas, embedded, this.maxCanvasSize, this.is('vr-mode'));
  51261. camera.aspect = size.width / size.height;
  51262. camera.updateProjectionMatrix();
  51263. // Notify renderer of size change.
  51264. this.renderer.setSize(size.width, size.height, false);
  51265. this.emit('rendererresize', null, false);
  51266. },
  51267. writable: true
  51268. },
  51269. setupRenderer: {
  51270. value: function () {
  51271. var self = this;
  51272. var renderer;
  51273. var rendererAttr;
  51274. var rendererAttrString;
  51275. var rendererConfig;
  51276. rendererConfig = {
  51277. alpha: true,
  51278. antialias: !isMobile,
  51279. canvas: this.canvas,
  51280. logarithmicDepthBuffer: false
  51281. };
  51282. this.maxCanvasSize = {height: 1920, width: 1920};
  51283. if (this.hasAttribute('renderer')) {
  51284. rendererAttrString = this.getAttribute('renderer');
  51285. rendererAttr = utils.styleParser.parse(rendererAttrString);
  51286. if (rendererAttr.precision) {
  51287. rendererConfig.precision = rendererAttr.precision + 'p';
  51288. }
  51289. if (rendererAttr.antialias && rendererAttr.antialias !== 'auto') {
  51290. rendererConfig.antialias = rendererAttr.antialias === 'true';
  51291. }
  51292. if (rendererAttr.logarithmicDepthBuffer && rendererAttr.logarithmicDepthBuffer !== 'auto') {
  51293. rendererConfig.logarithmicDepthBuffer = rendererAttr.logarithmicDepthBuffer === 'true';
  51294. }
  51295. if (rendererAttr.alpha) {
  51296. rendererConfig.alpha = rendererAttr.alpha === 'true';
  51297. }
  51298. this.maxCanvasSize = {
  51299. width: rendererAttr.maxCanvasWidth
  51300. ? parseInt(rendererAttr.maxCanvasWidth)
  51301. : this.maxCanvasSize.width,
  51302. height: rendererAttr.maxCanvasHeight
  51303. ? parseInt(rendererAttr.maxCanvasHeight)
  51304. : this.maxCanvasSize.height
  51305. };
  51306. }
  51307. renderer = this.renderer = new THREE.WebGLRenderer(rendererConfig);
  51308. renderer.setPixelRatio(window.devicePixelRatio);
  51309. renderer.sortObjects = false;
  51310. if (this.camera) { renderer.vr.setPoseTarget(this.camera.el.object3D); }
  51311. this.addEventListener('camera-set-active', function () {
  51312. renderer.vr.setPoseTarget(self.camera.el.object3D);
  51313. });
  51314. loadingScreen.setup(this, getCanvasSize);
  51315. },
  51316. writable: window.debug
  51317. },
  51318. /**
  51319. * Handler attached to elements to help scene know when to kick off.
  51320. * Scene waits for all entities to load.
  51321. */
  51322. play: {
  51323. value: function () {
  51324. var self = this;
  51325. var sceneEl = this;
  51326. if (this.renderStarted) {
  51327. AEntity.prototype.play.call(this);
  51328. return;
  51329. }
  51330. this.addEventListener('loaded', function () {
  51331. var renderer = this.renderer;
  51332. var vrDisplay;
  51333. var vrManager = this.renderer.vr;
  51334. AEntity.prototype.play.call(this); // .play() *before* render.
  51335. if (sceneEl.renderStarted) { return; }
  51336. sceneEl.resize();
  51337. // Kick off render loop.
  51338. if (sceneEl.renderer) {
  51339. if (window.performance) { window.performance.mark('render-started'); }
  51340. loadingScreen.remove();
  51341. vrDisplay = utils.device.getVRDisplay();
  51342. if (vrDisplay && vrDisplay.isPresenting) {
  51343. vrManager.setDevice(vrDisplay);
  51344. vrManager.enabled = true;
  51345. sceneEl.enterVR();
  51346. }
  51347. renderer.setAnimationLoop(this.render);
  51348. sceneEl.renderStarted = true;
  51349. sceneEl.emit('renderstart');
  51350. }
  51351. });
  51352. // setTimeout to wait for all nodes to attach and run their callbacks.
  51353. setTimeout(function () {
  51354. AEntity.prototype.load.call(self);
  51355. });
  51356. }
  51357. },
  51358. /**
  51359. * Wrap `updateComponent` to not initialize the component if the component has a system
  51360. * (aframevr/aframe#2365).
  51361. */
  51362. updateComponent: {
  51363. value: function (componentName) {
  51364. if (componentName in systems) { return; }
  51365. AEntity.prototype.updateComponent.apply(this, arguments);
  51366. }
  51367. },
  51368. /**
  51369. * Behavior-updater meant to be called from scene render.
  51370. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  51371. * needing to render.
  51372. */
  51373. tick: {
  51374. value: function (time, timeDelta) {
  51375. var i;
  51376. var systems = this.systems;
  51377. // Components.
  51378. for (i = 0; i < this.behaviors.tick.length; i++) {
  51379. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  51380. this.behaviors.tick[i].tick(time, timeDelta);
  51381. }
  51382. // Systems.
  51383. for (i = 0; i < this.systemNames.length; i++) {
  51384. if (!systems[this.systemNames[i]].tick) { continue; }
  51385. systems[this.systemNames[i]].tick(time, timeDelta);
  51386. }
  51387. }
  51388. },
  51389. /**
  51390. * Behavior-updater meant to be called after scene render for post processing purposes.
  51391. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  51392. * needing to render.
  51393. */
  51394. tock: {
  51395. value: function (time, timeDelta, camera) {
  51396. var i;
  51397. var systems = this.systems;
  51398. // Components.
  51399. for (i = 0; i < this.behaviors.tock.length; i++) {
  51400. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  51401. this.behaviors.tock[i].tock(time, timeDelta, camera);
  51402. }
  51403. // Systems.
  51404. for (i = 0; i < this.systemNames.length; i++) {
  51405. if (!systems[this.systemNames[i]].tock) { continue; }
  51406. systems[this.systemNames[i]].tock(time, timeDelta, camera);
  51407. }
  51408. }
  51409. },
  51410. /**
  51411. * The render loop.
  51412. *
  51413. * Updates animations.
  51414. * Updates behaviors.
  51415. * Renders with request animation frame.
  51416. */
  51417. render: {
  51418. value: function (time, frame) {
  51419. var renderer = this.renderer;
  51420. this.frame = frame;
  51421. this.delta = this.clock.getDelta() * 1000;
  51422. this.time = this.clock.elapsedTime * 1000;
  51423. if (this.isPlaying) { this.tick(this.time, this.delta); }
  51424. renderer.render(this.object3D, this.camera);
  51425. },
  51426. writable: true
  51427. }
  51428. })
  51429. });
  51430. /**
  51431. * Return the canvas size where the scene will be rendered.
  51432. * Will be always the window size except when the scene is embedded.
  51433. * The parent size (less than max size) will be returned in that case.
  51434. *
  51435. * @param {object} canvasEl - the canvas element
  51436. * @param {boolean} embedded - Is the scene embedded?
  51437. * @param {object} max - Max size parameters
  51438. * @param {boolean} isVR - If in VR
  51439. */
  51440. function getCanvasSize (canvasEl, embedded, maxSize, isVR) {
  51441. if (embedded) {
  51442. return {
  51443. height: canvasEl.parentElement.offsetHeight,
  51444. width: canvasEl.parentElement.offsetWidth
  51445. };
  51446. }
  51447. return getMaxSize(maxSize, isVR);
  51448. }
  51449. /**
  51450. * Return the canvas size. Will be the window size unless that size is greater than the
  51451. * maximum size (1920x1920 by default). The constrained size will be returned in that case,
  51452. * maintaining aspect ratio
  51453. *
  51454. * @param {object} maxSize - Max size parameters (width and height).
  51455. * @param {boolean} isVR - If in VR.
  51456. * @returns {object} Width and height.
  51457. */
  51458. function getMaxSize (maxSize, isVR) {
  51459. var aspectRatio;
  51460. var size;
  51461. var pixelRatio = window.devicePixelRatio;
  51462. size = {height: document.body.offsetHeight, width: document.body.offsetWidth};
  51463. if (!maxSize || isVR || (maxSize.width === -1 && maxSize.height === -1)) {
  51464. return size;
  51465. }
  51466. if (size.width * pixelRatio < maxSize.width &&
  51467. size.height * pixelRatio < maxSize.height) {
  51468. return size;
  51469. }
  51470. aspectRatio = size.width / size.height;
  51471. if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
  51472. size.width = Math.round(maxSize.width / pixelRatio);
  51473. size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
  51474. }
  51475. if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
  51476. size.height = Math.round(maxSize.height / pixelRatio);
  51477. size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
  51478. }
  51479. return size;
  51480. }
  51481. function requestFullscreen (canvas) {
  51482. var requestFullscreen =
  51483. canvas.requestFullscreen ||
  51484. canvas.webkitRequestFullscreen ||
  51485. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  51486. canvas.msRequestFullscreen;
  51487. // Hide navigation buttons on Android.
  51488. requestFullscreen.apply(canvas, [{navigationUI: 'hide'}]);
  51489. }
  51490. function exitFullscreen () {
  51491. var fullscreenEl =
  51492. document.fullscreenElement ||
  51493. document.webkitFullscreenElement ||
  51494. document.mozFullScreenElement;
  51495. if (!fullscreenEl) { return; }
  51496. if (document.exitFullscreen) {
  51497. document.exitFullscreen();
  51498. } else if (document.mozCancelFullScreen) {
  51499. document.mozCancelFullScreen();
  51500. } else if (document.webkitExitFullscreen) {
  51501. document.webkitExitFullscreen();
  51502. }
  51503. }
  51504. function setupCanvas (sceneEl) {
  51505. var canvasEl;
  51506. canvasEl = document.createElement('canvas');
  51507. canvasEl.classList.add('a-canvas');
  51508. // Mark canvas as provided/injected by A-Frame.
  51509. canvasEl.dataset.aframeCanvas = true;
  51510. sceneEl.appendChild(canvasEl);
  51511. document.addEventListener('fullscreenchange', onFullScreenChange);
  51512. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  51513. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  51514. // Prevent overscroll on mobile.
  51515. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  51516. // Set canvas on scene.
  51517. sceneEl.canvas = canvasEl;
  51518. sceneEl.emit('render-target-loaded', {target: canvasEl});
  51519. // For unknown reasons a synchronous resize does not work on desktop when
  51520. // entering/exiting fullscreen.
  51521. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  51522. function onFullScreenChange () {
  51523. var fullscreenEl =
  51524. document.fullscreenElement ||
  51525. document.mozFullScreenElement ||
  51526. document.webkitFullscreenElement;
  51527. // No fullscren element === exit fullscreen
  51528. if (!fullscreenEl) { sceneEl.exitVR(); }
  51529. document.activeElement.blur();
  51530. document.body.focus();
  51531. }
  51532. }
  51533. module.exports.setupCanvas = setupCanvas; // For testing.
  51534. },{"../../lib/three":151,"../../utils/":176,"../a-entity":99,"../a-node":101,"../a-register-element":102,"../system":114,"./loadingScreen":107,"./metaTags":108,"./postMessage":109,"./scenes":110,"./wakelock":111}],107:[function(_dereq_,module,exports){
  51535. /* global THREE */
  51536. var utils = _dereq_('../../utils/');
  51537. var styleParser = utils.styleParser;
  51538. var sceneEl;
  51539. var titleEl;
  51540. var getSceneCanvasSize;
  51541. var ATTR_NAME = 'loading-screen';
  51542. var LOADER_TITLE_CLASS = 'a-loader-title';
  51543. module.exports.setup = function setup (el, getCanvasSize) {
  51544. sceneEl = el;
  51545. getSceneCanvasSize = getCanvasSize;
  51546. var loaderAttribute = sceneEl.hasAttribute(ATTR_NAME) ? styleParser.parse(sceneEl.getAttribute(ATTR_NAME)) : undefined;
  51547. var dotsColor = loaderAttribute && loaderAttribute.dotsColor || 'white';
  51548. var backgroundColor = loaderAttribute && loaderAttribute.backgroundColor || '#24CAFF';
  51549. var loaderEnabled = loaderAttribute === undefined || loaderAttribute.enabled === true || loaderAttribute.enabled === undefined; // true default
  51550. var loaderScene;
  51551. var sphereGeometry;
  51552. var sphereMaterial;
  51553. var sphereMesh1;
  51554. var sphereMesh2;
  51555. var sphereMesh3;
  51556. var camera;
  51557. var clock;
  51558. var time;
  51559. var render;
  51560. if (!loaderEnabled) { return; }
  51561. // Setup Scene.
  51562. loaderScene = new THREE.Scene();
  51563. sphereGeometry = new THREE.SphereGeometry(0.20, 36, 18, 0, 2 * Math.PI, 0, Math.PI);
  51564. sphereMaterial = new THREE.MeshBasicMaterial({color: dotsColor});
  51565. sphereMesh1 = new THREE.Mesh(sphereGeometry, sphereMaterial);
  51566. sphereMesh2 = sphereMesh1.clone();
  51567. sphereMesh3 = sphereMesh1.clone();
  51568. camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.0005, 10000);
  51569. clock = new THREE.Clock();
  51570. time = 0;
  51571. render = function () {
  51572. sceneEl.renderer.render(loaderScene, camera);
  51573. time = clock.getElapsedTime() % 4;
  51574. sphereMesh1.visible = time >= 1;
  51575. sphereMesh2.visible = time >= 2;
  51576. sphereMesh3.visible = time >= 3;
  51577. };
  51578. loaderScene.background = new THREE.Color(backgroundColor);
  51579. loaderScene.add(camera);
  51580. sphereMesh1.position.set(-1, 0, -15);
  51581. sphereMesh2.position.set(0, 0, -15);
  51582. sphereMesh3.position.set(1, 0, -15);
  51583. camera.add(sphereMesh1);
  51584. camera.add(sphereMesh2);
  51585. camera.add(sphereMesh3);
  51586. setupTitle();
  51587. // Delay 200ms to avoid loader flashes.
  51588. setTimeout(function () {
  51589. if (sceneEl.hasLoaded) { return; }
  51590. resize(camera);
  51591. titleEl.style.display = 'block';
  51592. window.addEventListener('resize', function () { resize(camera); });
  51593. sceneEl.renderer.setAnimationLoop(render);
  51594. }, 200);
  51595. };
  51596. module.exports.remove = function remove () {
  51597. window.removeEventListener('resize', resize);
  51598. if (!titleEl) { return; }
  51599. // Hide title.
  51600. titleEl.style.display = 'none';
  51601. };
  51602. function resize (camera) {
  51603. var size = getSceneCanvasSize(sceneEl.canvas, false, sceneEl.maxCanvasSize, sceneEl.is('vr-mode'));
  51604. camera.aspect = size.width / size.height;
  51605. camera.updateProjectionMatrix();
  51606. // Notify renderer of size change.
  51607. sceneEl.renderer.setSize(size.width, size.height, false);
  51608. }
  51609. function setupTitle () {
  51610. titleEl = document.createElement('div');
  51611. titleEl.className = LOADER_TITLE_CLASS;
  51612. titleEl.innerHTML = document.title;
  51613. titleEl.style.display = 'none';
  51614. sceneEl.appendChild(titleEl);
  51615. }
  51616. },{"../../utils/":176}],108:[function(_dereq_,module,exports){
  51617. var constants = _dereq_('../../constants/');
  51618. var extend = _dereq_('../../utils').extend;
  51619. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  51620. 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'}),
  51621. // W3C-standardised meta tags.
  51622. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  51623. Meta({name: 'theme-color', content: 'black'})
  51624. ];
  51625. var MOBILE_IOS_HEAD_TAGS = [
  51626. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  51627. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  51628. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  51629. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  51630. ];
  51631. function Meta (attrs) {
  51632. return {
  51633. tagName: 'meta',
  51634. attributes: attrs,
  51635. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  51636. };
  51637. }
  51638. function Link (attrs) {
  51639. return {
  51640. tagName: 'link',
  51641. attributes: attrs,
  51642. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  51643. };
  51644. }
  51645. /**
  51646. * Injects the necessary metatags in the document for mobile support:
  51647. * 1. Prevent the user to zoom in the document.
  51648. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  51649. * values and the canvas is properly scaled.
  51650. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  51651. * iOS.
  51652. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  51653. *
  51654. * @param {object} scene - Scene element
  51655. * @returns {Array}
  51656. */
  51657. module.exports.inject = function injectHeadTags (scene) {
  51658. var headEl = document.head;
  51659. var headScriptEl = headEl.querySelector('script');
  51660. var tag;
  51661. var headTags = [];
  51662. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  51663. if (scene.isIOS) {
  51664. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  51665. }
  51666. return headTags;
  51667. function createAndInjectTag (tagObj) {
  51668. if (!tagObj || tagObj.exists()) { return; }
  51669. tag = createTag(tagObj);
  51670. if (!tag) { return; }
  51671. if (headScriptEl) {
  51672. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  51673. } else {
  51674. headEl.appendChild(tag);
  51675. }
  51676. headTags.push(tag);
  51677. }
  51678. };
  51679. function createTag (tagObj) {
  51680. if (!tagObj || !tagObj.tagName) { return; }
  51681. var meta = document.createElement(tagObj.tagName);
  51682. meta.setAttribute(constants.AFRAME_INJECTED, '');
  51683. return extend(meta, tagObj.attributes);
  51684. }
  51685. },{"../../constants/":95,"../../utils":176}],109:[function(_dereq_,module,exports){
  51686. var bind = _dereq_('../../utils/bind');
  51687. var isIframed = _dereq_('../../utils/').isIframed;
  51688. /**
  51689. * Provides a post message API for scenes contained
  51690. * in an iframe.
  51691. */
  51692. module.exports = function initPostMessageAPI (scene) {
  51693. // Handles fullscreen behavior when inside an iframe.
  51694. if (!isIframed()) { return; }
  51695. // postMessage API handler
  51696. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  51697. };
  51698. function postMessageAPIHandler (event) {
  51699. var scene = this;
  51700. if (!event.data) { return; }
  51701. switch (event.data.type) {
  51702. case 'vr': {
  51703. switch (event.data.data) {
  51704. case 'enter':
  51705. scene.enterVR();
  51706. break;
  51707. case 'exit':
  51708. scene.exitVR();
  51709. break;
  51710. }
  51711. }
  51712. }
  51713. }
  51714. },{"../../utils/":176,"../../utils/bind":170}],110:[function(_dereq_,module,exports){
  51715. /*
  51716. Scene index for keeping track of created scenes.
  51717. */
  51718. module.exports = [];
  51719. },{}],111:[function(_dereq_,module,exports){
  51720. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  51721. module.exports = function initWakelock (scene) {
  51722. if (!scene.isMobile) { return; }
  51723. var wakelock = scene.wakelock = new Wakelock();
  51724. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  51725. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  51726. };
  51727. },{"../../../vendor/wakelock/wakelock":189}],112:[function(_dereq_,module,exports){
  51728. var utils = _dereq_('../utils/');
  51729. var PropertyTypes = _dereq_('./propertyTypes');
  51730. var debug = utils.debug;
  51731. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  51732. var propertyTypes = PropertyTypes.propertyTypes;
  51733. var warn = debug('core:schema:warn');
  51734. /**
  51735. * A schema is classified as a schema for a single property if:
  51736. * - `type` is defined on the schema as a string.
  51737. * - OR `default` is defined on the schema, as a reserved keyword.
  51738. * - OR schema is empty.
  51739. */
  51740. function isSingleProperty (schema) {
  51741. if ('type' in schema) {
  51742. return typeof schema.type === 'string';
  51743. }
  51744. return 'default' in schema;
  51745. }
  51746. module.exports.isSingleProperty = isSingleProperty;
  51747. /**
  51748. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  51749. *
  51750. * @param {object} schema
  51751. * @param {string} componentName
  51752. * @returns {object} Schema.
  51753. */
  51754. module.exports.process = function (schema, componentName) {
  51755. var propName;
  51756. // For single property schema, run processPropDefinition over the whole schema.
  51757. if (isSingleProperty(schema)) {
  51758. return processPropertyDefinition(schema, componentName);
  51759. }
  51760. // For multi-property schema, run processPropDefinition over each property definition.
  51761. for (propName in schema) {
  51762. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  51763. }
  51764. return schema;
  51765. };
  51766. /**
  51767. * Inject default value, parser, stringifier for single property.
  51768. *
  51769. * @param {object} propDefinition
  51770. * @param {string} componentName
  51771. */
  51772. function processPropertyDefinition (propDefinition, componentName) {
  51773. var defaultVal = propDefinition.default;
  51774. var isCustomType;
  51775. var propType;
  51776. var typeName = propDefinition.type;
  51777. // Type inference.
  51778. if (!propDefinition.type) {
  51779. if (defaultVal !== undefined &&
  51780. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  51781. // Type inference.
  51782. typeName = typeof defaultVal;
  51783. } else if (Array.isArray(defaultVal)) {
  51784. typeName = 'array';
  51785. } else {
  51786. // Fall back to string.
  51787. typeName = 'string';
  51788. }
  51789. } else if (propDefinition.type === 'bool') {
  51790. typeName = 'boolean';
  51791. } else if (propDefinition.type === 'float') {
  51792. typeName = 'number';
  51793. }
  51794. propType = propertyTypes[typeName];
  51795. if (!propType) {
  51796. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  51797. }
  51798. // Fill in parse and stringify using property types.
  51799. isCustomType = !!propDefinition.parse;
  51800. propDefinition.parse = propDefinition.parse || propType.parse;
  51801. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  51802. // Fill in type name.
  51803. propDefinition.type = typeName;
  51804. // Check that default value exists.
  51805. if ('default' in propDefinition) {
  51806. // Check that default values are valid.
  51807. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  51808. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  51809. '` in component `' + componentName + '`');
  51810. }
  51811. } else {
  51812. // Fill in default value.
  51813. propDefinition.default = propType.default;
  51814. }
  51815. return propDefinition;
  51816. }
  51817. module.exports.processPropertyDefinition = processPropertyDefinition;
  51818. /**
  51819. * Parse propData using schema. Use default values if not existing in propData.
  51820. *
  51821. * @param {object} propData - Unparsed properties.
  51822. * @param {object} schema - Property types definition.
  51823. * @param {boolean} getPartialData - Whether to return full component data or just the data
  51824. * with keys in `propData`.
  51825. * @param {string } componentName - Name of the component, used for the property warning.
  51826. * @param {boolean} silent - Suppress warning messages.
  51827. */
  51828. module.exports.parseProperties = (function () {
  51829. var propNames = [];
  51830. return function (propData, schema, getPartialData, componentName, silent) {
  51831. var i;
  51832. var propName;
  51833. var propDefinition;
  51834. var propValue;
  51835. propNames.length = 0;
  51836. for (propName in (getPartialData ? propData : schema)) {
  51837. if (getPartialData && propData[propName] === undefined) { continue; }
  51838. propNames.push(propName);
  51839. }
  51840. if (propData === null || typeof propData !== 'object') { return propData; }
  51841. // Validation errors.
  51842. for (propName in propData) {
  51843. if (propData[propName] !== undefined && !schema[propName] && !silent) {
  51844. warn('Unknown property `' + propName +
  51845. '` for component/system `' + componentName + '`.');
  51846. }
  51847. }
  51848. for (i = 0; i < propNames.length; i++) {
  51849. propName = propNames[i];
  51850. propDefinition = schema[propName];
  51851. propValue = propData[propName];
  51852. if (!(schema[propName])) { return; }
  51853. propData[propName] = parseProperty(propValue, propDefinition);
  51854. }
  51855. return propData;
  51856. };
  51857. })();
  51858. /**
  51859. * Deserialize a single property.
  51860. */
  51861. function parseProperty (value, propDefinition) {
  51862. // Use default value if value is falsy.
  51863. if (value === undefined || value === null || value === '') {
  51864. value = propDefinition.default;
  51865. if (Array.isArray(value)) { value = value.slice(); }
  51866. }
  51867. // Invoke property type parser.
  51868. return propDefinition.parse(value, propDefinition.default);
  51869. }
  51870. module.exports.parseProperty = parseProperty;
  51871. /**
  51872. * Serialize a group of properties.
  51873. */
  51874. module.exports.stringifyProperties = function (propData, schema) {
  51875. var propName;
  51876. var propDefinition;
  51877. var propValue;
  51878. var stringifiedData = {};
  51879. var value;
  51880. for (propName in propData) {
  51881. propDefinition = schema[propName];
  51882. propValue = propData[propName];
  51883. value = propValue;
  51884. if (typeof value === 'object') {
  51885. value = stringifyProperty(propValue, propDefinition);
  51886. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  51887. }
  51888. stringifiedData[propName] = value;
  51889. }
  51890. return stringifiedData;
  51891. };
  51892. /**
  51893. * Serialize a single property.
  51894. */
  51895. function stringifyProperty (value, propDefinition) {
  51896. // This function stringifies but it's used in a context where
  51897. // there's always second stringification pass. By returning the original
  51898. // value when it's not an object we save one unnecessary call
  51899. // to JSON.stringify.
  51900. if (typeof value !== 'object') { return value; }
  51901. // if there's no schema for the property we use standar JSON stringify
  51902. if (!propDefinition || value === null) { return JSON.stringify(value); }
  51903. return propDefinition.stringify(value);
  51904. }
  51905. module.exports.stringifyProperty = stringifyProperty;
  51906. },{"../utils/":176,"./propertyTypes":105}],113:[function(_dereq_,module,exports){
  51907. var schema = _dereq_('./schema');
  51908. var processSchema = schema.process;
  51909. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  51910. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  51911. var THREE = _dereq_('../lib/three');
  51912. var utils = _dereq_('../utils');
  51913. // A-Frame properties to three.js uniform types.
  51914. var propertyToThreeMapping = {
  51915. array: 'v3',
  51916. color: 'v3',
  51917. int: 'i',
  51918. number: 'f',
  51919. map: 't',
  51920. time: 'f',
  51921. vec2: 'v2',
  51922. vec3: 'v3',
  51923. vec4: 'v4'
  51924. };
  51925. /**
  51926. * Shader class definition.
  51927. *
  51928. * Shaders extend the material component API so you can create your own library
  51929. * of customized materials
  51930. *
  51931. */
  51932. var Shader = module.exports.Shader = function () {};
  51933. Shader.prototype = {
  51934. /**
  51935. * Contains the type schema and defaults for the data values.
  51936. * Data is coerced into the types of the values of the defaults.
  51937. */
  51938. schema: {},
  51939. vertexShader:
  51940. 'void main() {' +
  51941. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  51942. '}',
  51943. fragmentShader:
  51944. 'void main() {' +
  51945. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  51946. '}',
  51947. /**
  51948. * Init handler. Similar to attachedCallback.
  51949. * Called during shader initialization and is only run once.
  51950. */
  51951. init: function (data) {
  51952. this.attributes = this.initVariables(data, 'attribute');
  51953. this.uniforms = this.initVariables(data, 'uniform');
  51954. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  51955. // attributes: this.attributes,
  51956. uniforms: this.uniforms,
  51957. vertexShader: this.vertexShader,
  51958. fragmentShader: this.fragmentShader
  51959. });
  51960. return this.material;
  51961. },
  51962. initVariables: function (data, type) {
  51963. var key;
  51964. var schema = this.schema;
  51965. var variables = {};
  51966. var varType;
  51967. for (key in schema) {
  51968. if (schema[key].is !== type) { continue; }
  51969. varType = propertyToThreeMapping[schema[key].type];
  51970. variables[key] = {
  51971. type: varType,
  51972. value: undefined // Let updateVariables handle setting these.
  51973. };
  51974. }
  51975. return variables;
  51976. },
  51977. /**
  51978. * Update handler. Similar to attributeChangedCallback.
  51979. * Called whenever the associated material data changes.
  51980. *
  51981. * @param {object} data - New material data.
  51982. */
  51983. update: function (data) {
  51984. this.updateVariables(data, 'attribute');
  51985. this.updateVariables(data, 'uniform');
  51986. },
  51987. updateVariables: function (data, type) {
  51988. var key;
  51989. var materialKey;
  51990. var schema = this.schema;
  51991. var variables;
  51992. variables = type === 'uniform' ? this.uniforms : this.attributes;
  51993. for (key in data) {
  51994. if (!schema[key] || schema[key].is !== type) { continue; }
  51995. if (schema[key].type === 'map') {
  51996. // If data unchanged, get out early.
  51997. if (!variables[key] || variables[key].value === data[key]) { continue; }
  51998. // Special handling is needed for textures.
  51999. materialKey = '_texture_' + key;
  52000. // We can't actually set the variable correctly until we've loaded the texture.
  52001. this.setMapOnTextureLoad(variables, key, materialKey);
  52002. // Kick off the texture update now that handler is added.
  52003. utils.material.updateMapMaterialFromData(materialKey, key, this, data);
  52004. continue;
  52005. }
  52006. variables[key].value = this.parseValue(schema[key].type, data[key]);
  52007. variables[key].needsUpdate = true;
  52008. }
  52009. },
  52010. parseValue: function (type, value) {
  52011. var color;
  52012. switch (type) {
  52013. case 'vec2': {
  52014. return new THREE.Vector2(value.x, value.y);
  52015. }
  52016. case 'vec3': {
  52017. return new THREE.Vector3(value.x, value.y, value.z);
  52018. }
  52019. case 'vec4': {
  52020. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  52021. }
  52022. case 'color': {
  52023. color = new THREE.Color(value);
  52024. return new THREE.Vector3(color.r, color.g, color.b);
  52025. }
  52026. case 'map': {
  52027. return THREE.ImageUtils.loadTexture(value);
  52028. }
  52029. default: {
  52030. return value;
  52031. }
  52032. }
  52033. },
  52034. setMapOnTextureLoad: function (variables, key, materialKey) {
  52035. var self = this;
  52036. this.el.addEventListener('materialtextureloaded', function () {
  52037. variables[key].value = self.material[materialKey];
  52038. variables[key].needsUpdate = true;
  52039. });
  52040. }
  52041. };
  52042. /**
  52043. * Registers a shader to A-Frame.
  52044. *
  52045. * @param {string} name - shader name.
  52046. * @param {object} definition - shader property and methods.
  52047. * @returns {object} Shader.
  52048. */
  52049. module.exports.registerShader = function (name, definition) {
  52050. var NewShader;
  52051. var proto = {};
  52052. // Format definition object to prototype object.
  52053. Object.keys(definition).forEach(function (key) {
  52054. proto[key] = {
  52055. value: definition[key],
  52056. writable: true
  52057. };
  52058. });
  52059. if (shaders[name]) {
  52060. throw new Error('The shader ' + name + ' has been already registered');
  52061. }
  52062. NewShader = function () { Shader.call(this); };
  52063. NewShader.prototype = Object.create(Shader.prototype, proto);
  52064. NewShader.prototype.name = name;
  52065. NewShader.prototype.constructor = NewShader;
  52066. shaders[name] = {
  52067. Shader: NewShader,
  52068. schema: processSchema(NewShader.prototype.schema)
  52069. };
  52070. shaderNames.push(name);
  52071. return NewShader;
  52072. };
  52073. },{"../lib/three":151,"../utils":176,"./schema":112}],114:[function(_dereq_,module,exports){
  52074. var components = _dereq_('./component');
  52075. var schema = _dereq_('./schema');
  52076. var utils = _dereq_('../utils/');
  52077. var parseProperties = schema.parseProperties;
  52078. var parseProperty = schema.parseProperty;
  52079. var processSchema = schema.process;
  52080. var isSingleProp = schema.isSingleProperty;
  52081. var styleParser = utils.styleParser;
  52082. var systems = module.exports.systems = {}; // Keep track of registered systems.
  52083. /**
  52084. * System class definition.
  52085. *
  52086. * Systems provide global scope and services to a group of instantiated components of the
  52087. * same class. They can also help abstract logic away from components such that components
  52088. * only have to worry about data.
  52089. *
  52090. * For example, a physics component that creates a physics world that oversees
  52091. * all entities with a physics or rigid body component.
  52092. *
  52093. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  52094. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  52095. * setAttribute behavior).
  52096. *
  52097. * @member {string} name - Name that system is registered under.
  52098. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  52099. */
  52100. var System = module.exports.System = function (sceneEl) {
  52101. var component = components && components.components[this.name];
  52102. // Set reference to scene.
  52103. this.el = sceneEl;
  52104. this.sceneEl = sceneEl;
  52105. // Set reference to matching component (if exists).
  52106. if (component) { component.Component.prototype.system = this; }
  52107. // Process system configuration.
  52108. this.buildData();
  52109. this.init();
  52110. this.update({});
  52111. };
  52112. System.prototype = {
  52113. /**
  52114. * Schema to configure system.
  52115. */
  52116. schema: {},
  52117. /**
  52118. * Init handler. Called during scene initialization and is only run once.
  52119. * Systems can use this to set initial state.
  52120. */
  52121. init: function () { /* no-op */ },
  52122. /**
  52123. * Update handler. Called during scene attribute updates.
  52124. * Systems can use this to dynamically update their state.
  52125. */
  52126. update: function (oldData) { /* no-op */ },
  52127. /**
  52128. * Build data and call update handler.
  52129. *
  52130. * @private
  52131. */
  52132. updateProperties: function (rawData) {
  52133. var oldData = this.data;
  52134. if (!Object.keys(schema).length) { return; }
  52135. this.buildData(rawData);
  52136. this.update(oldData);
  52137. },
  52138. /**
  52139. * Parse data.
  52140. */
  52141. buildData: function (rawData) {
  52142. var schema = this.schema;
  52143. if (!Object.keys(schema).length) { return; }
  52144. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  52145. if (isSingleProp(schema)) {
  52146. this.data = parseProperty(rawData, schema);
  52147. } else {
  52148. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  52149. }
  52150. },
  52151. /**
  52152. * Tick handler.
  52153. * Called on each tick of the scene render loop.
  52154. * Affected by play and pause.
  52155. *
  52156. * @param {number} time - Scene tick time.
  52157. * @param {number} timeDelta - Difference in current render time and previous render time.
  52158. */
  52159. tick: undefined,
  52160. /**
  52161. * Tock handler.
  52162. * Called on each tock of the scene render loop.
  52163. * Affected by play and pause.
  52164. *
  52165. * @param {number} time - Scene tick time.
  52166. * @param {number} timeDelta - Difference in current render time and previous render time.
  52167. */
  52168. tock: undefined,
  52169. /**
  52170. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  52171. */
  52172. play: function () { /* no-op */ },
  52173. /**
  52174. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  52175. */
  52176. pause: function () { /* no-op */ }
  52177. };
  52178. /**
  52179. * Registers a system to A-Frame.
  52180. *
  52181. * @param {string} name - Component name.
  52182. * @param {object} definition - Component property and methods.
  52183. * @returns {object} Component.
  52184. */
  52185. module.exports.registerSystem = function (name, definition) {
  52186. var i;
  52187. var NewSystem;
  52188. var proto = {};
  52189. var scenes = utils.findAllScenes(document);
  52190. // Format definition object to prototype object.
  52191. Object.keys(definition).forEach(function (key) {
  52192. proto[key] = {
  52193. value: definition[key],
  52194. writable: true
  52195. };
  52196. });
  52197. if (systems[name]) {
  52198. throw new Error('The system `' + name + '` has been already registered. ' +
  52199. 'Check that you are not loading two versions of the same system ' +
  52200. 'or two different systems of the same name.');
  52201. }
  52202. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  52203. NewSystem.prototype = Object.create(System.prototype, proto);
  52204. NewSystem.prototype.name = name;
  52205. NewSystem.prototype.constructor = NewSystem;
  52206. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  52207. systems[name] = NewSystem;
  52208. // Initialize systems for existing scenes
  52209. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  52210. };
  52211. },{"../utils/":176,"./component":103,"./schema":112}],115:[function(_dereq_,module,exports){
  52212. _dereq_('./pivot');
  52213. },{"./pivot":116}],116:[function(_dereq_,module,exports){
  52214. var registerComponent = _dereq_('../../core/component').registerComponent;
  52215. var THREE = _dereq_('../../lib/three');
  52216. var originalPosition = new THREE.Vector3();
  52217. var originalRotation = new THREE.Vector3();
  52218. /**
  52219. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  52220. */
  52221. registerComponent('pivot', {
  52222. dependencies: ['position'],
  52223. schema: {type: 'vec3'},
  52224. init: function () {
  52225. var data = this.data;
  52226. var el = this.el;
  52227. var originalParent = el.object3D.parent;
  52228. var originalGroup = el.object3D;
  52229. var outerGroup = new THREE.Group();
  52230. originalPosition.copy(originalGroup.position);
  52231. originalRotation.copy(originalGroup.rotation);
  52232. // Detach current group from parent.
  52233. originalParent.remove(originalGroup);
  52234. outerGroup.add(originalGroup);
  52235. // Set new group as the outer group.
  52236. originalParent.add(outerGroup);
  52237. // Set outer group as new object3D.
  52238. el.object3D = outerGroup;
  52239. // Apply pivot to original group.
  52240. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  52241. // Offset the pivot so that world position not affected.
  52242. // And restore position onto outer group.
  52243. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  52244. data.z + originalPosition.z);
  52245. // Transfer rotation to outer group.
  52246. outerGroup.rotation.copy(originalGroup.rotation);
  52247. originalGroup.rotation.set(0, 0, 0);
  52248. }
  52249. });
  52250. },{"../../core/component":103,"../../lib/three":151}],117:[function(_dereq_,module,exports){
  52251. /**
  52252. * Common mesh defaults, mappings, and transforms.
  52253. */
  52254. var components = _dereq_('../../core/component').components;
  52255. var shaders = _dereq_('../../core/shader').shaders;
  52256. var utils = _dereq_('../../utils/');
  52257. var materialMappings = {};
  52258. Object.keys(components.material.schema).forEach(addMapping);
  52259. Object.keys(shaders.standard.schema).forEach(addMapping);
  52260. function addMapping (prop) {
  52261. // To hyphenated.
  52262. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52263. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  52264. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  52265. materialMappings[htmlAttrName] = 'material.' + prop;
  52266. }
  52267. module.exports = function getMeshMixin () {
  52268. return {
  52269. defaultComponents: {material: {}},
  52270. mappings: utils.extend({}, materialMappings)
  52271. };
  52272. };
  52273. },{"../../core/component":103,"../../core/shader":113,"../../utils/":176}],118:[function(_dereq_,module,exports){
  52274. _dereq_('./primitives/a-camera');
  52275. _dereq_('./primitives/a-cursor');
  52276. _dereq_('./primitives/a-curvedimage');
  52277. _dereq_('./primitives/a-gltf-model');
  52278. _dereq_('./primitives/a-image');
  52279. _dereq_('./primitives/a-light');
  52280. _dereq_('./primitives/a-link');
  52281. _dereq_('./primitives/a-obj-model');
  52282. _dereq_('./primitives/a-sky');
  52283. _dereq_('./primitives/a-sound');
  52284. _dereq_('./primitives/a-text');
  52285. _dereq_('./primitives/a-video');
  52286. _dereq_('./primitives/a-videosphere');
  52287. _dereq_('./primitives/meshPrimitives');
  52288. },{"./primitives/a-camera":120,"./primitives/a-cursor":121,"./primitives/a-curvedimage":122,"./primitives/a-gltf-model":123,"./primitives/a-image":124,"./primitives/a-light":125,"./primitives/a-link":126,"./primitives/a-obj-model":127,"./primitives/a-sky":128,"./primitives/a-sound":129,"./primitives/a-text":130,"./primitives/a-video":131,"./primitives/a-videosphere":132,"./primitives/meshPrimitives":133}],119:[function(_dereq_,module,exports){
  52289. var AEntity = _dereq_('../../core/a-entity');
  52290. var components = _dereq_('../../core/component').components;
  52291. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  52292. var utils = _dereq_('../../utils/');
  52293. var debug = utils.debug;
  52294. var setComponentProperty = utils.entity.setComponentProperty;
  52295. var log = debug('extras:primitives:debug');
  52296. var warn = debug('extras:primitives:warn');
  52297. var primitives = module.exports.primitives = {};
  52298. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  52299. name = name.toLowerCase();
  52300. log('Registering <%s>', name);
  52301. // Deprecation warning for defaultAttributes usage.
  52302. if (definition.defaultAttributes) {
  52303. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  52304. }
  52305. var primitive = registerElement(name, {
  52306. prototype: Object.create(AEntity.prototype, {
  52307. defaultComponentsFromPrimitive: {
  52308. value: definition.defaultComponents || definition.defaultAttributes || {}
  52309. },
  52310. deprecated: {value: definition.deprecated || null},
  52311. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  52312. mappings: {value: definition.mappings || {}},
  52313. createdCallback: {
  52314. value: function () {
  52315. if (definition.deprecated) { console.warn(definition.deprecated); }
  52316. this.resolveMappingCollisions();
  52317. }
  52318. },
  52319. /**
  52320. * If a mapping collides with a registered component name
  52321. * it renames the mapping to componentname-property
  52322. */
  52323. resolveMappingCollisions: {
  52324. value: function () {
  52325. var mappings = this.mappings;
  52326. var self = this;
  52327. Object.keys(mappings).forEach(function resolveCollision (key) {
  52328. var newAttribute;
  52329. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  52330. if (components[key]) {
  52331. newAttribute = mappings[key].replace('.', '-');
  52332. mappings[newAttribute] = mappings[key];
  52333. delete mappings[key];
  52334. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  52335. 'The attribute ' + key + ' has the same name as a registered component and' +
  52336. ' has been renamed to ' + newAttribute);
  52337. }
  52338. });
  52339. }
  52340. },
  52341. getExtraComponents: {
  52342. value: function () {
  52343. var attr;
  52344. var data;
  52345. var i;
  52346. var mapping;
  52347. var mixins;
  52348. var path;
  52349. var self = this;
  52350. // Gather component data from default components.
  52351. data = utils.clone(this.defaultComponentsFromPrimitive);
  52352. // Factor in mixins to overwrite default components.
  52353. mixins = this.getAttribute('mixin');
  52354. if (mixins) {
  52355. mixins = mixins.trim().split(' ');
  52356. mixins.forEach(function applyMixin (mixinId) {
  52357. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  52358. Object.keys(mixinComponents).forEach(function setComponent (name) {
  52359. data[name] = extend(data[name], mixinComponents[name]);
  52360. });
  52361. });
  52362. }
  52363. // Gather component data from mappings.
  52364. for (i = 0; i < this.attributes.length; i++) {
  52365. attr = this.attributes[i];
  52366. mapping = this.mappings[attr.name];
  52367. if (mapping) {
  52368. path = utils.entity.getComponentPropertyPath(mapping);
  52369. if (path.constructor === Array) {
  52370. data[path[0]] = data[path[0]] || {};
  52371. data[path[0]][path[1]] = attr.value.trim();
  52372. } else {
  52373. data[path] = attr.value.trim();
  52374. }
  52375. continue;
  52376. }
  52377. }
  52378. return data;
  52379. /**
  52380. * For the base to be extensible, both objects must be pure JavaScript objects.
  52381. * The function assumes that base is undefined, or null or a pure object.
  52382. */
  52383. function extend (base, extension) {
  52384. if (isUndefined(base)) {
  52385. return copy(extension);
  52386. }
  52387. if (isUndefined(extension)) {
  52388. return copy(base);
  52389. }
  52390. if (isPureObject(base) && isPureObject(extension)) {
  52391. return utils.extendDeep(base, extension);
  52392. }
  52393. return copy(extension);
  52394. }
  52395. function isUndefined (value) {
  52396. return typeof value === 'undefined';
  52397. }
  52398. function copy (value) {
  52399. if (isPureObject(value)) {
  52400. return utils.extendDeep({}, value);
  52401. }
  52402. return value;
  52403. }
  52404. function isPureObject (value) {
  52405. return value !== null && value.constructor === Object;
  52406. }
  52407. }
  52408. },
  52409. /**
  52410. * Sync to attribute to component property whenever mapped attribute changes.
  52411. * If attribute is mapped to a component property, set the component property using
  52412. * the attribute value.
  52413. */
  52414. attributeChangedCallback: {
  52415. value: function (attr, oldVal, value) {
  52416. var componentName = this.mappings[attr];
  52417. if (attr in this.deprecatedMappings) {
  52418. console.warn(this.deprecatedMappings[attr]);
  52419. }
  52420. if (!attr || !componentName) { return; }
  52421. // Set value.
  52422. setComponentProperty(this, componentName, value);
  52423. }
  52424. }
  52425. })
  52426. });
  52427. // Store.
  52428. primitives[name] = primitive;
  52429. return primitive;
  52430. };
  52431. /**
  52432. * Add component mappings using schema.
  52433. */
  52434. function addComponentMapping (componentName, mappings) {
  52435. var schema = components[componentName].schema;
  52436. Object.keys(schema).map(function (prop) {
  52437. // Hyphenate where there is camelCase.
  52438. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52439. // If there is a mapping collision, prefix with component name and hyphen.
  52440. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  52441. mappings[attrName] = componentName + '.' + prop;
  52442. });
  52443. }
  52444. /**
  52445. * Helper to define a primitive, building mappings using a component schema.
  52446. */
  52447. function definePrimitive (tagName, defaultComponents, mappings) {
  52448. // If no initial mappings provided, start from empty map.
  52449. mappings = mappings || {};
  52450. // From the default components, add mapping automagically.
  52451. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  52452. addComponentMapping(componentName, mappings);
  52453. });
  52454. // Register the primitive.
  52455. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  52456. defaultComponents: defaultComponents,
  52457. mappings: mappings
  52458. }));
  52459. }
  52460. module.exports.definePrimitive = definePrimitive;
  52461. },{"../../core/a-entity":99,"../../core/a-register-element":102,"../../core/component":103,"../../utils/":176}],120:[function(_dereq_,module,exports){
  52462. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52463. registerPrimitive('a-camera', {
  52464. defaultComponents: {
  52465. 'camera': {},
  52466. 'look-controls': {},
  52467. 'wasd-controls': {},
  52468. 'position': {x: 0, y: 1.6, z: 0}
  52469. },
  52470. mappings: {
  52471. active: 'camera.active',
  52472. far: 'camera.far',
  52473. fov: 'camera.fov',
  52474. 'look-controls-enabled': 'look-controls.enabled',
  52475. near: 'camera.near',
  52476. 'pointer-lock-enabled': 'look-controls.pointerLockEnabled',
  52477. 'wasd-controls-enabled': 'wasd-controls.enabled',
  52478. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  52479. zoom: 'camera.zoom'
  52480. }
  52481. });
  52482. },{"../primitives":119}],121:[function(_dereq_,module,exports){
  52483. var getMeshMixin = _dereq_('../getMeshMixin');
  52484. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52485. var utils = _dereq_('../../../utils/');
  52486. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  52487. defaultComponents: {
  52488. cursor: {},
  52489. geometry: {
  52490. primitive: 'ring',
  52491. radiusOuter: 0.016,
  52492. radiusInner: 0.01,
  52493. segmentsTheta: 32
  52494. },
  52495. material: {
  52496. color: '#000',
  52497. shader: 'flat',
  52498. opacity: 0.8
  52499. },
  52500. position: {
  52501. x: 0,
  52502. y: 0,
  52503. z: -1
  52504. }
  52505. },
  52506. mappings: {
  52507. far: 'raycaster.far',
  52508. fuse: 'cursor.fuse',
  52509. 'fuse-timeout': 'cursor.fuseTimeout',
  52510. interval: 'raycaster.interval',
  52511. objects: 'raycaster.objects'
  52512. }
  52513. }));
  52514. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],122:[function(_dereq_,module,exports){
  52515. var getMeshMixin = _dereq_('../getMeshMixin');
  52516. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52517. var utils = _dereq_('../../../utils/');
  52518. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  52519. defaultComponents: {
  52520. geometry: {
  52521. height: 1,
  52522. primitive: 'cylinder',
  52523. radius: 2,
  52524. segmentsRadial: 48,
  52525. thetaLength: 270,
  52526. openEnded: true,
  52527. thetaStart: 0
  52528. },
  52529. material: {
  52530. color: '#FFF',
  52531. shader: 'flat',
  52532. side: 'double',
  52533. transparent: true,
  52534. repeat: '-1 1'
  52535. }
  52536. },
  52537. mappings: {
  52538. height: 'geometry.height',
  52539. 'open-ended': 'geometry.openEnded',
  52540. radius: 'geometry.radius',
  52541. segments: 'geometry.segmentsRadial',
  52542. start: 'geometry.thetaStart',
  52543. 'theta-length': 'geometry.thetaLength',
  52544. 'theta-start': 'geometry.thetaStart',
  52545. 'width': 'geometry.thetaLength'
  52546. }
  52547. }));
  52548. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],123:[function(_dereq_,module,exports){
  52549. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52550. registerPrimitive('a-gltf-model', {
  52551. mappings: {
  52552. src: 'gltf-model'
  52553. }
  52554. });
  52555. },{"../primitives":119}],124:[function(_dereq_,module,exports){
  52556. var getMeshMixin = _dereq_('../getMeshMixin');
  52557. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52558. var utils = _dereq_('../../../utils/');
  52559. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  52560. defaultComponents: {
  52561. geometry: {
  52562. primitive: 'plane'
  52563. },
  52564. material: {
  52565. color: '#FFF',
  52566. shader: 'flat',
  52567. side: 'double',
  52568. transparent: true
  52569. }
  52570. },
  52571. mappings: {
  52572. height: 'geometry.height',
  52573. width: 'geometry.width'
  52574. }
  52575. }));
  52576. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],125:[function(_dereq_,module,exports){
  52577. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52578. registerPrimitive('a-light', {
  52579. defaultComponents: {
  52580. light: {}
  52581. },
  52582. mappings: {
  52583. angle: 'light.angle',
  52584. color: 'light.color',
  52585. 'ground-color': 'light.groundColor',
  52586. decay: 'light.decay',
  52587. distance: 'light.distance',
  52588. intensity: 'light.intensity',
  52589. penumbra: 'light.penumbra',
  52590. type: 'light.type',
  52591. target: 'light.target'
  52592. }
  52593. });
  52594. },{"../primitives":119}],126:[function(_dereq_,module,exports){
  52595. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52596. registerPrimitive('a-link', {
  52597. defaultComponents: {
  52598. link: {
  52599. visualAspectEnabled: true
  52600. }
  52601. },
  52602. mappings: {
  52603. href: 'link.href',
  52604. image: 'link.image',
  52605. title: 'link.title'
  52606. }
  52607. });
  52608. },{"../primitives":119}],127:[function(_dereq_,module,exports){
  52609. var meshMixin = _dereq_('../getMeshMixin')();
  52610. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52611. var utils = _dereq_('../../../utils/');
  52612. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  52613. defaultComponents: {
  52614. 'obj-model': {}
  52615. },
  52616. mappings: {
  52617. src: 'obj-model.obj',
  52618. mtl: 'obj-model.mtl'
  52619. }
  52620. }));
  52621. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],128:[function(_dereq_,module,exports){
  52622. var getMeshMixin = _dereq_('../getMeshMixin');
  52623. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52624. var utils = _dereq_('../../../utils/');
  52625. var meshPrimitives = _dereq_('./meshPrimitives');
  52626. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  52627. defaultComponents: {
  52628. geometry: {
  52629. primitive: 'sphere',
  52630. radius: 5000,
  52631. segmentsWidth: 64,
  52632. segmentsHeight: 32
  52633. },
  52634. material: {
  52635. color: '#FFF',
  52636. side: 'back',
  52637. shader: 'flat',
  52638. npot: true
  52639. },
  52640. scale: '-1 1 1'
  52641. },
  52642. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  52643. }));
  52644. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119,"./meshPrimitives":133}],129:[function(_dereq_,module,exports){
  52645. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52646. registerPrimitive('a-sound', {
  52647. defaultComponents: {
  52648. sound: {}
  52649. },
  52650. mappings: {
  52651. src: 'sound.src',
  52652. on: 'sound.on',
  52653. autoplay: 'sound.autoplay',
  52654. loop: 'sound.loop',
  52655. volume: 'sound.volume'
  52656. }
  52657. });
  52658. },{"../primitives":119}],130:[function(_dereq_,module,exports){
  52659. // <a-text> using `definePrimitive` helper.
  52660. var definePrimitive = _dereq_('../primitives').definePrimitive;
  52661. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  52662. },{"../primitives":119}],131:[function(_dereq_,module,exports){
  52663. var getMeshMixin = _dereq_('../getMeshMixin');
  52664. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52665. var utils = _dereq_('../../../utils/');
  52666. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  52667. defaultComponents: {
  52668. geometry: {
  52669. primitive: 'plane'
  52670. },
  52671. material: {
  52672. color: '#FFF',
  52673. shader: 'flat',
  52674. side: 'double',
  52675. transparent: true
  52676. }
  52677. },
  52678. mappings: {
  52679. height: 'geometry.height',
  52680. width: 'geometry.width'
  52681. }
  52682. }));
  52683. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],132:[function(_dereq_,module,exports){
  52684. var getMeshMixin = _dereq_('../getMeshMixin');
  52685. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52686. var utils = _dereq_('../../../utils/');
  52687. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  52688. defaultComponents: {
  52689. geometry: {
  52690. primitive: 'sphere',
  52691. radius: 5000,
  52692. segmentsWidth: 64,
  52693. segmentsHeight: 32
  52694. },
  52695. material: {
  52696. color: '#FFF',
  52697. shader: 'flat',
  52698. side: 'back',
  52699. npot: true
  52700. },
  52701. scale: '-1 1 1'
  52702. },
  52703. mappings: {
  52704. radius: 'geometry.radius',
  52705. 'segments-height': 'geometry.segmentsHeight',
  52706. 'segments-width': 'geometry.segmentsWidth'
  52707. }
  52708. }));
  52709. },{"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],133:[function(_dereq_,module,exports){
  52710. /**
  52711. * Automated mesh primitive registration.
  52712. */
  52713. var getMeshMixin = _dereq_('../getMeshMixin');
  52714. var geometries = _dereq_('../../../core/geometry').geometries;
  52715. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  52716. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52717. var utils = _dereq_('../../../utils/');
  52718. // For testing.
  52719. var meshPrimitives = module.exports = {};
  52720. // Generate primitive for each geometry type.
  52721. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  52722. var geometry = geometries[geometryName];
  52723. var geometryHyphened = unCamelCase(geometryName);
  52724. // Generate mappings.
  52725. var mappings = {};
  52726. Object.keys(geometry.schema).forEach(function createMapping (property) {
  52727. mappings[unCamelCase(property)] = 'geometry.' + property;
  52728. });
  52729. // Register.
  52730. var tagName = 'a-' + geometryHyphened;
  52731. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  52732. defaultComponents: {geometry: {primitive: geometryName}},
  52733. mappings: mappings
  52734. }));
  52735. meshPrimitives[tagName] = primitive;
  52736. });
  52737. /**
  52738. * camelCase to hyphened-string.
  52739. */
  52740. function unCamelCase (str) {
  52741. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52742. }
  52743. },{"../../../core/geometry":104,"../../../utils/":176,"../getMeshMixin":117,"../primitives":119}],134:[function(_dereq_,module,exports){
  52744. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52745. var THREE = _dereq_('../lib/three');
  52746. registerGeometry('box', {
  52747. schema: {
  52748. depth: {default: 1, min: 0},
  52749. height: {default: 1, min: 0},
  52750. width: {default: 1, min: 0},
  52751. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52752. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  52753. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  52754. },
  52755. init: function (data) {
  52756. this.geometry = new THREE.BoxGeometry(
  52757. data.width, data.height, data.depth,
  52758. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  52759. }
  52760. });
  52761. },{"../core/geometry":104,"../lib/three":151}],135:[function(_dereq_,module,exports){
  52762. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52763. var THREE = _dereq_('../lib/three');
  52764. var degToRad = THREE.Math.degToRad;
  52765. registerGeometry('circle', {
  52766. schema: {
  52767. radius: {default: 1, min: 0},
  52768. segments: {default: 32, min: 3, type: 'int'},
  52769. thetaLength: {default: 360, min: 0},
  52770. thetaStart: {default: 0}
  52771. },
  52772. init: function (data) {
  52773. this.geometry = new THREE.CircleGeometry(
  52774. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52775. }
  52776. });
  52777. },{"../core/geometry":104,"../lib/three":151}],136:[function(_dereq_,module,exports){
  52778. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52779. var THREE = _dereq_('../lib/three');
  52780. var degToRad = THREE.Math.degToRad;
  52781. registerGeometry('cone', {
  52782. schema: {
  52783. height: {default: 1, min: 0},
  52784. openEnded: {default: false},
  52785. radiusBottom: {default: 1, min: 0},
  52786. radiusTop: {default: 0.01, min: 0},
  52787. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52788. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52789. thetaLength: {default: 360, min: 0},
  52790. thetaStart: {default: 0}
  52791. },
  52792. init: function (data) {
  52793. this.geometry = new THREE.CylinderGeometry(
  52794. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  52795. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  52796. degToRad(data.thetaLength));
  52797. }
  52798. });
  52799. },{"../core/geometry":104,"../lib/three":151}],137:[function(_dereq_,module,exports){
  52800. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52801. var THREE = _dereq_('../lib/three');
  52802. var degToRad = THREE.Math.degToRad;
  52803. registerGeometry('cylinder', {
  52804. schema: {
  52805. height: {default: 1, min: 0},
  52806. openEnded: {default: false},
  52807. radius: {default: 1, min: 0},
  52808. segmentsHeight: {default: 18, min: 1, type: 'int'},
  52809. segmentsRadial: {default: 36, min: 3, type: 'int'},
  52810. thetaLength: {default: 360, min: 0},
  52811. thetaStart: {default: 0}
  52812. },
  52813. init: function (data) {
  52814. this.geometry = new THREE.CylinderGeometry(
  52815. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  52816. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  52817. }
  52818. });
  52819. },{"../core/geometry":104,"../lib/three":151}],138:[function(_dereq_,module,exports){
  52820. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52821. var THREE = _dereq_('../lib/three');
  52822. registerGeometry('dodecahedron', {
  52823. schema: {
  52824. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52825. radius: {default: 1, min: 0}
  52826. },
  52827. init: function (data) {
  52828. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  52829. }
  52830. });
  52831. },{"../core/geometry":104,"../lib/three":151}],139:[function(_dereq_,module,exports){
  52832. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52833. var THREE = _dereq_('../lib/three');
  52834. registerGeometry('icosahedron', {
  52835. schema: {
  52836. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52837. radius: {default: 1, min: 0}
  52838. },
  52839. init: function (data) {
  52840. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  52841. }
  52842. });
  52843. },{"../core/geometry":104,"../lib/three":151}],140:[function(_dereq_,module,exports){
  52844. _dereq_('./box.js');
  52845. _dereq_('./circle.js');
  52846. _dereq_('./cone.js');
  52847. _dereq_('./cylinder.js');
  52848. _dereq_('./dodecahedron.js');
  52849. _dereq_('./icosahedron.js');
  52850. _dereq_('./octahedron.js');
  52851. _dereq_('./plane.js');
  52852. _dereq_('./ring.js');
  52853. _dereq_('./sphere.js');
  52854. _dereq_('./tetrahedron.js');
  52855. _dereq_('./torus.js');
  52856. _dereq_('./torusKnot.js');
  52857. _dereq_('./triangle.js');
  52858. },{"./box.js":134,"./circle.js":135,"./cone.js":136,"./cylinder.js":137,"./dodecahedron.js":138,"./icosahedron.js":139,"./octahedron.js":141,"./plane.js":142,"./ring.js":143,"./sphere.js":144,"./tetrahedron.js":145,"./torus.js":146,"./torusKnot.js":147,"./triangle.js":148}],141:[function(_dereq_,module,exports){
  52859. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52860. var THREE = _dereq_('../lib/three');
  52861. registerGeometry('octahedron', {
  52862. schema: {
  52863. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52864. radius: {default: 1, min: 0}
  52865. },
  52866. init: function (data) {
  52867. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  52868. }
  52869. });
  52870. },{"../core/geometry":104,"../lib/three":151}],142:[function(_dereq_,module,exports){
  52871. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52872. var THREE = _dereq_('../lib/three');
  52873. registerGeometry('plane', {
  52874. schema: {
  52875. height: {default: 1, min: 0},
  52876. width: {default: 1, min: 0},
  52877. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  52878. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  52879. },
  52880. init: function (data) {
  52881. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  52882. }
  52883. });
  52884. },{"../core/geometry":104,"../lib/three":151}],143:[function(_dereq_,module,exports){
  52885. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52886. var THREE = _dereq_('../lib/three');
  52887. var degToRad = THREE.Math.degToRad;
  52888. registerGeometry('ring', {
  52889. schema: {
  52890. radiusInner: {default: 0.8, min: 0},
  52891. radiusOuter: {default: 1.2, min: 0},
  52892. segmentsPhi: {default: 10, min: 1, type: 'int'},
  52893. segmentsTheta: {default: 32, min: 3, type: 'int'},
  52894. thetaLength: {default: 360, min: 0},
  52895. thetaStart: {default: 0}
  52896. },
  52897. init: function (data) {
  52898. this.geometry = new THREE.RingGeometry(
  52899. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  52900. degToRad(data.thetaStart), degToRad(data.thetaLength));
  52901. }
  52902. });
  52903. },{"../core/geometry":104,"../lib/three":151}],144:[function(_dereq_,module,exports){
  52904. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52905. var THREE = _dereq_('../lib/three');
  52906. var degToRad = THREE.Math.degToRad;
  52907. registerGeometry('sphere', {
  52908. schema: {
  52909. radius: {default: 1, min: 0},
  52910. phiLength: {default: 360},
  52911. phiStart: {default: 0, min: 0},
  52912. thetaLength: {default: 180, min: 0},
  52913. thetaStart: {default: 0},
  52914. segmentsHeight: {default: 18, min: 2, type: 'int'},
  52915. segmentsWidth: {default: 36, min: 3, type: 'int'}
  52916. },
  52917. init: function (data) {
  52918. this.geometry = new THREE.SphereGeometry(
  52919. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  52920. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  52921. }
  52922. });
  52923. },{"../core/geometry":104,"../lib/three":151}],145:[function(_dereq_,module,exports){
  52924. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52925. var THREE = _dereq_('../lib/three');
  52926. registerGeometry('tetrahedron', {
  52927. schema: {
  52928. detail: {default: 0, min: 0, max: 5, type: 'int'},
  52929. radius: {default: 1, min: 0}
  52930. },
  52931. init: function (data) {
  52932. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  52933. }
  52934. });
  52935. },{"../core/geometry":104,"../lib/three":151}],146:[function(_dereq_,module,exports){
  52936. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52937. var THREE = _dereq_('../lib/three');
  52938. var degToRad = THREE.Math.degToRad;
  52939. registerGeometry('torus', {
  52940. schema: {
  52941. arc: {default: 360},
  52942. radius: {default: 1, min: 0},
  52943. radiusTubular: {default: 0.2, min: 0},
  52944. segmentsRadial: {default: 36, min: 2, type: 'int'},
  52945. segmentsTubular: {default: 32, min: 3, type: 'int'}
  52946. },
  52947. init: function (data) {
  52948. this.geometry = new THREE.TorusGeometry(
  52949. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  52950. degToRad(data.arc));
  52951. }
  52952. });
  52953. },{"../core/geometry":104,"../lib/three":151}],147:[function(_dereq_,module,exports){
  52954. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52955. var THREE = _dereq_('../lib/three');
  52956. registerGeometry('torusKnot', {
  52957. schema: {
  52958. p: {default: 2, min: 1},
  52959. q: {default: 3, min: 1},
  52960. radius: {default: 1, min: 0},
  52961. radiusTubular: {default: 0.2, min: 0},
  52962. segmentsRadial: {default: 8, min: 3, type: 'int'},
  52963. segmentsTubular: {default: 100, min: 3, type: 'int'}
  52964. },
  52965. init: function (data) {
  52966. this.geometry = new THREE.TorusKnotGeometry(
  52967. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  52968. data.p, data.q);
  52969. }
  52970. });
  52971. },{"../core/geometry":104,"../lib/three":151}],148:[function(_dereq_,module,exports){
  52972. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  52973. var THREE = _dereq_('../lib/three');
  52974. var quaternion = new THREE.Quaternion();
  52975. var rotateVector = new THREE.Vector3(0, 0, 1);
  52976. var uvMinVector = new THREE.Vector2();
  52977. var uvMaxVector = new THREE.Vector2();
  52978. var uvScaleVector = new THREE.Vector2();
  52979. registerGeometry('triangle', {
  52980. schema: {
  52981. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  52982. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  52983. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  52984. },
  52985. init: function (data) {
  52986. var geometry;
  52987. var normal;
  52988. var triangle;
  52989. var uvA;
  52990. var uvB;
  52991. var uvC;
  52992. triangle = new THREE.Triangle();
  52993. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  52994. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  52995. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  52996. normal = triangle.getNormal(new THREE.Vector3());
  52997. // Rotate the 3D triangle to be parallel to XY plane.
  52998. quaternion.setFromUnitVectors(normal, rotateVector);
  52999. uvA = triangle.a.clone().applyQuaternion(quaternion);
  53000. uvB = triangle.b.clone().applyQuaternion(quaternion);
  53001. uvC = triangle.c.clone().applyQuaternion(quaternion);
  53002. // Compute UVs.
  53003. // Normalize x/y values of UV so they are within 0 to 1.
  53004. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  53005. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  53006. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  53007. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  53008. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  53009. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  53010. geometry = this.geometry = new THREE.Geometry();
  53011. geometry.vertices.push(triangle.a);
  53012. geometry.vertices.push(triangle.b);
  53013. geometry.vertices.push(triangle.c);
  53014. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  53015. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  53016. }
  53017. });
  53018. },{"../core/geometry":104,"../lib/three":151}],149:[function(_dereq_,module,exports){
  53019. // Polyfill `Promise`.
  53020. window.Promise = window.Promise || _dereq_('promise-polyfill');
  53021. // WebVR polyfill
  53022. // Check before the polyfill runs.
  53023. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays ||
  53024. !!window.navigator.getVRDevices;
  53025. window.hasNativeWebXRImplementation = navigator.xr !== undefined;
  53026. // If native WebXR or WebVR are defined WebVRPolyfill does not initialize.
  53027. if (!window.hasNativeWebXRImplementation && !window.hasNativeWebVRImplementation) {
  53028. var isIOSOlderThan10 = _dereq_('./utils/isIOSOlderThan10');
  53029. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  53030. // Only for iOS on versions older than 10.
  53031. var bufferScale = isIOSOlderThan10(window.navigator.userAgent) ? 1 / window.devicePixelRatio : 1;
  53032. var WebVRPolyfill = _dereq_('webvr-polyfill');
  53033. var polyfillConfig = {
  53034. BUFFER_SCALE: bufferScale,
  53035. CARDBOARD_UI_DISABLED: true,
  53036. ROTATE_INSTRUCTIONS_DISABLED: true
  53037. };
  53038. window.webvrpolyfill = new WebVRPolyfill(polyfillConfig);
  53039. }
  53040. var utils = _dereq_('./utils/');
  53041. var debug = utils.debug;
  53042. if (utils.isIE11) {
  53043. // Polyfill `CustomEvent`.
  53044. _dereq_('custom-event-polyfill');
  53045. // Polyfill String.startsWith.
  53046. _dereq_('../vendor/starts-with-polyfill');
  53047. }
  53048. var error = debug('A-Frame:error');
  53049. var warn = debug('A-Frame:warn');
  53050. if (window.document.currentScript && window.document.currentScript.parentNode !==
  53051. window.document.head && !window.debug) {
  53052. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  53053. 'ensure everything for A-Frame is properly registered before they are used from ' +
  53054. 'HTML.');
  53055. }
  53056. // Error if not using a server.
  53057. if (window.location.protocol === 'file:') {
  53058. error(
  53059. 'This HTML file is currently being served via the file:// protocol. ' +
  53060. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  53061. 'Please use a local or hosted server: ' +
  53062. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  53063. }
  53064. _dereq_('present'); // Polyfill `performance.now()`.
  53065. // CSS.
  53066. if (utils.device.isBrowserEnvironment) {
  53067. _dereq_('./style/aframe.css');
  53068. _dereq_('./style/rStats.css');
  53069. }
  53070. // Required before `AEntity` so that all components are registered.
  53071. var AScene = _dereq_('./core/scene/a-scene').AScene;
  53072. var components = _dereq_('./core/component').components;
  53073. var registerComponent = _dereq_('./core/component').registerComponent;
  53074. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  53075. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  53076. var registerShader = _dereq_('./core/shader').registerShader;
  53077. var registerSystem = _dereq_('./core/system').registerSystem;
  53078. var shaders = _dereq_('./core/shader').shaders;
  53079. var systems = _dereq_('./core/system').systems;
  53080. // Exports THREE to window so three.js can be used without alteration.
  53081. var THREE = window.THREE = _dereq_('./lib/three');
  53082. var pkg = _dereq_('../package');
  53083. _dereq_('./components/index'); // Register standard components.
  53084. _dereq_('./geometries/index'); // Register standard geometries.
  53085. _dereq_('./shaders/index'); // Register standard shaders.
  53086. _dereq_('./systems/index'); // Register standard systems.
  53087. var ANode = _dereq_('./core/a-node');
  53088. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  53089. _dereq_('./core/a-assets');
  53090. _dereq_('./core/a-cubemap');
  53091. _dereq_('./core/a-mixin');
  53092. // Extras.
  53093. _dereq_('./extras/components/');
  53094. _dereq_('./extras/primitives/');
  53095. console.log('A-Frame Version: 0.9.2 (Date 2019-05-06, Commit #f57a1fa)');
  53096. console.log('three Version (https://github.com/supermedium/three.js):',
  53097. pkg.dependencies['super-three']);
  53098. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  53099. module.exports = window.AFRAME = {
  53100. AComponent: _dereq_('./core/component').Component,
  53101. AEntity: AEntity,
  53102. ANode: ANode,
  53103. ANIME: _dereq_('super-animejs'),
  53104. AScene: AScene,
  53105. components: components,
  53106. coreComponents: Object.keys(components),
  53107. geometries: _dereq_('./core/geometry').geometries,
  53108. registerComponent: registerComponent,
  53109. registerElement: _dereq_('./core/a-register-element').registerElement,
  53110. registerGeometry: registerGeometry,
  53111. registerPrimitive: registerPrimitive,
  53112. registerShader: registerShader,
  53113. registerSystem: registerSystem,
  53114. primitives: {
  53115. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  53116. primitives: _dereq_('./extras/primitives/primitives').primitives
  53117. },
  53118. scenes: _dereq_('./core/scene/scenes'),
  53119. schema: _dereq_('./core/schema'),
  53120. shaders: shaders,
  53121. systems: systems,
  53122. THREE: THREE,
  53123. utils: utils,
  53124. version: pkg.version
  53125. };
  53126. },{"../package":51,"../vendor/starts-with-polyfill":187,"./components/index":60,"./core/a-assets":97,"./core/a-cubemap":98,"./core/a-entity":99,"./core/a-mixin":100,"./core/a-node":101,"./core/a-register-element":102,"./core/component":103,"./core/geometry":104,"./core/scene/a-scene":106,"./core/scene/scenes":110,"./core/schema":112,"./core/shader":113,"./core/system":114,"./extras/components/":115,"./extras/primitives/":118,"./extras/primitives/getMeshMixin":117,"./extras/primitives/primitives":119,"./geometries/index":140,"./lib/three":151,"./shaders/index":153,"./style/aframe.css":158,"./style/rStats.css":159,"./systems/index":163,"./utils/":176,"./utils/isIOSOlderThan10":178,"custom-event-polyfill":7,"present":31,"promise-polyfill":33,"super-animejs":35,"webvr-polyfill":46}],150:[function(_dereq_,module,exports){
  53127. window.aframeStats = function (scene) {
  53128. var _rS = null;
  53129. var _scene = scene;
  53130. var _values = {
  53131. te: {
  53132. caption: 'Entities'
  53133. },
  53134. lt: {
  53135. caption: 'Load Time'
  53136. }
  53137. };
  53138. var _groups = [ {
  53139. caption: 'A-Frame',
  53140. values: [ 'te', 'lt' ]
  53141. } ];
  53142. function _update () {
  53143. _rS('te').set(getEntityCount());
  53144. if (window.performance.getEntriesByName) {
  53145. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  53146. }
  53147. }
  53148. function getEntityCount () {
  53149. var elements = _scene.querySelectorAll('*');
  53150. Array.prototype.slice.call(elements).filter(function (el) {
  53151. return el.isEntity;
  53152. });
  53153. return elements.length;
  53154. }
  53155. function _start () {}
  53156. function _end () {}
  53157. function _attach (r) {
  53158. _rS = r;
  53159. }
  53160. return {
  53161. update: _update,
  53162. start: _start,
  53163. end: _end,
  53164. attach: _attach,
  53165. values: _values,
  53166. groups: _groups,
  53167. fractions: []
  53168. };
  53169. };
  53170. if (typeof module === 'object') {
  53171. module.exports = {
  53172. aframeStats: window.aframeStats
  53173. };
  53174. }
  53175. },{}],151:[function(_dereq_,module,exports){
  53176. (function (global){
  53177. var THREE = global.THREE = _dereq_('super-three');
  53178. // Allow cross-origin images to be loaded.
  53179. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  53180. // Must be on `THREE.TextureLoader`.
  53181. if (THREE.TextureLoader) {
  53182. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  53183. }
  53184. // This is for images loaded from the model loaders.
  53185. if (THREE.ImageLoader) {
  53186. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  53187. }
  53188. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  53189. if (THREE.Cache) {
  53190. THREE.Cache.enabled = true;
  53191. }
  53192. // TODO: Eventually include these only if they are needed by a component.
  53193. _dereq_('super-three/examples/js/loaders/DRACOLoader'); // THREE.DRACOLoader
  53194. _dereq_('super-three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  53195. _dereq_('super-three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  53196. _dereq_('super-three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  53197. THREE.DRACOLoader.prototype.crossOrigin = 'anonymous';
  53198. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  53199. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  53200. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  53201. module.exports = THREE;
  53202. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  53203. },{"super-three":36,"super-three/examples/js/loaders/DRACOLoader":37,"super-three/examples/js/loaders/GLTFLoader":38,"super-three/examples/js/loaders/MTLLoader":39,"super-three/examples/js/loaders/OBJLoader":40}],152:[function(_dereq_,module,exports){
  53204. var registerShader = _dereq_('../core/shader').registerShader;
  53205. var THREE = _dereq_('../lib/three');
  53206. var utils = _dereq_('../utils/');
  53207. /**
  53208. * Flat shader using THREE.MeshBasicMaterial.
  53209. */
  53210. module.exports.Shader = registerShader('flat', {
  53211. schema: {
  53212. color: {type: 'color'},
  53213. fog: {default: true},
  53214. height: {default: 256},
  53215. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53216. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53217. src: {type: 'map'},
  53218. width: {default: 512},
  53219. wireframe: {default: false},
  53220. wireframeLinewidth: {default: 2}
  53221. },
  53222. /**
  53223. * Initializes the shader.
  53224. * Adds a reference from the scene to this entity as the camera.
  53225. */
  53226. init: function (data) {
  53227. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53228. this.materialData = {color: new THREE.Color()};
  53229. this.textureSrc = null;
  53230. getMaterialData(data, this.materialData);
  53231. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53232. this.material = new THREE.MeshBasicMaterial(this.materialData);
  53233. utils.material.updateMap(this, data);
  53234. },
  53235. update: function (data) {
  53236. this.updateMaterial(data);
  53237. utils.material.updateMap(this, data);
  53238. },
  53239. /**
  53240. * Updating existing material.
  53241. *
  53242. * @param {object} data - Material component data.
  53243. */
  53244. updateMaterial: function (data) {
  53245. var key;
  53246. getMaterialData(data, this.materialData);
  53247. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53248. for (key in this.materialData) {
  53249. this.material[key] = this.materialData[key];
  53250. }
  53251. }
  53252. });
  53253. /**
  53254. * Builds and normalize material data, normalizing stuff along the way.
  53255. *
  53256. * @param {object} data - Material data.
  53257. * @param {object} materialData - Object to reuse.
  53258. * @returns {object} Updated material data.
  53259. */
  53260. function getMaterialData (data, materialData) {
  53261. materialData.color.set(data.color);
  53262. materialData.fog = data.fog;
  53263. materialData.wireframe = data.wireframe;
  53264. materialData.wireframeLinewidth = data.wireframeLinewidth;
  53265. return materialData;
  53266. }
  53267. },{"../core/shader":113,"../lib/three":151,"../utils/":176}],153:[function(_dereq_,module,exports){
  53268. _dereq_('./flat');
  53269. _dereq_('./standard');
  53270. _dereq_('./sdf');
  53271. _dereq_('./msdf');
  53272. _dereq_('./ios10hls');
  53273. },{"./flat":152,"./ios10hls":154,"./msdf":155,"./sdf":156,"./standard":157}],154:[function(_dereq_,module,exports){
  53274. var registerShader = _dereq_('../core/shader').registerShader;
  53275. /**
  53276. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  53277. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  53278. */
  53279. module.exports.Shader = registerShader('ios10hls', {
  53280. schema: {
  53281. src: {type: 'map', is: 'uniform'},
  53282. opacity: {type: 'number', is: 'uniform', default: 1}
  53283. },
  53284. vertexShader: [
  53285. 'varying vec2 vUV;',
  53286. 'void main(void) {',
  53287. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53288. ' vUV = uv;',
  53289. '}'
  53290. ].join('\n'),
  53291. fragmentShader: [
  53292. 'uniform sampler2D src;',
  53293. 'uniform float opacity;',
  53294. 'varying vec2 vUV;',
  53295. 'void main() {',
  53296. ' vec2 offset = vec2(0, 0);',
  53297. ' vec2 repeat = vec2(1, 1);',
  53298. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  53299. ' gl_FragColor = vec4(color.rgb, opacity);',
  53300. '}'
  53301. ].join('\n')
  53302. });
  53303. },{"../core/shader":113}],155:[function(_dereq_,module,exports){
  53304. var registerShader = _dereq_('../core/shader').registerShader;
  53305. /**
  53306. * Multi-channel signed distance field.
  53307. * Used by text component.
  53308. */
  53309. module.exports.Shader = registerShader('msdf', {
  53310. schema: {
  53311. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53312. color: {type: 'color', is: 'uniform', default: 'white'},
  53313. map: {type: 'map', is: 'uniform'},
  53314. negate: {type: 'boolean', is: 'uniform', default: true},
  53315. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53316. },
  53317. raw: true,
  53318. vertexShader: [
  53319. 'attribute vec2 uv;',
  53320. 'attribute vec3 position;',
  53321. 'uniform mat4 projectionMatrix;',
  53322. 'uniform mat4 modelViewMatrix;',
  53323. 'varying vec2 vUV;',
  53324. 'void main(void) {',
  53325. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53326. ' vUV = uv;',
  53327. '}'
  53328. ].join('\n'),
  53329. fragmentShader: [
  53330. '#ifdef GL_OES_standard_derivatives',
  53331. '#extension GL_OES_standard_derivatives: enable',
  53332. '#endif',
  53333. 'precision highp float;',
  53334. 'uniform bool negate;',
  53335. 'uniform float alphaTest;',
  53336. 'uniform float opacity;',
  53337. 'uniform sampler2D map;',
  53338. 'uniform vec3 color;',
  53339. 'varying vec2 vUV;',
  53340. 'float median(float r, float g, float b) {',
  53341. ' return max(min(r, g), min(max(r, g), b));',
  53342. '}',
  53343. // FIXME: Experimentally determined constants.
  53344. '#define BIG_ENOUGH 0.001',
  53345. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53346. 'void main() {',
  53347. ' vec3 sample = texture2D(map, vUV).rgb;',
  53348. ' if (negate) { sample = 1.0 - sample; }',
  53349. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  53350. ' float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
  53351. ' float dscale = 0.353505;',
  53352. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  53353. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53354. // When texel is too small, blend raw alpha value rather than supersampling.
  53355. // FIXME: Experimentally determined constant.
  53356. ' // Do modified alpha test.',
  53357. ' if (isBigEnough > BIG_ENOUGH) {',
  53358. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53359. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  53360. ' }',
  53361. ' // Do modified alpha test.',
  53362. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53363. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  53364. '}'
  53365. ].join('\n')
  53366. });
  53367. },{"../core/shader":113}],156:[function(_dereq_,module,exports){
  53368. var registerShader = _dereq_('../core/shader').registerShader;
  53369. /**
  53370. * Signed distance field.
  53371. * Used by text component.
  53372. */
  53373. module.exports.Shader = registerShader('sdf', {
  53374. schema: {
  53375. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53376. color: {type: 'color', is: 'uniform', default: 'white'},
  53377. map: {type: 'map', is: 'uniform'},
  53378. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53379. },
  53380. raw: true,
  53381. vertexShader: [
  53382. 'attribute vec2 uv;',
  53383. 'attribute vec3 position;',
  53384. 'uniform mat4 projectionMatrix;',
  53385. 'uniform mat4 modelViewMatrix;',
  53386. 'varying vec2 vUV;',
  53387. 'void main(void) {',
  53388. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53389. ' vUV = uv;',
  53390. '}'
  53391. ].join('\n'),
  53392. fragmentShader: [
  53393. '#ifdef GL_OES_standard_derivatives',
  53394. '#extension GL_OES_standard_derivatives: enable',
  53395. '#endif',
  53396. 'precision highp float;',
  53397. 'uniform float alphaTest;',
  53398. 'uniform float opacity;',
  53399. 'uniform sampler2D map;',
  53400. 'uniform vec3 color;',
  53401. 'varying vec2 vUV;',
  53402. '#ifdef GL_OES_standard_derivatives',
  53403. ' float contour(float width, float value) {',
  53404. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  53405. ' }',
  53406. '#else',
  53407. ' float aastep(float value, float afwidth) {',
  53408. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  53409. ' }',
  53410. '#endif',
  53411. // FIXME: Experimentally determined constants.
  53412. '#define BIG_ENOUGH 0.001',
  53413. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53414. '#define ALL_SMOOTH 0.4',
  53415. '#define ALL_ROUGH 0.02',
  53416. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53417. 'void main() {',
  53418. // When we have derivatives and can get texel size for supersampling.
  53419. ' #ifdef GL_OES_standard_derivatives',
  53420. ' vec2 uv = vUV;',
  53421. ' vec4 texColor = texture2D(map, uv);',
  53422. ' float dist = texColor.a;',
  53423. ' float width = fwidth(dist);',
  53424. ' float alpha = contour(dist, width);',
  53425. ' float dscale = 0.353505;',
  53426. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  53427. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53428. // When texel is too small, blend raw alpha value rather than supersampling.
  53429. // FIXME: experimentally determined constant
  53430. ' if (isBigEnough > BIG_ENOUGH) {',
  53431. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53432. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  53433. ' }',
  53434. // Otherwise do weighted supersampling.
  53435. // FIXME: why this weighting?
  53436. ' if (isBigEnough <= BIG_ENOUGH) {',
  53437. ' vec4 box = vec4 (uv - duv, uv + duv);',
  53438. ' alpha = (alpha + 0.5 * (',
  53439. ' contour(texture2D(map, box.xy).a, width)',
  53440. ' + contour(texture2D(map, box.zw).a, width)',
  53441. ' + contour(texture2D(map, box.xw).a, width)',
  53442. ' + contour(texture2D(map, box.zy).a, width)',
  53443. ' )) / 3.0;',
  53444. ' }',
  53445. // Do modified alpha test.
  53446. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53447. ' #else',
  53448. // When we don't have derivatives, use approximations.
  53449. ' vec4 texColor = texture2D(map, vUV);',
  53450. ' float value = texColor.a;',
  53451. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53452. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  53453. ' float alpha = aastep(value, afwidth);',
  53454. // Use gl_FragCoord.w to guess when we should blend.
  53455. // FIXME: If we understood font pixel dimensions, this could probably be improved.
  53456. ' 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);',
  53457. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  53458. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  53459. ' if (ratio < 1.0 && alpha <= DISCARD_ALPHA) { discard; return; }',
  53460. ' #endif',
  53461. ' gl_FragColor = vec4(color, opacity * alpha);',
  53462. '}'
  53463. ].join('\n')
  53464. });
  53465. },{"../core/shader":113}],157:[function(_dereq_,module,exports){
  53466. var registerShader = _dereq_('../core/shader').registerShader;
  53467. var THREE = _dereq_('../lib/three');
  53468. var utils = _dereq_('../utils/');
  53469. var CubeLoader = new THREE.CubeTextureLoader();
  53470. var texturePromises = {};
  53471. /**
  53472. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  53473. */
  53474. module.exports.Shader = registerShader('standard', {
  53475. schema: {
  53476. ambientOcclusionMap: {type: 'map'},
  53477. ambientOcclusionMapIntensity: {default: 1},
  53478. ambientOcclusionTextureOffset: {type: 'vec2'},
  53479. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53480. color: {type: 'color'},
  53481. displacementMap: {type: 'map'},
  53482. displacementScale: {default: 1},
  53483. displacementBias: {default: 0.5},
  53484. displacementTextureOffset: {type: 'vec2'},
  53485. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53486. emissive: {type: 'color', default: '#000'},
  53487. emissiveIntensity: {default: 1},
  53488. envMap: {default: ''},
  53489. fog: {default: true},
  53490. height: {default: 256},
  53491. metalness: {default: 0.0, min: 0.0, max: 1.0},
  53492. metalnessMap: {type: 'map'},
  53493. metalnessTextureOffset: {type: 'vec2'},
  53494. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53495. normalMap: {type: 'map'},
  53496. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  53497. normalTextureOffset: {type: 'vec2'},
  53498. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53499. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53500. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53501. roughness: {default: 0.5, min: 0.0, max: 1.0},
  53502. roughnessMap: {type: 'map'},
  53503. roughnessTextureOffset: {type: 'vec2'},
  53504. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53505. sphericalEnvMap: {type: 'map'},
  53506. src: {type: 'map'},
  53507. width: {default: 512},
  53508. wireframe: {default: false},
  53509. wireframeLinewidth: {default: 2}
  53510. },
  53511. /**
  53512. * Initializes the shader.
  53513. * Adds a reference from the scene to this entity as the camera.
  53514. */
  53515. init: function (data) {
  53516. this.rendererSystem = this.el.sceneEl.systems.renderer;
  53517. this.materialData = {color: new THREE.Color(), emissive: new THREE.Color()};
  53518. getMaterialData(data, this.materialData);
  53519. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53520. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  53521. this.material = new THREE.MeshStandardMaterial(this.materialData);
  53522. utils.material.updateMap(this, data);
  53523. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53524. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53525. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53526. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  53527. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  53528. this.updateEnvMap(data);
  53529. },
  53530. update: function (data) {
  53531. this.updateMaterial(data);
  53532. utils.material.updateMap(this, data);
  53533. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53534. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53535. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53536. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  53537. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  53538. this.updateEnvMap(data);
  53539. },
  53540. /**
  53541. * Updating existing material.
  53542. *
  53543. * @param {object} data - Material component data.
  53544. * @returns {object} Material.
  53545. */
  53546. updateMaterial: function (data) {
  53547. var key;
  53548. var material = this.material;
  53549. getMaterialData(data, this.materialData);
  53550. this.rendererSystem.applyColorCorrection(this.materialData.color);
  53551. this.rendererSystem.applyColorCorrection(this.materialData.emissive);
  53552. for (key in this.materialData) {
  53553. material[key] = this.materialData[key];
  53554. }
  53555. },
  53556. /**
  53557. * Handle environment cubemap. Textures are cached in texturePromises.
  53558. */
  53559. updateEnvMap: function (data) {
  53560. var self = this;
  53561. var material = this.material;
  53562. var envMap = data.envMap;
  53563. var sphericalEnvMap = data.sphericalEnvMap;
  53564. // No envMap defined or already loading.
  53565. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  53566. material.envMap = null;
  53567. material.needsUpdate = true;
  53568. return;
  53569. }
  53570. this.isLoadingEnvMap = true;
  53571. // if a spherical env map is defined then use it.
  53572. if (sphericalEnvMap) {
  53573. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  53574. self.isLoadingEnvMap = false;
  53575. texture.mapping = THREE.SphericalReflectionMapping;
  53576. material.envMap = texture;
  53577. utils.material.handleTextureEvents(self.el, texture);
  53578. material.needsUpdate = true;
  53579. });
  53580. return;
  53581. }
  53582. // Another material is already loading this texture. Wait on promise.
  53583. if (texturePromises[envMap]) {
  53584. texturePromises[envMap].then(function (cube) {
  53585. self.isLoadingEnvMap = false;
  53586. material.envMap = cube;
  53587. utils.material.handleTextureEvents(self.el, cube);
  53588. material.needsUpdate = true;
  53589. });
  53590. return;
  53591. }
  53592. // Material is first to load this texture. Load and resolve texture.
  53593. texturePromises[envMap] = new Promise(function (resolve) {
  53594. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  53595. CubeLoader.load(urls, function (cube) {
  53596. // Texture loaded.
  53597. self.isLoadingEnvMap = false;
  53598. material.envMap = cube;
  53599. utils.material.handleTextureEvents(self.el, cube);
  53600. resolve(cube);
  53601. });
  53602. });
  53603. });
  53604. }
  53605. });
  53606. /**
  53607. * Builds and normalize material data, normalizing stuff along the way.
  53608. *
  53609. * @param {object} data - Material data.
  53610. * @param {object} materialData - Object to use.
  53611. * @returns {object} Updated materialData.
  53612. */
  53613. function getMaterialData (data, materialData) {
  53614. materialData.color.set(data.color);
  53615. materialData.emissive.set(data.emissive);
  53616. materialData.emissiveIntensity = data.emissiveIntensity;
  53617. materialData.fog = data.fog;
  53618. materialData.metalness = data.metalness;
  53619. materialData.roughness = data.roughness;
  53620. materialData.wireframe = data.wireframe;
  53621. materialData.wireframeLinewidth = data.wireframeLinewidth;
  53622. if (data.normalMap) { materialData.normalScale = data.normalScale; }
  53623. if (data.ambientOcclusionMap) {
  53624. materialData.aoMapIntensity = data.ambientOcclusionMapIntensity;
  53625. }
  53626. if (data.displacementMap) {
  53627. materialData.displacementScale = data.displacementScale;
  53628. materialData.displacementBias = data.displacementBias;
  53629. }
  53630. return materialData;
  53631. }
  53632. },{"../core/shader":113,"../lib/three":151,"../utils/":176}],158:[function(_dereq_,module,exports){
  53633. 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;
  53634. },{"browserify-css":4}],159:[function(_dereq_,module,exports){
  53635. 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;
  53636. },{"browserify-css":4}],160:[function(_dereq_,module,exports){
  53637. var constants = _dereq_('../constants/');
  53638. var registerSystem = _dereq_('../core/system').registerSystem;
  53639. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  53640. /**
  53641. * Camera system. Manages which camera is active among multiple cameras in scene.
  53642. *
  53643. * @member {object} activeCameraEl - Active camera entity.
  53644. */
  53645. module.exports.System = registerSystem('camera', {
  53646. init: function () {
  53647. this.activeCameraEl = null;
  53648. this.render = this.render.bind(this);
  53649. this.unwrapRender = this.unwrapRender.bind(this);
  53650. this.wrapRender = this.wrapRender.bind(this);
  53651. this.initialCameraFound = false;
  53652. this.numUserCameras = 0;
  53653. this.numUserCamerasChecked = 0;
  53654. this.setupInitialCamera();
  53655. },
  53656. /**
  53657. * Setup initial camera, either searching for camera or
  53658. * creating a default camera if user has not added one during the initial scene traversal.
  53659. * We want sceneEl.camera to be ready, set, and initialized before the rest of the scene
  53660. * loads.
  53661. *
  53662. * Default camera offset height is at average eye level (~1.6m).
  53663. */
  53664. setupInitialCamera: function () {
  53665. var cameraEls;
  53666. var i;
  53667. var sceneEl = this.sceneEl;
  53668. var self = this;
  53669. // Camera already defined or the one defined it is an spectator one.
  53670. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  53671. sceneEl.emit('cameraready', {cameraEl: sceneEl.camera.el});
  53672. return;
  53673. }
  53674. // Search for initial user-defined camera.
  53675. cameraEls = sceneEl.querySelectorAll('a-camera, [camera]');
  53676. // No user cameras, create default one.
  53677. if (!cameraEls.length) {
  53678. this.createDefaultCamera();
  53679. return;
  53680. }
  53681. this.numUserCameras = cameraEls.length;
  53682. for (i = 0; i < cameraEls.length; i++) {
  53683. cameraEls[i].addEventListener('object3dset', function (evt) {
  53684. if (evt.detail.type !== 'camera') { return; }
  53685. self.checkUserCamera(this);
  53686. });
  53687. // Load camera and wait for camera to initialize.
  53688. if (cameraEls[i].isNode) {
  53689. cameraEls[i].load();
  53690. } else {
  53691. cameraEls[i].addEventListener('nodeready', function () {
  53692. this.load();
  53693. });
  53694. }
  53695. }
  53696. },
  53697. /**
  53698. * Check if a user-defined camera entity is appropriate to be initial camera.
  53699. * (active + non-spectator).
  53700. *
  53701. * Keep track of the number of cameras we checked and whether we found one.
  53702. */
  53703. checkUserCamera: function (cameraEl) {
  53704. var cameraData;
  53705. var sceneEl = this.el.sceneEl;
  53706. this.numUserCamerasChecked++;
  53707. // Already found one.
  53708. if (this.initialCameraFound) { return; }
  53709. // Check if camera is appropriate for being the initial camera.
  53710. cameraData = cameraEl.getAttribute('camera');
  53711. if (!cameraData.active || cameraData.spectator) {
  53712. // No user cameras eligible, create default camera.
  53713. if (this.numUserCamerasChecked === this.numUserCameras) {
  53714. this.createDefaultCamera();
  53715. }
  53716. return;
  53717. }
  53718. this.initialCameraFound = true;
  53719. sceneEl.camera = cameraEl.getObject3D('camera');
  53720. sceneEl.emit('cameraready', {cameraEl: cameraEl});
  53721. },
  53722. createDefaultCamera: function () {
  53723. var defaultCameraEl;
  53724. var sceneEl = this.sceneEl;
  53725. // Set up default camera.
  53726. defaultCameraEl = document.createElement('a-entity');
  53727. defaultCameraEl.setAttribute('camera', {active: true});
  53728. defaultCameraEl.setAttribute('position', {
  53729. x: 0,
  53730. y: constants.DEFAULT_CAMERA_HEIGHT,
  53731. z: 0
  53732. });
  53733. defaultCameraEl.setAttribute('wasd-controls', '');
  53734. defaultCameraEl.setAttribute('look-controls', '');
  53735. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  53736. defaultCameraEl.addEventListener('object3dset', function (evt) {
  53737. if (evt.detail.type !== 'camera') { return; }
  53738. sceneEl.camera = evt.detail.object;
  53739. sceneEl.emit('cameraready', {cameraEl: defaultCameraEl});
  53740. });
  53741. sceneEl.appendChild(defaultCameraEl);
  53742. },
  53743. /**
  53744. * Set a different active camera.
  53745. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  53746. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  53747. * the new camera.
  53748. */
  53749. disableActiveCamera: function () {
  53750. var cameraEls;
  53751. var newActiveCameraEl;
  53752. cameraEls = this.sceneEl.querySelectorAll('[camera]');
  53753. newActiveCameraEl = cameraEls[cameraEls.length - 1];
  53754. newActiveCameraEl.setAttribute('camera', 'active', true);
  53755. },
  53756. /**
  53757. * Set active camera to be used by renderer.
  53758. * Removes the default camera (if present).
  53759. * Disables all other cameras in the scene.
  53760. *
  53761. * @param {Element} newCameraEl - Entity with camera component.
  53762. */
  53763. setActiveCamera: function (newCameraEl) {
  53764. var cameraEl;
  53765. var cameraEls;
  53766. var i;
  53767. var newCamera;
  53768. var previousCamera = this.activeCameraEl;
  53769. var sceneEl = this.sceneEl;
  53770. // Same camera.
  53771. newCamera = newCameraEl.getObject3D('camera');
  53772. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  53773. // Grab the default camera.
  53774. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53775. var defaultCameraEl = defaultCameraWrapper &&
  53776. defaultCameraWrapper.querySelector('[camera]');
  53777. // Remove default camera if new camera is not the default camera.
  53778. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  53779. // Make new camera active.
  53780. this.activeCameraEl = newCameraEl;
  53781. this.activeCameraEl.play();
  53782. sceneEl.camera = newCamera;
  53783. // Disable current camera
  53784. if (previousCamera) {
  53785. previousCamera.setAttribute('camera', 'active', false);
  53786. }
  53787. // Disable other cameras in the scene
  53788. cameraEls = sceneEl.querySelectorAll('[camera]');
  53789. for (i = 0; i < cameraEls.length; i++) {
  53790. cameraEl = cameraEls[i];
  53791. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  53792. cameraEl.setAttribute('camera', 'active', false);
  53793. cameraEl.pause();
  53794. }
  53795. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  53796. },
  53797. /**
  53798. * Set spectator camera to render the scene on a 2D display.
  53799. *
  53800. * @param {Element} newCameraEl - Entity with camera component.
  53801. */
  53802. setSpectatorCamera: function (newCameraEl) {
  53803. var newCamera;
  53804. var previousCamera = this.spectatorCameraEl;
  53805. var sceneEl = this.sceneEl;
  53806. var spectatorCameraEl;
  53807. // Same camera.
  53808. newCamera = newCameraEl.getObject3D('camera');
  53809. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  53810. // Disable current camera
  53811. if (previousCamera) {
  53812. previousCamera.setAttribute('camera', 'spectator', false);
  53813. }
  53814. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  53815. sceneEl.addEventListener('enter-vr', this.wrapRender);
  53816. sceneEl.addEventListener('exit-vr', this.unwrapRender);
  53817. spectatorCameraEl.setAttribute('camera', 'active', false);
  53818. spectatorCameraEl.play();
  53819. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  53820. },
  53821. /**
  53822. * Disables current spectator camera.
  53823. */
  53824. disableSpectatorCamera: function () {
  53825. this.spectatorCameraEl = undefined;
  53826. },
  53827. /**
  53828. * Wrap the render method of the renderer to render
  53829. * the spectator camera after vrDisplay.submitFrame.
  53830. */
  53831. wrapRender: function () {
  53832. if (!this.spectatorCameraEl) { return; }
  53833. this.originalRender = this.sceneEl.renderer.render;
  53834. this.sceneEl.renderer.render = this.render;
  53835. },
  53836. unwrapRender: function () {
  53837. if (!this.originalRender) { return; }
  53838. this.sceneEl.renderer.render = this.originalRender;
  53839. this.originalRender = undefined;
  53840. },
  53841. render: function (scene, camera) {
  53842. var isVREnabled;
  53843. var sceneEl = this.sceneEl;
  53844. var spectatorCamera;
  53845. isVREnabled = sceneEl.renderer.vr.enabled;
  53846. this.originalRender.call(sceneEl.renderer, scene, camera);
  53847. if (!this.spectatorCameraEl || sceneEl.isMobile || !isVREnabled) { return; }
  53848. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  53849. sceneEl.renderer.vr.enabled = false;
  53850. this.originalRender.call(sceneEl.renderer, scene, spectatorCamera);
  53851. sceneEl.renderer.vr.enabled = isVREnabled;
  53852. }
  53853. });
  53854. /**
  53855. * Remove injected default camera from scene, if present.
  53856. *
  53857. * @param {Element} sceneEl
  53858. */
  53859. function removeDefaultCamera (sceneEl) {
  53860. var defaultCamera;
  53861. var camera = sceneEl.camera;
  53862. if (!camera) { return; }
  53863. // Remove default camera if present.
  53864. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  53865. if (!defaultCamera) { return; }
  53866. sceneEl.removeChild(defaultCamera);
  53867. }
  53868. },{"../constants/":95,"../core/system":114}],161:[function(_dereq_,module,exports){
  53869. var geometries = _dereq_('../core/geometry').geometries;
  53870. var registerSystem = _dereq_('../core/system').registerSystem;
  53871. var THREE = _dereq_('../lib/three');
  53872. /**
  53873. * System for geometry component.
  53874. * Handle geometry caching.
  53875. *
  53876. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  53877. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  53878. * know whether to dispose on removal.
  53879. */
  53880. module.exports.System = registerSystem('geometry', {
  53881. init: function () {
  53882. this.cache = {};
  53883. this.cacheCount = {};
  53884. },
  53885. /**
  53886. * Reset cache. Mainly for testing.
  53887. */
  53888. clearCache: function () {
  53889. this.cache = {};
  53890. this.cacheCount = {};
  53891. },
  53892. /**
  53893. * Attempt to retrieve from cache.
  53894. *
  53895. * @returns {Object|null} A geometry if it exists, else null.
  53896. */
  53897. getOrCreateGeometry: function (data) {
  53898. var cache = this.cache;
  53899. var cachedGeometry;
  53900. var hash;
  53901. // Skip all caching logic.
  53902. if (data.skipCache) { return createGeometry(data); }
  53903. // Try to retrieve from cache first.
  53904. hash = this.hash(data);
  53905. cachedGeometry = cache[hash];
  53906. incrementCacheCount(this.cacheCount, hash);
  53907. if (cachedGeometry) { return cachedGeometry; }
  53908. // Create geometry.
  53909. cachedGeometry = createGeometry(data);
  53910. // Cache and return geometry.
  53911. cache[hash] = cachedGeometry;
  53912. return cachedGeometry;
  53913. },
  53914. /**
  53915. * Let system know that an entity is no longer using a geometry.
  53916. */
  53917. unuseGeometry: function (data) {
  53918. var cache = this.cache;
  53919. var cacheCount = this.cacheCount;
  53920. var geometry;
  53921. var hash;
  53922. if (data.skipCache) { return; }
  53923. hash = this.hash(data);
  53924. if (!cache[hash]) { return; }
  53925. decrementCacheCount(cacheCount, hash);
  53926. // Another entity is still using this geometry. No need to do anything.
  53927. if (cacheCount[hash] > 0) { return; }
  53928. // No more entities are using this geometry. Dispose.
  53929. geometry = cache[hash];
  53930. geometry.dispose();
  53931. delete cache[hash];
  53932. delete cacheCount[hash];
  53933. },
  53934. /**
  53935. * Use JSON.stringify to turn component data into hash.
  53936. * Should be deterministic within a single browser engine.
  53937. * If not, then look into json-stable-stringify.
  53938. */
  53939. hash: function (data) {
  53940. return JSON.stringify(data);
  53941. }
  53942. });
  53943. /**
  53944. * Create geometry using component data.
  53945. *
  53946. * @param {object} data - Component data.
  53947. * @returns {object} Geometry.
  53948. */
  53949. function createGeometry (data) {
  53950. var geometryType = data.primitive;
  53951. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  53952. var geometryInstance = new GeometryClass();
  53953. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  53954. geometryInstance.init(data);
  53955. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  53956. }
  53957. /**
  53958. * Decreate count of entity using a geometry.
  53959. */
  53960. function decrementCacheCount (cacheCount, hash) {
  53961. cacheCount[hash]--;
  53962. }
  53963. /**
  53964. * Increase count of entity using a geometry.
  53965. */
  53966. function incrementCacheCount (cacheCount, hash) {
  53967. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  53968. }
  53969. /**
  53970. * Transform geometry to BufferGeometry if `doBuffer`.
  53971. *
  53972. * @param {object} geometry
  53973. * @param {boolean} doBuffer
  53974. * @returns {object} Geometry.
  53975. */
  53976. function toBufferGeometry (geometry, doBuffer) {
  53977. var bufferGeometry;
  53978. if (!doBuffer) { return geometry; }
  53979. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  53980. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  53981. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  53982. return bufferGeometry;
  53983. }
  53984. },{"../core/geometry":104,"../core/system":114,"../lib/three":151}],162:[function(_dereq_,module,exports){
  53985. var registerSystem = _dereq_('../core/system').registerSystem;
  53986. var THREE = _dereq_('../lib/three');
  53987. /**
  53988. * glTF model system.
  53989. *
  53990. * Configures glTF loading options. Models using glTF compression require that a Draco decoder be
  53991. * provided externally.
  53992. *
  53993. * @param {string} dracoDecoderPath - Base path from which to load Draco decoder library.
  53994. */
  53995. module.exports.System = registerSystem('gltf-model', {
  53996. schema: {
  53997. dracoDecoderPath: {default: ''}
  53998. },
  53999. init: function () {
  54000. var path = this.data.dracoDecoderPath;
  54001. THREE.DRACOLoader.setDecoderPath(path);
  54002. this.dracoLoader = path ? new THREE.DRACOLoader() : null;
  54003. },
  54004. update: function () {
  54005. var path;
  54006. if (this.dracoLoader) { return; }
  54007. path = this.data.dracoDecoderPath;
  54008. THREE.DRACOLoader.setDecoderPath(path);
  54009. this.dracoLoader = path ? new THREE.DRACOLoader() : null;
  54010. },
  54011. getDRACOLoader: function () {
  54012. return this.dracoLoader;
  54013. }
  54014. });
  54015. },{"../core/system":114,"../lib/three":151}],163:[function(_dereq_,module,exports){
  54016. _dereq_('./camera');
  54017. _dereq_('./geometry');
  54018. _dereq_('./gltf-model');
  54019. _dereq_('./light');
  54020. _dereq_('./material');
  54021. _dereq_('./renderer');
  54022. _dereq_('./shadow');
  54023. _dereq_('./tracked-controls-webvr');
  54024. _dereq_('./tracked-controls-webxr');
  54025. },{"./camera":160,"./geometry":161,"./gltf-model":162,"./light":164,"./material":165,"./renderer":166,"./shadow":167,"./tracked-controls-webvr":168,"./tracked-controls-webxr":169}],164:[function(_dereq_,module,exports){
  54026. var registerSystem = _dereq_('../core/system').registerSystem;
  54027. var bind = _dereq_('../utils/bind');
  54028. var constants = _dereq_('../constants/');
  54029. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  54030. /**
  54031. * Light system.
  54032. *
  54033. * Prescribes default lighting if not specified (one ambient, one directional).
  54034. * Removes default lighting from the scene when a new light is added.
  54035. *
  54036. * @param {bool} defaultLights - Whether default lighting are defined.
  54037. * @param {bool} userDefinedLights - Whether user lighting is defined.
  54038. */
  54039. module.exports.System = registerSystem('light', {
  54040. schema: {
  54041. defaultLightsEnabled: {default: true}
  54042. },
  54043. init: function () {
  54044. this.defaultLights = false;
  54045. this.userDefinedLights = false;
  54046. // Wait for all entities to fully load before checking for existence of lights.
  54047. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  54048. // will do so asynchronously.
  54049. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  54050. },
  54051. /**
  54052. * Notify scene that light has been added and to remove the default.
  54053. *
  54054. * @param {object} el - element holding the light component.
  54055. */
  54056. registerLight: function (el) {
  54057. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  54058. // User added a light, remove default lights through DOM.
  54059. this.removeDefaultLights();
  54060. this.userDefinedLights = true;
  54061. }
  54062. },
  54063. removeDefaultLights: function () {
  54064. var defaultLights;
  54065. var sceneEl = this.sceneEl;
  54066. if (!this.defaultLights) { return; }
  54067. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  54068. for (var i = 0; i < defaultLights.length; i++) {
  54069. sceneEl.removeChild(defaultLights[i]);
  54070. }
  54071. this.defaultLights = false;
  54072. },
  54073. /**
  54074. * Prescibe default lights to the scene.
  54075. * Does so by injecting markup such that this state is not invisible.
  54076. * These lights are removed if the user adds any lights.
  54077. */
  54078. setupDefaultLights: function () {
  54079. var sceneEl = this.sceneEl;
  54080. var ambientLight;
  54081. var directionalLight;
  54082. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  54083. return;
  54084. }
  54085. ambientLight = document.createElement('a-entity');
  54086. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  54087. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54088. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  54089. sceneEl.appendChild(ambientLight);
  54090. directionalLight = document.createElement('a-entity');
  54091. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  54092. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  54093. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54094. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  54095. sceneEl.appendChild(directionalLight);
  54096. this.defaultLights = true;
  54097. }
  54098. });
  54099. },{"../constants/":95,"../core/system":114,"../utils/bind":170}],165:[function(_dereq_,module,exports){
  54100. var registerSystem = _dereq_('../core/system').registerSystem;
  54101. var THREE = _dereq_('../lib/three');
  54102. var utils = _dereq_('../utils/');
  54103. var isHLS = _dereq_('../utils/material').isHLS;
  54104. var bind = utils.bind;
  54105. var debug = utils.debug;
  54106. var error = debug('components:texture:error');
  54107. var TextureLoader = new THREE.TextureLoader();
  54108. var warn = debug('components:texture:warn');
  54109. TextureLoader.setCrossOrigin('anonymous');
  54110. /**
  54111. * System for material component.
  54112. * Handle material registration, updates (for fog), and texture caching.
  54113. *
  54114. * @member {object} materials - Registered materials.
  54115. * @member {object} textureCounts - Number of times each texture is used. Tracked
  54116. * separately from textureCache, because the cache (1) is populated in
  54117. * multiple places, and (2) may be cleared at any time.
  54118. * @member {object} textureCache - Texture cache for:
  54119. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  54120. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  54121. */
  54122. module.exports.System = registerSystem('material', {
  54123. init: function () {
  54124. this.materials = {};
  54125. this.textureCounts = {};
  54126. this.textureCache = {};
  54127. this.sceneEl.addEventListener(
  54128. 'materialtextureloaded',
  54129. bind(this.onMaterialTextureLoaded, this)
  54130. );
  54131. },
  54132. clearTextureCache: function () {
  54133. this.textureCache = {};
  54134. },
  54135. /**
  54136. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  54137. *
  54138. * @param {string, or element} src - Texture URL or element.
  54139. * @param {string} data - Relevant texture data used for caching.
  54140. * @param {function} cb - Callback to pass texture to.
  54141. */
  54142. loadTexture: function (src, data, cb) {
  54143. var self = this;
  54144. // Canvas.
  54145. if (src.tagName === 'CANVAS') {
  54146. this.loadCanvas(src, data, cb);
  54147. return;
  54148. }
  54149. // Video element.
  54150. if (src.tagName === 'VIDEO') {
  54151. if (!src.src && !src.srcObject && !src.childElementCount) {
  54152. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  54153. }
  54154. this.loadVideo(src, data, cb);
  54155. return;
  54156. }
  54157. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  54158. function loadImageCb (src) { self.loadImage(src, data, cb); }
  54159. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  54160. },
  54161. /**
  54162. * High-level function for loading image textures (THREE.Texture).
  54163. *
  54164. * @param {Element|string} src - Texture source.
  54165. * @param {object} data - Texture data.
  54166. * @param {function} cb - Callback to pass texture to.
  54167. */
  54168. loadImage: function (src, data, handleImageTextureLoaded) {
  54169. var hash = this.hash(data);
  54170. var textureCache = this.textureCache;
  54171. // Texture already being loaded or already loaded. Wait on promise.
  54172. if (textureCache[hash]) {
  54173. textureCache[hash].then(handleImageTextureLoaded);
  54174. return;
  54175. }
  54176. // Texture not yet being loaded. Start loading it.
  54177. textureCache[hash] = loadImageTexture(src, data);
  54178. textureCache[hash].then(handleImageTextureLoaded);
  54179. },
  54180. /**
  54181. * High-level function for loading canvas textures (THREE.Texture).
  54182. *
  54183. * @param {Element|string} src - Texture source.
  54184. * @param {object} data - Texture data.
  54185. * @param {function} cb - Callback to pass texture to.
  54186. */
  54187. loadCanvas: function (src, data, cb) {
  54188. var texture;
  54189. texture = new THREE.CanvasTexture(src);
  54190. setTextureProperties(texture, data);
  54191. cb(texture);
  54192. },
  54193. /**
  54194. * Load video texture (THREE.VideoTexture).
  54195. * Which is just an image texture that RAFs + needsUpdate.
  54196. * Note that creating a video texture is synchronous unlike loading an image texture.
  54197. * Made asynchronous to be consistent with image textures.
  54198. *
  54199. * @param {Element|string} src - Texture source.
  54200. * @param {object} data - Texture data.
  54201. * @param {function} cb - Callback to pass texture to.
  54202. */
  54203. loadVideo: function (src, data, cb) {
  54204. var hash;
  54205. var texture;
  54206. var textureCache = this.textureCache;
  54207. var videoEl;
  54208. var videoTextureResult;
  54209. function handleVideoTextureLoaded (result) {
  54210. result.texture.needsUpdate = true;
  54211. cb(result.texture, result.videoEl);
  54212. }
  54213. // Video element provided.
  54214. if (typeof src !== 'string') {
  54215. // Check cache before creating texture.
  54216. videoEl = src;
  54217. hash = this.hashVideo(data, videoEl);
  54218. if (textureCache[hash]) {
  54219. textureCache[hash].then(handleVideoTextureLoaded);
  54220. return;
  54221. }
  54222. // If not in cache, fix up the attributes then start to create the texture.
  54223. fixVideoAttributes(videoEl);
  54224. }
  54225. // Only URL provided. Use video element to create texture.
  54226. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  54227. // Generated video element already cached. Use that.
  54228. hash = this.hashVideo(data, videoEl);
  54229. if (textureCache[hash]) {
  54230. textureCache[hash].then(handleVideoTextureLoaded);
  54231. return;
  54232. }
  54233. // Create new video texture.
  54234. texture = new THREE.VideoTexture(videoEl);
  54235. texture.minFilter = THREE.LinearFilter;
  54236. setTextureProperties(texture, data);
  54237. // If iOS and video is HLS, do some hacks.
  54238. if (this.sceneEl.isIOS &&
  54239. isHLS(videoEl.src || videoEl.getAttribute('src'),
  54240. videoEl.type || videoEl.getAttribute('type'))) {
  54241. // Actually BGRA. Tell shader to correct later.
  54242. texture.format = THREE.RGBAFormat;
  54243. texture.needsCorrectionBGRA = true;
  54244. // Apparently needed for HLS. Tell shader to correct later.
  54245. texture.flipY = false;
  54246. texture.needsCorrectionFlipY = true;
  54247. }
  54248. // Cache as promise to be consistent with image texture caching.
  54249. videoTextureResult = {texture: texture, videoEl: videoEl};
  54250. textureCache[hash] = Promise.resolve(videoTextureResult);
  54251. handleVideoTextureLoaded(videoTextureResult);
  54252. },
  54253. /**
  54254. * Create a hash of the material properties for texture cache key.
  54255. */
  54256. hash: function (data) {
  54257. if (data.src.tagName) {
  54258. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  54259. data = utils.extendDeep({}, data);
  54260. data.src = data.src.src;
  54261. }
  54262. return JSON.stringify(data);
  54263. },
  54264. hashVideo: function (data, videoEl) {
  54265. return calculateVideoCacheHash(data, videoEl);
  54266. },
  54267. /**
  54268. * Keep track of material in case an update trigger is needed (e.g., fog).
  54269. *
  54270. * @param {object} material
  54271. */
  54272. registerMaterial: function (material) {
  54273. this.materials[material.uuid] = material;
  54274. },
  54275. /**
  54276. * Stop tracking material, and dispose of any textures not being used by
  54277. * another material component.
  54278. *
  54279. * @param {object} material
  54280. */
  54281. unregisterMaterial: function (material) {
  54282. delete this.materials[material.uuid];
  54283. // If any textures on this material are no longer in use, dispose of them.
  54284. var textureCounts = this.textureCounts;
  54285. Object.keys(material)
  54286. .filter(function (propName) {
  54287. return material[propName] && material[propName].isTexture;
  54288. })
  54289. .forEach(function (mapName) {
  54290. textureCounts[material[mapName].uuid]--;
  54291. if (textureCounts[material[mapName].uuid] <= 0) {
  54292. material[mapName].dispose();
  54293. }
  54294. });
  54295. },
  54296. /**
  54297. * Trigger update to all registered materials.
  54298. */
  54299. updateMaterials: function (material) {
  54300. var materials = this.materials;
  54301. Object.keys(materials).forEach(function (uuid) {
  54302. materials[uuid].needsUpdate = true;
  54303. });
  54304. },
  54305. /**
  54306. * Track textures used by material components, so that they can be safely
  54307. * disposed when no longer in use. Textures must be registered here, and not
  54308. * through registerMaterial(), because textures may not be attached at the
  54309. * time the material is registered.
  54310. *
  54311. * @param {Event} e
  54312. */
  54313. onMaterialTextureLoaded: function (e) {
  54314. if (!this.textureCounts[e.detail.texture.uuid]) {
  54315. this.textureCounts[e.detail.texture.uuid] = 0;
  54316. }
  54317. this.textureCounts[e.detail.texture.uuid]++;
  54318. }
  54319. });
  54320. /**
  54321. * Calculates consistent hash from a video element using its attributes.
  54322. * If the video element has an ID, use that.
  54323. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  54324. *
  54325. * @param data {object} - Texture data such as repeat.
  54326. * @param videoEl {Element} - Video element.
  54327. * @returns {string}
  54328. */
  54329. function calculateVideoCacheHash (data, videoEl) {
  54330. var i;
  54331. var id = videoEl.getAttribute('id');
  54332. var hash;
  54333. var videoAttributes;
  54334. if (id) { return id; }
  54335. // Calculate hash using sorted video attributes.
  54336. hash = '';
  54337. videoAttributes = data || {};
  54338. for (i = 0; i < videoEl.attributes.length; i++) {
  54339. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  54340. }
  54341. Object.keys(videoAttributes).sort().forEach(function (name) {
  54342. hash += name + ':' + videoAttributes[name] + ';';
  54343. });
  54344. return hash;
  54345. }
  54346. /**
  54347. * Load image texture.
  54348. *
  54349. * @private
  54350. * @param {string|object} src - An <img> element or url to an image file.
  54351. * @param {object} data - Data to set texture properties like `repeat`.
  54352. * @returns {Promise} Resolves once texture is loaded.
  54353. */
  54354. function loadImageTexture (src, data) {
  54355. return new Promise(doLoadImageTexture);
  54356. function doLoadImageTexture (resolve, reject) {
  54357. var isEl = typeof src !== 'string';
  54358. function resolveTexture (texture) {
  54359. setTextureProperties(texture, data);
  54360. texture.needsUpdate = true;
  54361. resolve(texture);
  54362. }
  54363. // Create texture from an element.
  54364. if (isEl) {
  54365. resolveTexture(new THREE.Texture(src));
  54366. return;
  54367. }
  54368. // Request and load texture from src string. THREE will create underlying element.
  54369. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  54370. TextureLoader.load(
  54371. src,
  54372. resolveTexture,
  54373. function () { /* no-op */ },
  54374. function (xhr) {
  54375. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  54376. xhr.statusText);
  54377. }
  54378. );
  54379. }
  54380. }
  54381. /**
  54382. * Set texture properties such as repeat and offset.
  54383. *
  54384. * @param {object} data - With keys like `repeat`.
  54385. */
  54386. function setTextureProperties (texture, data) {
  54387. var offset = data.offset || {x: 0, y: 0};
  54388. var repeat = data.repeat || {x: 1, y: 1};
  54389. var npot = data.npot || false;
  54390. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  54391. // and filters must not use mipmaps (i.e. Nearest or Linear).
  54392. if (npot) {
  54393. texture.wrapS = THREE.ClampToEdgeWrapping;
  54394. texture.wrapT = THREE.ClampToEdgeWrapping;
  54395. texture.magFilter = THREE.LinearFilter;
  54396. texture.minFilter = THREE.LinearFilter;
  54397. }
  54398. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  54399. if (repeat.x !== 1 || repeat.y !== 1) {
  54400. texture.wrapS = THREE.RepeatWrapping;
  54401. texture.wrapT = THREE.RepeatWrapping;
  54402. texture.repeat.set(repeat.x, repeat.y);
  54403. }
  54404. // Don't bother setting offset if it is 0/0.
  54405. if (offset.x !== 0 || offset.y !== 0) {
  54406. texture.offset.set(offset.x, offset.y);
  54407. }
  54408. }
  54409. /**
  54410. * Create video element to be used as a texture.
  54411. *
  54412. * @param {string} src - Url to a video file.
  54413. * @param {number} width - Width of the video.
  54414. * @param {number} height - Height of the video.
  54415. * @returns {Element} Video element.
  54416. */
  54417. function createVideoEl (src, width, height) {
  54418. var videoEl = document.createElement('video');
  54419. videoEl.width = width;
  54420. videoEl.height = height;
  54421. // Support inline videos for iOS webviews.
  54422. videoEl.setAttribute('playsinline', '');
  54423. videoEl.setAttribute('webkit-playsinline', '');
  54424. videoEl.autoplay = true;
  54425. videoEl.loop = true;
  54426. videoEl.crossOrigin = 'anonymous';
  54427. videoEl.addEventListener('error', function () {
  54428. warn('`$s` is not a valid video', src);
  54429. }, true);
  54430. videoEl.src = src;
  54431. return videoEl;
  54432. }
  54433. /**
  54434. * Fixes a video element's attributes to prevent developers from accidentally passing the
  54435. * wrong attribute values to commonly misused video attributes.
  54436. *
  54437. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  54438. * as booleans. Existence of those attributes will mean truthy.
  54439. *
  54440. * For example, translates <video loop="false"> to <video>.
  54441. *
  54442. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  54443. * @param {Element} videoEl - Video element.
  54444. * @returns {Element} Video element with the correct properties updated.
  54445. */
  54446. function fixVideoAttributes (videoEl) {
  54447. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  54448. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  54449. if (videoEl.getAttribute('loop') === 'false') {
  54450. videoEl.removeAttribute('loop');
  54451. }
  54452. if (videoEl.getAttribute('preload') === 'false') {
  54453. videoEl.preload = 'none';
  54454. }
  54455. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  54456. // To support inline videos in iOS webviews.
  54457. videoEl.setAttribute('playsinline', '');
  54458. videoEl.setAttribute('webkit-playsinline', '');
  54459. return videoEl;
  54460. }
  54461. },{"../core/system":114,"../lib/three":151,"../utils/":176,"../utils/material":179}],166:[function(_dereq_,module,exports){
  54462. var registerSystem = _dereq_('../core/system').registerSystem;
  54463. var utils = _dereq_('../utils/');
  54464. var THREE = _dereq_('../lib/three');
  54465. var debug = utils.debug;
  54466. var warn = debug('components:renderer:warn');
  54467. /**
  54468. * Determines state of various renderer properties.
  54469. */
  54470. module.exports.System = registerSystem('renderer', {
  54471. schema: {
  54472. antialias: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  54473. highRefreshRate: {default: false},
  54474. logarithmicDepthBuffer: {default: 'auto', oneOf: ['true', 'false', 'auto']},
  54475. maxCanvasWidth: {default: 1920},
  54476. maxCanvasHeight: {default: 1920},
  54477. physicallyCorrectLights: {default: false},
  54478. precision: {default: 'high', oneOf: ['high', 'medium', 'low']},
  54479. sortObjects: {default: false},
  54480. colorManagement: {default: false},
  54481. gammaOutput: {default: false},
  54482. alpha: {default: true},
  54483. foveationLevel: {default: 0}
  54484. },
  54485. init: function () {
  54486. var data = this.data;
  54487. var sceneEl = this.el;
  54488. // This is the rendering engine, such as THREE.js so copy over any persistent properties from the rendering system.
  54489. var renderer = sceneEl.renderer;
  54490. renderer.sortObjects = data.sortObjects;
  54491. renderer.physicallyCorrectLights = data.physicallyCorrectLights;
  54492. if (data.colorManagement || data.gammaOutput) {
  54493. renderer.gammaOutput = true;
  54494. renderer.gammaFactor = 2.2;
  54495. if (data.gammaOutput) {
  54496. warn('Property `gammaOutput` is deprecated. Use `renderer="colorManagement: true;"` instead.');
  54497. }
  54498. }
  54499. if (sceneEl.hasAttribute('antialias')) {
  54500. warn('Component `antialias` is deprecated. Use `renderer="antialias: true"` instead.');
  54501. }
  54502. if (sceneEl.hasAttribute('logarithmicDepthBuffer')) {
  54503. warn('Component `logarithmicDepthBuffer` is deprecated. Use `renderer="logarithmicDepthBuffer: true"` instead.');
  54504. }
  54505. },
  54506. applyColorCorrection: function (colorOrTexture) {
  54507. if (!this.data.colorManagement || !colorOrTexture) {
  54508. return;
  54509. } else if (colorOrTexture.isColor) {
  54510. colorOrTexture.convertSRGBToLinear();
  54511. } else if (colorOrTexture.isTexture) {
  54512. colorOrTexture.encoding = THREE.sRGBEncoding;
  54513. }
  54514. }
  54515. });
  54516. },{"../core/system":114,"../lib/three":151,"../utils/":176}],167:[function(_dereq_,module,exports){
  54517. var registerSystem = _dereq_('../core/system').registerSystem;
  54518. var THREE = _dereq_('../lib/three');
  54519. var SHADOW_MAP_TYPE_MAP = {
  54520. basic: THREE.BasicShadowMap,
  54521. pcf: THREE.PCFShadowMap,
  54522. pcfsoft: THREE.PCFSoftShadowMap
  54523. };
  54524. /**
  54525. * Shadow system.
  54526. *
  54527. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  54528. * options on the WebGLRenderer for configuring shadow appearance.
  54529. */
  54530. module.exports.System = registerSystem('shadow', {
  54531. schema: {
  54532. enabled: {default: true},
  54533. autoUpdate: {default: true},
  54534. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  54535. },
  54536. init: function () {
  54537. var sceneEl = this.sceneEl;
  54538. var data = this.data;
  54539. this.shadowMapEnabled = false;
  54540. if (!sceneEl.renderer) { return; } // For tests.
  54541. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  54542. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  54543. this.setShadowMapEnabled(this.shadowMapEnabled);
  54544. },
  54545. update: function (prevData) {
  54546. if (prevData.enabled !== this.data.enabled) {
  54547. this.setShadowMapEnabled(this.data.enabled);
  54548. }
  54549. },
  54550. /**
  54551. * Enables/disables the renderer shadow map.
  54552. * @param {boolean} enabled
  54553. */
  54554. setShadowMapEnabled: function (enabled) {
  54555. var renderer = this.sceneEl.renderer;
  54556. this.shadowMapEnabled = this.data.enabled && enabled;
  54557. if (renderer) {
  54558. renderer.shadowMap.enabled = this.shadowMapEnabled;
  54559. }
  54560. }
  54561. });
  54562. },{"../core/system":114,"../lib/three":151}],168:[function(_dereq_,module,exports){
  54563. var registerSystem = _dereq_('../core/system').registerSystem;
  54564. var utils = _dereq_('../utils');
  54565. /**
  54566. * Tracked controls system.
  54567. * Maintain list with available tracked controllers.
  54568. */
  54569. module.exports.System = registerSystem('tracked-controls-webvr', {
  54570. init: function () {
  54571. var self = this;
  54572. this.controllers = [];
  54573. this.isChrome = navigator.userAgent.indexOf('Chrome') !== -1;
  54574. this.updateControllerList();
  54575. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  54576. if (!navigator.getVRDisplays) { return; }
  54577. this.sceneEl.addEventListener('enter-vr', function () {
  54578. navigator.getVRDisplays().then(function (displays) {
  54579. if (displays.length) { self.vrDisplay = displays[0]; }
  54580. });
  54581. });
  54582. },
  54583. tick: function () {
  54584. if (this.isChrome) {
  54585. // Retrieve new controller handlers with updated state (pose, buttons...)
  54586. this.updateControllerList();
  54587. } else {
  54588. this.throttledUpdateControllerList();
  54589. }
  54590. },
  54591. /**
  54592. * Update controller list.
  54593. */
  54594. updateControllerList: function () {
  54595. var controllers = this.controllers;
  54596. var gamepad;
  54597. var gamepads;
  54598. var i;
  54599. var prevCount;
  54600. gamepads = navigator.getGamepads && navigator.getGamepads();
  54601. if (!gamepads) { return; }
  54602. prevCount = controllers.length;
  54603. controllers.length = 0;
  54604. for (i = 0; i < gamepads.length; ++i) {
  54605. gamepad = gamepads[i];
  54606. if (gamepad && gamepad.pose) {
  54607. controllers.push(gamepad);
  54608. }
  54609. }
  54610. if (controllers.length !== prevCount) {
  54611. this.el.emit('controllersupdated', undefined, false);
  54612. }
  54613. }
  54614. });
  54615. },{"../core/system":114,"../utils":176}],169:[function(_dereq_,module,exports){
  54616. var registerSystem = _dereq_('../core/system').registerSystem;
  54617. var utils = _dereq_('../utils');
  54618. /**
  54619. * Tracked controls system.
  54620. * Maintain list with available tracked controllers.
  54621. */
  54622. module.exports.System = registerSystem('tracked-controls-webxr', {
  54623. init: function () {
  54624. this.controllers = [];
  54625. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  54626. },
  54627. tick: function () {
  54628. this.throttledUpdateControllerList();
  54629. },
  54630. updateControllerList: function () {
  54631. var oldControllersLength = this.controllers.length;
  54632. if (!this.el.xrSession) { return; }
  54633. this.controllers = this.el.xrSession.getInputSources();
  54634. if (oldControllersLength === this.controllers.length) { return; }
  54635. this.el.emit('controllersupdated', undefined, false);
  54636. }
  54637. });
  54638. },{"../core/system":114,"../utils":176}],170:[function(_dereq_,module,exports){
  54639. /**
  54640. * Faster version of Function.prototype.bind
  54641. * @param {Function} fn - Function to wrap.
  54642. * @param {Object} ctx - What to bind as context.
  54643. * @param {...*} arguments - Arguments to pass through.
  54644. */
  54645. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  54646. return (function (prependedArgs) {
  54647. return function bound () {
  54648. // Concat the bound function arguments with those passed to original bind
  54649. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  54650. return fn.apply(ctx, args);
  54651. };
  54652. })(Array.prototype.slice.call(arguments, 2));
  54653. };
  54654. },{}],171:[function(_dereq_,module,exports){
  54655. /* global THREE */
  54656. var debug = _dereq_('./debug');
  54657. var extend = _dereq_('object-assign');
  54658. var warn = debug('utils:coordinates:warn');
  54659. // Order of coordinates parsed by coordinates.parse.
  54660. var COORDINATE_KEYS = ['x', 'y', 'z', 'w'];
  54661. // Coordinate string regex. Handles negative, positive, and decimals.
  54662. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  54663. module.exports.regex = regex;
  54664. var OBJECT = 'object';
  54665. var whitespaceRegex = /\s+/g;
  54666. /**
  54667. * Parses coordinates from an "x y z" string.
  54668. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  54669. *
  54670. * @param {string} val - An "x y z" string.
  54671. * @param {string} defaults - fallback value.
  54672. * @returns {object} An object with keys [x, y, z].
  54673. */
  54674. function parse (value, defaultVec) {
  54675. var coordinate;
  54676. var defaultVal;
  54677. var key;
  54678. var i;
  54679. var vec;
  54680. var x;
  54681. var y;
  54682. var z;
  54683. var w;
  54684. if (value && value instanceof Object) {
  54685. x = value.x === undefined ? defaultVec && defaultVec.x : value.x;
  54686. y = value.y === undefined ? defaultVec && defaultVec.y : value.y;
  54687. z = value.z === undefined ? defaultVec && defaultVec.z : value.z;
  54688. w = value.w === undefined ? defaultVec && defaultVec.w : value.w;
  54689. if (x !== undefined && x !== null) { value.x = parseIfString(x); }
  54690. if (y !== undefined && y !== null) { value.y = parseIfString(y); }
  54691. if (z !== undefined && z !== null) { value.z = parseIfString(z); }
  54692. if (w !== undefined && w !== null) { value.w = parseIfString(w); }
  54693. return value;
  54694. }
  54695. if (value === null || value === undefined) {
  54696. return typeof defaultVec === OBJECT ? extend({}, defaultVec) : defaultVec;
  54697. }
  54698. coordinate = value.trim().split(whitespaceRegex);
  54699. vec = {};
  54700. for (i = 0; i < COORDINATE_KEYS.length; i++) {
  54701. key = COORDINATE_KEYS[i];
  54702. if (coordinate[i]) {
  54703. vec[key] = parseFloat(coordinate[i], 10);
  54704. } else {
  54705. defaultVal = defaultVec && defaultVec[key];
  54706. if (defaultVal === undefined) { continue; }
  54707. vec[key] = parseIfString(defaultVal);
  54708. }
  54709. }
  54710. return vec;
  54711. }
  54712. module.exports.parse = parse;
  54713. /**
  54714. * Stringify coordinates from an object with keys [x y z].
  54715. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  54716. *
  54717. * @param {object|string} data - An object with keys [x y z].
  54718. * @returns {string} An "x y z" string.
  54719. */
  54720. function stringify (data) {
  54721. var str;
  54722. if (typeof data !== OBJECT) { return data; }
  54723. str = data.x + ' ' + data.y;
  54724. if (data.z != null) { str += ' ' + data.z; }
  54725. if (data.w != null) { str += ' ' + data.w; }
  54726. return str;
  54727. }
  54728. module.exports.stringify = stringify;
  54729. /**
  54730. * @returns {bool}
  54731. */
  54732. function isCoordinates (value) {
  54733. return regex.test(value);
  54734. }
  54735. module.exports.isCoordinates = isCoordinates;
  54736. module.exports.isCoordinate = function (value) {
  54737. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  54738. return isCoordinates(value);
  54739. };
  54740. function parseIfString (val) {
  54741. if (val !== null && val !== undefined && val.constructor === String) {
  54742. return parseFloat(val, 10);
  54743. }
  54744. return val;
  54745. }
  54746. /**
  54747. * Convert {x, y, z} object to three.js Vector3.
  54748. */
  54749. module.exports.toVector3 = function (vec3) {
  54750. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  54751. };
  54752. },{"./debug":172,"object-assign":25}],172:[function(_dereq_,module,exports){
  54753. (function (process){
  54754. var debugLib = _dereq_('debug');
  54755. var extend = _dereq_('object-assign');
  54756. var settings = {
  54757. colors: {
  54758. debug: 'gray',
  54759. error: 'red',
  54760. info: 'gray',
  54761. warn: 'orange'
  54762. }
  54763. };
  54764. /**
  54765. * Monkeypatches `debug` so we can colorize error/warning messages.
  54766. *
  54767. * (See issue: https://github.com/visionmedia/debug/issues/137)
  54768. */
  54769. var debug = function (namespace) {
  54770. var d = debugLib(namespace);
  54771. d.color = getDebugNamespaceColor(namespace);
  54772. return d;
  54773. };
  54774. extend(debug, debugLib);
  54775. /**
  54776. * Returns the type of the namespace (e.g., `error`, `warn`).
  54777. *
  54778. * @param {String} namespace
  54779. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54780. * @returns {String} The type of the namespace (e.g., `warn`).
  54781. * @api private
  54782. */
  54783. function getDebugNamespaceType (namespace) {
  54784. var chunks = namespace.split(':');
  54785. return chunks[chunks.length - 1]; // Return the last one
  54786. }
  54787. /**
  54788. * Returns the color of the namespace (e.g., `orange`).
  54789. *
  54790. * @param {String} namespace
  54791. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54792. * @returns {String} The color of the namespace (e.g., `orange`).
  54793. * @api private
  54794. */
  54795. function getDebugNamespaceColor (namespace) {
  54796. var type = getDebugNamespaceType(namespace);
  54797. var color = settings.colors && settings.colors[type];
  54798. return color || null;
  54799. }
  54800. /**
  54801. * Returns `localStorage` if possible.
  54802. *
  54803. * This is necessary because Safari throws when a user disables
  54804. * cookies or `localStorage` and you attempt to access it.
  54805. *
  54806. * @returns {localStorage}
  54807. * @api private
  54808. */
  54809. function storage () {
  54810. try {
  54811. return window.localStorage;
  54812. } catch (e) {
  54813. }
  54814. }
  54815. /**
  54816. * To enable console logging, type this in the Console of your Dev Tools:
  54817. *
  54818. * localStorage.logs = 1
  54819. *
  54820. * To disable console logging:
  54821. *
  54822. * localStorage.logs = 0
  54823. *
  54824. */
  54825. var ls = storage();
  54826. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  54827. debug.enable('*');
  54828. } else {
  54829. debug.enable('*:error,*:info,*:warn');
  54830. }
  54831. if (process.browser) { window.logs = debug; }
  54832. module.exports = debug;
  54833. }).call(this,_dereq_('_process'))
  54834. },{"_process":32,"debug":8,"object-assign":25}],173:[function(_dereq_,module,exports){
  54835. (function (process){
  54836. var error = _dereq_('debug')('device:error');
  54837. var vrDisplay;
  54838. // Catch vrdisplayactivate early to ensure we can enter VR mode after the scene loads.
  54839. window.addEventListener('vrdisplayactivate', function (evt) {
  54840. var canvasEl;
  54841. // WebXR takes priority if available.
  54842. if (navigator.xr) { return; }
  54843. canvasEl = document.createElement('canvas');
  54844. vrDisplay = evt.display;
  54845. // Request present immediately. a-scene will be allowed to enter VR without user gesture.
  54846. vrDisplay.requestPresent([{source: canvasEl}]).then(function () {}, function () {});
  54847. });
  54848. // Support both WebVR and WebXR APIs.
  54849. if (navigator.xr) {
  54850. navigator.xr.requestDevice().then(function (device) {
  54851. if (!device) { return; }
  54852. device.supportsSession({immersive: true, exclusive: true}).then(function () {
  54853. var sceneEl = document.querySelector('a-scene');
  54854. vrDisplay = device;
  54855. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  54856. });
  54857. }).catch(function (err) {
  54858. error('WebXR Request Device: ' + err.message);
  54859. });
  54860. } else {
  54861. if (navigator.getVRDisplays) {
  54862. navigator.getVRDisplays().then(function (displays) {
  54863. var sceneEl = document.querySelector('a-scene');
  54864. vrDisplay = displays.length && displays[0];
  54865. if (sceneEl) { sceneEl.emit('displayconnected', {vrDisplay: vrDisplay}); }
  54866. });
  54867. }
  54868. }
  54869. module.exports.isWebXRAvailable = navigator.xr !== undefined;
  54870. function getVRDisplay () { return vrDisplay; }
  54871. module.exports.getVRDisplay = getVRDisplay;
  54872. /**
  54873. * Determine if a headset is connected by checking if a vrDisplay is available.
  54874. */
  54875. function checkHeadsetConnected () { return !!getVRDisplay(); }
  54876. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  54877. /**
  54878. * Checks if browser is mobile and not stand-alone dedicated vr device.
  54879. * @return {Boolean} True if mobile browser detected.
  54880. */
  54881. var isMobile = (function () {
  54882. var _isMobile = false;
  54883. (function (a) {
  54884. // eslint-disable-next-line no-useless-escape
  54885. 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))) {
  54886. _isMobile = true;
  54887. }
  54888. if (isIOS() || isTablet() || isR7()) {
  54889. _isMobile = true;
  54890. }
  54891. if (isMobileVR()) {
  54892. _isMobile = false;
  54893. }
  54894. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  54895. return function () { return _isMobile; };
  54896. })();
  54897. module.exports.isMobile = isMobile;
  54898. /**
  54899. * Detect tablet devices.
  54900. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  54901. */
  54902. function isTablet (mockUserAgent) {
  54903. var userAgent = mockUserAgent || window.navigator.userAgent;
  54904. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  54905. }
  54906. module.exports.isTablet = isTablet;
  54907. function isIOS () {
  54908. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  54909. }
  54910. module.exports.isIOS = isIOS;
  54911. /**
  54912. * Detect browsers in Stand-Alone headsets
  54913. */
  54914. function isMobileVR () {
  54915. return /(OculusBrowser)|(SamsungBrowser)|(Mobile VR)/i.test(window.navigator.userAgent);
  54916. }
  54917. module.exports.isMobileVR = isMobileVR;
  54918. function isR7 () {
  54919. return /R7 Build/.test(window.navigator.userAgent);
  54920. }
  54921. module.exports.isR7 = isR7;
  54922. /**
  54923. * Checks mobile device orientation.
  54924. * @return {Boolean} True if landscape orientation.
  54925. */
  54926. module.exports.isLandscape = function () {
  54927. var orientation = window.orientation;
  54928. if (isR7()) { orientation += 90; }
  54929. return orientation === 90 || orientation === -90;
  54930. };
  54931. /**
  54932. * Check if running in a browser or spoofed browser (bundler).
  54933. * We need to check a node api that isn't mocked on either side.
  54934. * `require` and `module.exports` are mocked in browser by bundlers.
  54935. * `window` is mocked in node.
  54936. * `process` is also mocked by browserify, but has custom properties.
  54937. */
  54938. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  54939. /**
  54940. * Check if running in node on the server.
  54941. */
  54942. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  54943. /**
  54944. * Update an Object3D pose if a polyfilled vrDisplay is present.
  54945. */
  54946. module.exports.PolyfillControls = function PolyfillControls (object) {
  54947. var frameData;
  54948. var vrDisplay = window.webvrpolyfill && window.webvrpolyfill.getPolyfillDisplays()[0];
  54949. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  54950. this.update = function () {
  54951. var pose;
  54952. if (!vrDisplay) { return; }
  54953. vrDisplay.getFrameData(frameData);
  54954. pose = frameData.pose;
  54955. if (pose.orientation !== null) {
  54956. object.quaternion.fromArray(pose.orientation);
  54957. }
  54958. if (pose.position !== null) {
  54959. object.position.fromArray(pose.position);
  54960. } else {
  54961. object.position.set(0, 0, 0);
  54962. }
  54963. };
  54964. };
  54965. }).call(this,_dereq_('_process'))
  54966. },{"_process":32,"debug":8}],174:[function(_dereq_,module,exports){
  54967. /**
  54968. * Split a delimited component property string (e.g., `material.color`) to an object
  54969. * containing `component` name and `property` name. If there is no delimiter, just return the
  54970. * string back.
  54971. *
  54972. * Cache arrays from splitting strings via delimiter to save on memory.
  54973. *
  54974. * @param {string} str - e.g., `material.opacity`.
  54975. * @param {string} delimiter - e.g., `.`.
  54976. * @returns {array} e.g., `['material', 'opacity']`.
  54977. */
  54978. var propertyPathCache = {};
  54979. function getComponentPropertyPath (str, delimiter) {
  54980. delimiter = delimiter || '.';
  54981. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  54982. if (str.indexOf(delimiter) !== -1) {
  54983. propertyPathCache[delimiter][str] = str.split(delimiter);
  54984. } else {
  54985. propertyPathCache[delimiter][str] = str;
  54986. }
  54987. return propertyPathCache[delimiter][str];
  54988. }
  54989. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  54990. module.exports.propertyPathCache = propertyPathCache;
  54991. /**
  54992. * Get component property using encoded component name + component property name with a
  54993. * delimiter.
  54994. */
  54995. module.exports.getComponentProperty = function (el, name, delimiter) {
  54996. var splitName;
  54997. delimiter = delimiter || '.';
  54998. if (name.indexOf(delimiter) !== -1) {
  54999. splitName = getComponentPropertyPath(name, delimiter);
  55000. if (splitName.constructor === String) {
  55001. return el.getAttribute(splitName);
  55002. }
  55003. return el.getAttribute(splitName[0])[splitName[1]];
  55004. }
  55005. return el.getAttribute(name);
  55006. };
  55007. /**
  55008. * Set component property using encoded component name + component property name with a
  55009. * delimiter.
  55010. */
  55011. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  55012. var splitName;
  55013. delimiter = delimiter || '.';
  55014. if (name.indexOf(delimiter) !== -1) {
  55015. splitName = getComponentPropertyPath(name, delimiter);
  55016. if (splitName.constructor === String) {
  55017. el.setAttribute(splitName, value);
  55018. } else {
  55019. el.setAttribute(splitName[0], splitName[1], value);
  55020. }
  55021. return;
  55022. }
  55023. el.setAttribute(name, value);
  55024. };
  55025. },{}],175:[function(_dereq_,module,exports){
  55026. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  55027. var width = canvasEl.style.width;
  55028. var height = canvasEl.style.height;
  55029. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  55030. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  55031. // By changing the size 1 pixel and restoring the previous value
  55032. // we trigger a size recalculation cycle.
  55033. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  55034. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  55035. setTimeout(function () {
  55036. canvasEl.style.width = width;
  55037. canvasEl.style.height = height;
  55038. }, 200);
  55039. };
  55040. },{}],176:[function(_dereq_,module,exports){
  55041. /* global location */
  55042. /* Centralized place to reference utilities since utils is exposed to the user. */
  55043. var debug = _dereq_('./debug');
  55044. var deepAssign = _dereq_('deep-assign');
  55045. var device = _dereq_('./device');
  55046. var objectAssign = _dereq_('object-assign');
  55047. var objectPool = _dereq_('./object-pool');
  55048. var warn = debug('utils:warn');
  55049. module.exports.bind = _dereq_('./bind');
  55050. module.exports.coordinates = _dereq_('./coordinates');
  55051. module.exports.debug = debug;
  55052. module.exports.device = device;
  55053. module.exports.entity = _dereq_('./entity');
  55054. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  55055. module.exports.isIE11 = _dereq_('./is-ie11');
  55056. module.exports.material = _dereq_('./material');
  55057. module.exports.objectPool = objectPool;
  55058. module.exports.split = _dereq_('./split').split;
  55059. module.exports.styleParser = _dereq_('./styleParser');
  55060. module.exports.trackedControls = _dereq_('./tracked-controls');
  55061. module.exports.checkHeadsetConnected = function () {
  55062. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  55063. return device.checkHeadsetConnected(arguments);
  55064. };
  55065. module.exports.isGearVR = module.exports.device.isGearVR = function () {
  55066. warn('`utils.isGearVR` has been deprecated, use `utils.device.isMobileVR`');
  55067. };
  55068. module.exports.isIOS = function () {
  55069. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  55070. return device.isIOS(arguments);
  55071. };
  55072. module.exports.isOculusGo = module.exports.device.isOculusGo = function () {
  55073. warn('`utils.isOculusGo` has been deprecated, use `utils.device.isMobileVR`');
  55074. };
  55075. module.exports.isMobile = function () {
  55076. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  55077. return device.isMobile(arguments);
  55078. };
  55079. /**
  55080. * Returns throttle function that gets called at most once every interval.
  55081. *
  55082. * @param {function} functionToThrottle
  55083. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55084. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55085. * @returns {function} Throttled function.
  55086. */
  55087. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  55088. var lastTime;
  55089. if (optionalContext) {
  55090. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55091. }
  55092. return function () {
  55093. var time = Date.now();
  55094. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  55095. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55096. lastTime = time;
  55097. functionToThrottle.apply(null, arguments);
  55098. }
  55099. };
  55100. };
  55101. /**
  55102. * Returns throttle function that gets called at most once every interval.
  55103. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  55104. *
  55105. * @param {function} functionToThrottle
  55106. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55107. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55108. * @returns {function} Throttled function.
  55109. */
  55110. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  55111. var lastTime;
  55112. if (optionalContext) {
  55113. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55114. }
  55115. return function (time, delta) {
  55116. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  55117. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55118. lastTime = time;
  55119. functionToThrottle(time, sinceLastTime);
  55120. }
  55121. };
  55122. };
  55123. /**
  55124. * Returns debounce function that gets called only once after a set of repeated calls.
  55125. *
  55126. * @param {function} functionToDebounce
  55127. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  55128. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  55129. * @returns {function} Debounced function.
  55130. */
  55131. module.exports.debounce = function (func, wait, immediate) {
  55132. var timeout;
  55133. return function () {
  55134. var context = this;
  55135. var args = arguments;
  55136. var later = function () {
  55137. timeout = null;
  55138. if (!immediate) func.apply(context, args);
  55139. };
  55140. var callNow = immediate && !timeout;
  55141. clearTimeout(timeout);
  55142. timeout = setTimeout(later, wait);
  55143. if (callNow) func.apply(context, args);
  55144. };
  55145. };
  55146. /**
  55147. * Mix the properties of source object(s) into a destination object.
  55148. *
  55149. * @param {object} dest - The object to which properties will be copied.
  55150. * @param {...object} source - The object(s) from which properties will be copied.
  55151. */
  55152. module.exports.extend = objectAssign;
  55153. module.exports.extendDeep = deepAssign;
  55154. module.exports.clone = function (obj) {
  55155. return JSON.parse(JSON.stringify(obj));
  55156. };
  55157. /**
  55158. * Checks if two values are equal.
  55159. * Includes objects and arrays and nested objects and arrays.
  55160. * Try to keep this function performant as it will be called often to see if a component
  55161. * should be updated.
  55162. *
  55163. * @param {object} a - First object.
  55164. * @param {object} b - Second object.
  55165. * @returns {boolean} Whether two objects are deeply equal.
  55166. */
  55167. var deepEqual = (function () {
  55168. var arrayPool = objectPool.createPool(function () { return []; });
  55169. return function (a, b) {
  55170. var key;
  55171. var keysA;
  55172. var keysB;
  55173. var i;
  55174. var valA;
  55175. var valB;
  55176. // If not objects or arrays, compare as values.
  55177. if (a === undefined || b === undefined || a === null || b === null ||
  55178. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  55179. (a.constructor === Array && b.constructor === Array))) {
  55180. return a === b;
  55181. }
  55182. // Different number of keys, not equal.
  55183. keysA = arrayPool.use();
  55184. keysB = arrayPool.use();
  55185. keysA.length = 0;
  55186. keysB.length = 0;
  55187. for (key in a) { keysA.push(key); }
  55188. for (key in b) { keysB.push(key); }
  55189. if (keysA.length !== keysB.length) {
  55190. arrayPool.recycle(keysA);
  55191. arrayPool.recycle(keysB);
  55192. return false;
  55193. }
  55194. // Return `false` at the first sign of inequality.
  55195. for (i = 0; i < keysA.length; ++i) {
  55196. valA = a[keysA[i]];
  55197. valB = b[keysA[i]];
  55198. // Check nested array and object.
  55199. if ((typeof valA === 'object' || typeof valB === 'object') ||
  55200. (Array.isArray(valA) && Array.isArray(valB))) {
  55201. if (valA === valB) { continue; }
  55202. if (!deepEqual(valA, valB)) {
  55203. arrayPool.recycle(keysA);
  55204. arrayPool.recycle(keysB);
  55205. return false;
  55206. }
  55207. } else if (valA !== valB) {
  55208. arrayPool.recycle(keysA);
  55209. arrayPool.recycle(keysB);
  55210. return false;
  55211. }
  55212. }
  55213. arrayPool.recycle(keysA);
  55214. arrayPool.recycle(keysB);
  55215. return true;
  55216. };
  55217. })();
  55218. module.exports.deepEqual = deepEqual;
  55219. /**
  55220. * Computes the difference between two objects.
  55221. *
  55222. * @param {object} a - First object to compare (e.g., oldData).
  55223. * @param {object} b - Second object to compare (e.g., newData).
  55224. * @returns {object}
  55225. * Difference object where set of keys note which values were not equal, and values are
  55226. * `b`'s values.
  55227. */
  55228. module.exports.diff = (function () {
  55229. var keys = [];
  55230. return function (a, b, targetObject) {
  55231. var aVal;
  55232. var bVal;
  55233. var bKey;
  55234. var diff;
  55235. var key;
  55236. var i;
  55237. var isComparingObjects;
  55238. diff = targetObject || {};
  55239. // Collect A keys.
  55240. keys.length = 0;
  55241. for (key in a) { keys.push(key); }
  55242. if (!b) { return diff; }
  55243. // Collect B keys.
  55244. for (bKey in b) {
  55245. if (keys.indexOf(bKey) === -1) {
  55246. keys.push(bKey);
  55247. }
  55248. }
  55249. for (i = 0; i < keys.length; i++) {
  55250. key = keys[i];
  55251. aVal = a[key];
  55252. bVal = b[key];
  55253. isComparingObjects = aVal && bVal &&
  55254. aVal.constructor === Object && bVal.constructor === Object;
  55255. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  55256. (!isComparingObjects && aVal !== bVal)) {
  55257. diff[key] = bVal;
  55258. }
  55259. }
  55260. return diff;
  55261. };
  55262. })();
  55263. /**
  55264. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  55265. * @param {Event} event Event object.
  55266. * @returns {Boolean} Whether the key event should be captured.
  55267. */
  55268. module.exports.shouldCaptureKeyEvent = function (event) {
  55269. if (event.metaKey) { return false; }
  55270. return document.activeElement === document.body;
  55271. };
  55272. /**
  55273. * Splits a string into an array based on a delimiter.
  55274. *
  55275. * @param {string=} [str=''] Source string
  55276. * @param {string=} [delimiter=' '] Delimiter to use
  55277. * @returns {array} Array of delimited strings
  55278. */
  55279. module.exports.splitString = function (str, delimiter) {
  55280. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  55281. // First collapse the whitespace (or whatever the delimiter is).
  55282. var regex = new RegExp(delimiter, 'g');
  55283. str = (str || '').replace(regex, delimiter);
  55284. // Then split.
  55285. return str.split(delimiter);
  55286. };
  55287. /**
  55288. * Extracts data from the element given an object that contains expected keys.
  55289. *
  55290. * @param {Element} Source element.
  55291. * @param {Object} [defaults={}] Object of default key-value pairs.
  55292. * @returns {Object}
  55293. */
  55294. module.exports.getElData = function (el, defaults) {
  55295. defaults = defaults || {};
  55296. var data = {};
  55297. Object.keys(defaults).forEach(copyAttribute);
  55298. function copyAttribute (key) {
  55299. if (el.hasAttribute(key)) {
  55300. data[key] = el.getAttribute(key);
  55301. }
  55302. }
  55303. return data;
  55304. };
  55305. /**
  55306. * Retrieves querystring value.
  55307. * @param {String} name Name of querystring key.
  55308. * @return {String} Value
  55309. */
  55310. module.exports.getUrlParameter = function (name) {
  55311. // eslint-disable-next-line no-useless-escape
  55312. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  55313. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  55314. var results = regex.exec(location.search);
  55315. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  55316. };
  55317. /**
  55318. * Detects whether context is within iframe.
  55319. */
  55320. module.exports.isIframed = function () {
  55321. return window.top !== window.self;
  55322. };
  55323. /**
  55324. * Finds all elements under the element that have the isScene
  55325. * property set to true
  55326. */
  55327. module.exports.findAllScenes = function (el) {
  55328. var matchingElements = [];
  55329. var allElements = el.getElementsByTagName('*');
  55330. for (var i = 0, n = allElements.length; i < n; i++) {
  55331. if (allElements[i].isScene) {
  55332. // Element exists with isScene set.
  55333. matchingElements.push(allElements[i]);
  55334. }
  55335. }
  55336. return matchingElements;
  55337. };
  55338. // Must be at bottom to avoid circular dependency.
  55339. module.exports.srcLoader = _dereq_('./src-loader');
  55340. },{"./bind":170,"./coordinates":171,"./debug":172,"./device":173,"./entity":174,"./forceCanvasResizeSafariMobile":175,"./is-ie11":177,"./material":179,"./object-pool":180,"./split":181,"./src-loader":182,"./styleParser":183,"./tracked-controls":184,"deep-assign":10,"object-assign":25}],177:[function(_dereq_,module,exports){
  55341. // https://stackoverflow.com/a/17907562
  55342. function getInternetExplorerVersion () {
  55343. var version = -1;
  55344. var userAgent = navigator.userAgent;
  55345. var re;
  55346. if (navigator.appName === 'Microsoft Internet Explorer') {
  55347. re = new RegExp('MSIE ([0-9]{1,}[\\.0-9]{0,})');
  55348. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  55349. } else if (navigator.appName === 'Netscape') {
  55350. re = new RegExp('Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})');
  55351. if (re.exec(userAgent) != null) { version = parseFloat(RegExp.$1); }
  55352. }
  55353. return version;
  55354. }
  55355. module.exports = getInternetExplorerVersion() === 11;
  55356. },{}],178:[function(_dereq_,module,exports){
  55357. /**
  55358. * Check if device is iOS and older than version 10.
  55359. */
  55360. module.exports = function isIOSOlderThan10 (userAgent) {
  55361. return /(iphone|ipod|ipad).*os.(7_|8_|9_)/i.test(userAgent);
  55362. };
  55363. },{}],179:[function(_dereq_,module,exports){
  55364. var THREE = _dereq_('../lib/three');
  55365. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  55366. var COLOR_MAPS = new Set([
  55367. 'emissiveMap',
  55368. 'envMap',
  55369. 'map',
  55370. 'specularMap'
  55371. ]);
  55372. /**
  55373. * Update `material` texture property (usually but not always `map`)
  55374. * from `data` property (usually but not always `src`)
  55375. *
  55376. * @param {object} shader - A-Frame shader instance.
  55377. * @param {object} data
  55378. */
  55379. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  55380. var el = shader.el;
  55381. var material = shader.material;
  55382. var rendererSystem = el.sceneEl.systems.renderer;
  55383. var src = data[dataName];
  55384. // Because a single material / shader may have multiple textures,
  55385. // we need to remember the source value for this data property
  55386. // to avoid redundant operations which can be expensive otherwise
  55387. // (e.g. video texture loads).
  55388. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  55389. if (!src) {
  55390. // Forget the prior material src.
  55391. delete shader.materialSrcs[materialName];
  55392. // Remove the texture.
  55393. setMap(null);
  55394. return;
  55395. }
  55396. // Don't process if material src hasn't changed.
  55397. if (src === shader.materialSrcs[materialName]) { return; }
  55398. // Remember the new src for this texture (there may be multiple).
  55399. shader.materialSrcs[materialName] = src;
  55400. // If the new material src is already a texture, just use it.
  55401. if (src instanceof THREE.Texture) { setMap(src); } else {
  55402. // Load texture for the new material src.
  55403. // (And check if we should still use it once available in callback.)
  55404. el.sceneEl.systems.material.loadTexture(src,
  55405. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  55406. checkSetMap);
  55407. }
  55408. function checkSetMap (texture) {
  55409. // If the source has been changed, don't use loaded texture.
  55410. if (shader.materialSrcs[materialName] !== src) { return; }
  55411. setMap(texture);
  55412. }
  55413. function setMap (texture) {
  55414. material[materialName] = texture;
  55415. if (texture && COLOR_MAPS.has(materialName)) {
  55416. rendererSystem.applyColorCorrection(texture);
  55417. }
  55418. material.needsUpdate = true;
  55419. handleTextureEvents(el, texture);
  55420. }
  55421. };
  55422. /**
  55423. * Update `material.map` given `data.src`. For standard and flat shaders.
  55424. *
  55425. * @param {object} shader - A-Frame shader instance.
  55426. * @param {object} data
  55427. */
  55428. module.exports.updateMap = function (shader, data) {
  55429. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  55430. };
  55431. /**
  55432. * Updates the material's maps which give the illusion of extra geometry.
  55433. *
  55434. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  55435. * @param {object} shader - A-Frame shader instance
  55436. * @param {object} data
  55437. */
  55438. module.exports.updateDistortionMap = function (longType, shader, data) {
  55439. var shortType = longType;
  55440. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  55441. var el = shader.el;
  55442. var material = shader.material;
  55443. var rendererSystem = el.sceneEl.systems.renderer;
  55444. var src = data[longType + 'Map'];
  55445. var info = {};
  55446. info.src = src;
  55447. // Pass through the repeat and offset to be handled by the material loader.
  55448. info.offset = data[longType + 'TextureOffset'];
  55449. info.repeat = data[longType + 'TextureRepeat'];
  55450. info.wrap = data[longType + 'TextureWrap'];
  55451. if (src) {
  55452. if (src === shader[longType + 'TextureSrc']) { return; }
  55453. // Texture added or changed.
  55454. shader[longType + 'TextureSrc'] = src;
  55455. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  55456. return;
  55457. }
  55458. // Texture removed.
  55459. if (!material.map) { return; }
  55460. setMap(null);
  55461. function setMap (texture) {
  55462. var slot = shortType + 'Map';
  55463. material[slot] = texture;
  55464. if (texture && COLOR_MAPS.has(slot)) {
  55465. rendererSystem.applyColorCorrection(texture);
  55466. }
  55467. material.needsUpdate = true;
  55468. handleTextureEvents(el, texture);
  55469. }
  55470. };
  55471. /**
  55472. * Emit event on entities on texture-related events.
  55473. *
  55474. * @param {Element} el - Entity.
  55475. * @param {object} texture - three.js Texture.
  55476. */
  55477. function handleTextureEvents (el, texture) {
  55478. if (!texture) { return; }
  55479. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  55480. // Video events.
  55481. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  55482. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  55483. // Check to see if we need to use iOS 10 HLS shader.
  55484. // Only override the shader if it is stock shader that we know doesn't correct.
  55485. if (!el.components || !el.components.material) { return; }
  55486. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  55487. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  55488. el.setAttribute('material', 'shader', 'ios10hls');
  55489. }
  55490. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  55491. });
  55492. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  55493. // Works for non-looping videos only.
  55494. el.emit('materialvideoended', {src: texture.image, texture: texture});
  55495. });
  55496. }
  55497. module.exports.handleTextureEvents = handleTextureEvents;
  55498. /**
  55499. * Given video element src and type, guess whether stream is HLS.
  55500. *
  55501. * @param {string} src - src from video element (generally URL to content).
  55502. * @param {string} type - type from video element (generally MIME type if present).
  55503. */
  55504. module.exports.isHLS = function (src, type) {
  55505. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  55506. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  55507. return false;
  55508. };
  55509. },{"../lib/three":151}],180:[function(_dereq_,module,exports){
  55510. /*
  55511. Adapted deePool by Kyle Simpson.
  55512. MIT License: http://getify.mit-license.org
  55513. */
  55514. var EMPTY_SLOT = Object.freeze(Object.create(null));
  55515. // Default object factory.
  55516. function defaultObjectFactory () { return {}; }
  55517. /**
  55518. * Create a new pool.
  55519. */
  55520. module.exports.createPool = function createPool (objectFactory) {
  55521. var objPool = [];
  55522. var nextFreeSlot = null; // Pool location to look for a free object to use.
  55523. objectFactory = objectFactory || defaultObjectFactory;
  55524. function use () {
  55525. var objToUse;
  55526. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  55527. grow(objPool.length || 5);
  55528. }
  55529. objToUse = objPool[nextFreeSlot];
  55530. objPool[nextFreeSlot++] = EMPTY_SLOT;
  55531. clearObject(objToUse);
  55532. return objToUse;
  55533. }
  55534. function recycle (obj) {
  55535. if (!(obj instanceof Object)) { return; }
  55536. if (nextFreeSlot === null || nextFreeSlot === -1) {
  55537. objPool[objPool.length] = obj;
  55538. return;
  55539. }
  55540. objPool[--nextFreeSlot] = obj;
  55541. }
  55542. function grow (count) {
  55543. var currentLength;
  55544. var i;
  55545. count = count === undefined ? objPool.length : count;
  55546. if (count > 0 && nextFreeSlot == null) {
  55547. nextFreeSlot = 0;
  55548. }
  55549. if (count > 0) {
  55550. currentLength = objPool.length;
  55551. objPool.length += Number(count);
  55552. for (i = currentLength; i < objPool.length; i++) {
  55553. // Add new obj to pool.
  55554. objPool[i] = objectFactory();
  55555. }
  55556. }
  55557. return objPool.length;
  55558. }
  55559. function size () {
  55560. return objPool.length;
  55561. }
  55562. return {
  55563. grow: grow,
  55564. pool: objPool,
  55565. recycle: recycle,
  55566. size: size,
  55567. use: use
  55568. };
  55569. };
  55570. function clearObject (obj) {
  55571. var key;
  55572. if (!obj || obj.constructor !== Object) { return; }
  55573. for (key in obj) { obj[key] = undefined; }
  55574. }
  55575. module.exports.clearObject = clearObject;
  55576. function removeUnusedKeys (obj, schema) {
  55577. var key;
  55578. if (!obj || obj.constructor !== Object) { return; }
  55579. for (key in obj) {
  55580. if (!(key in schema)) {
  55581. delete obj[key];
  55582. }
  55583. }
  55584. }
  55585. module.exports.removeUnusedKeys = removeUnusedKeys;
  55586. },{}],181:[function(_dereq_,module,exports){
  55587. /**
  55588. * String split with cached result.
  55589. */
  55590. module.exports.split = (function () {
  55591. var splitCache = {};
  55592. return function (str, delimiter) {
  55593. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  55594. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  55595. splitCache[delimiter][str] = str.split(delimiter);
  55596. return splitCache[delimiter][str];
  55597. };
  55598. })();
  55599. },{}],182:[function(_dereq_,module,exports){
  55600. /* global Image, XMLHttpRequest */
  55601. var debug = _dereq_('./debug');
  55602. var warn = debug('utils:src-loader:warn');
  55603. /**
  55604. * Validate a texture, either as a selector or as a URL.
  55605. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  55606. * callback.
  55607. *
  55608. * `src` will be passed into the callback
  55609. *
  55610. * @params {string|Element} src - URL or media element.
  55611. * @params {function} isImageCb - callback if texture is an image.
  55612. * @params {function} isVideoCb - callback if texture is a video.
  55613. */
  55614. function validateSrc (src, isImageCb, isVideoCb) {
  55615. checkIsImage(src, function isAnImageUrl (isImage) {
  55616. if (isImage) {
  55617. isImageCb(src);
  55618. return;
  55619. }
  55620. isVideoCb(src);
  55621. });
  55622. }
  55623. /**
  55624. * Validates six images as a cubemap, either as selector or comma-separated
  55625. * URLs.
  55626. *
  55627. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55628. must be wrapped by `url()`.
  55629. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55630. must be wrapped by `url()`.
  55631. */
  55632. function validateCubemapSrc (src, cb) {
  55633. var aCubemap;
  55634. var cubemapSrcRegex = '';
  55635. var i;
  55636. var urls;
  55637. var validatedUrls = [];
  55638. for (i = 0; i < 5; i++) {
  55639. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  55640. }
  55641. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  55642. urls = src.match(new RegExp(cubemapSrcRegex));
  55643. // `src` is a comma-separated list of URLs.
  55644. // In this case, re-use validateSrc for each side of the cube.
  55645. function isImageCb (url) {
  55646. validatedUrls.push(url);
  55647. if (validatedUrls.length === 6) {
  55648. cb(validatedUrls);
  55649. }
  55650. }
  55651. if (urls) {
  55652. for (i = 1; i < 7; i++) {
  55653. validateSrc(parseUrl(urls[i]), isImageCb);
  55654. }
  55655. return;
  55656. }
  55657. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  55658. aCubemap = validateAndGetQuerySelector(src);
  55659. if (!aCubemap) { return; }
  55660. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  55661. return cb(aCubemap.srcs);
  55662. }
  55663. // Else if aCubeMap is not a <a-cubemap>.
  55664. warn('Selector "%s" does not point to <a-cubemap>', src);
  55665. }
  55666. /**
  55667. * Parses src from `url(src)`.
  55668. * @param {string} src - String to parse.
  55669. * @return {string} The parsed src, if parseable.
  55670. */
  55671. function parseUrl (src) {
  55672. var parsedSrc = src.match(/\url\((.+)\)/);
  55673. if (!parsedSrc) { return; }
  55674. return parsedSrc[1];
  55675. }
  55676. /**
  55677. * Call back whether `src` is an image.
  55678. *
  55679. * @param {string|Element} src - URL or element that will be tested.
  55680. * @param {function} onResult - Callback with whether `src` is an image.
  55681. */
  55682. function checkIsImage (src, onResult) {
  55683. var request;
  55684. if (src.tagName) {
  55685. onResult(src.tagName === 'IMG');
  55686. return;
  55687. }
  55688. request = new XMLHttpRequest();
  55689. // Try to send HEAD request to check if image first.
  55690. request.open('HEAD', src);
  55691. request.addEventListener('load', function (event) {
  55692. var contentType;
  55693. if (request.status >= 200 && request.status < 300) {
  55694. contentType = request.getResponseHeader('Content-Type');
  55695. if (contentType == null) {
  55696. checkIsImageFallback(src, onResult);
  55697. } else {
  55698. if (contentType.startsWith('image')) {
  55699. onResult(true);
  55700. } else {
  55701. onResult(false);
  55702. }
  55703. }
  55704. } else {
  55705. checkIsImageFallback(src, onResult);
  55706. }
  55707. request.abort();
  55708. });
  55709. request.send();
  55710. }
  55711. function checkIsImageFallback (src, onResult) {
  55712. var tester = new Image();
  55713. tester.addEventListener('load', onLoad);
  55714. function onLoad () { onResult(true); }
  55715. tester.addEventListener('error', onError);
  55716. function onError () { onResult(false); }
  55717. tester.src = src;
  55718. }
  55719. /**
  55720. * Query and validate a query selector,
  55721. *
  55722. * @param {string} selector - DOM selector.
  55723. * @return {object|null|undefined} Selected DOM element if exists.
  55724. null if query yields no results.
  55725. undefined if `selector` is not a valid selector.
  55726. */
  55727. function validateAndGetQuerySelector (selector) {
  55728. try {
  55729. var el = document.querySelector(selector);
  55730. if (!el) {
  55731. warn('No element was found matching the selector: "%s"', selector);
  55732. }
  55733. return el;
  55734. } catch (e) { // Capture exception if it's not a valid selector.
  55735. warn('"%s" is not a valid selector', selector);
  55736. return undefined;
  55737. }
  55738. }
  55739. module.exports = {
  55740. parseUrl: parseUrl,
  55741. validateSrc: validateSrc,
  55742. validateCubemapSrc: validateCubemapSrc
  55743. };
  55744. },{"./debug":172}],183:[function(_dereq_,module,exports){
  55745. /**
  55746. * Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5").
  55747. * Some code adapted from `style-attr` (https://github.com/joshwnj/style-attr)
  55748. * by Josh Johnston (MIT License).
  55749. */
  55750. var DASH_REGEX = /-([a-z])/g;
  55751. /**
  55752. * Deserialize style-like string into an object of properties.
  55753. *
  55754. * @param {string} value - HTML attribute value.
  55755. * @param {object} obj - Reused object for object pooling.
  55756. * @returns {object} Property data.
  55757. */
  55758. module.exports.parse = function (value, obj) {
  55759. var parsedData;
  55760. if (typeof value !== 'string') { return value; }
  55761. parsedData = styleParse(value, obj);
  55762. // The style parser returns an object { "" : "test"} when fed a string
  55763. if (parsedData['']) { return value; }
  55764. return transformKeysToCamelCase(parsedData);
  55765. };
  55766. /**
  55767. * Serialize an object of properties into a style-like string.
  55768. *
  55769. * @param {object} data - Property data.
  55770. * @returns {string}
  55771. */
  55772. module.exports.stringify = function (data) {
  55773. if (typeof data === 'string') { return data; }
  55774. return styleStringify(data);
  55775. };
  55776. /**
  55777. * Converts string from hyphen to camelCase.
  55778. *
  55779. * @param {string} str - String to camelCase.
  55780. * @return {string} CamelCased string.
  55781. */
  55782. function toCamelCase (str) {
  55783. return str.replace(DASH_REGEX, upperCase);
  55784. }
  55785. module.exports.toCamelCase = toCamelCase;
  55786. /**
  55787. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  55788. * `maxValue`).
  55789. *
  55790. * @param {object} obj - The object to camelCase keys.
  55791. * @return {object} The object with keys camelCased.
  55792. */
  55793. function transformKeysToCamelCase (obj) {
  55794. var camelKey;
  55795. var key;
  55796. for (key in obj) {
  55797. camelKey = toCamelCase(key);
  55798. if (key === camelKey) { continue; }
  55799. obj[camelKey] = obj[key];
  55800. delete obj[key];
  55801. }
  55802. return obj;
  55803. }
  55804. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  55805. /**
  55806. * Split a string into chunks matching `<key>: <value>`
  55807. */
  55808. var getKeyValueChunks = (function () {
  55809. var chunks = [];
  55810. var hasUnclosedUrl = /url\([^)]+$/;
  55811. return function getKeyValueChunks (raw) {
  55812. var chunk = '';
  55813. var nextSplit;
  55814. var offset = 0;
  55815. var sep = ';';
  55816. chunks.length = 0;
  55817. while (offset < raw.length) {
  55818. nextSplit = raw.indexOf(sep, offset);
  55819. if (nextSplit === -1) { nextSplit = raw.length; }
  55820. chunk += raw.substring(offset, nextSplit);
  55821. // data URIs can contain semicolons, so make sure we get the whole thing
  55822. if (hasUnclosedUrl.test(chunk)) {
  55823. chunk += ';';
  55824. offset = nextSplit + 1;
  55825. continue;
  55826. }
  55827. chunks.push(chunk.trim());
  55828. chunk = '';
  55829. offset = nextSplit + 1;
  55830. }
  55831. return chunks;
  55832. };
  55833. })();
  55834. /**
  55835. * Convert a style attribute string to an object.
  55836. *
  55837. * @param {object} str - Attribute string.
  55838. * @param {object} obj - Object to reuse as a base, else a new one will be allocated.
  55839. */
  55840. function styleParse (str, obj) {
  55841. var chunks;
  55842. var i;
  55843. var item;
  55844. var pos;
  55845. var key;
  55846. var val;
  55847. obj = obj || {};
  55848. chunks = getKeyValueChunks(str);
  55849. for (i = 0; i < chunks.length; i++) {
  55850. item = chunks[i];
  55851. if (!item) { continue; }
  55852. // Split with `.indexOf` rather than `.split` because the value may also contain colons.
  55853. pos = item.indexOf(':');
  55854. key = item.substr(0, pos).trim();
  55855. val = item.substr(pos + 1).trim();
  55856. obj[key] = val;
  55857. }
  55858. return obj;
  55859. }
  55860. /**
  55861. * Convert an object into an attribute string
  55862. **/
  55863. function styleStringify (obj) {
  55864. var key;
  55865. var keyCount = 0;
  55866. var i = 0;
  55867. var str = '';
  55868. for (key in obj) { keyCount++; }
  55869. for (key in obj) {
  55870. str += (key + ': ' + obj[key]);
  55871. if (i < keyCount - 1) { str += '; '; }
  55872. i++;
  55873. }
  55874. return str;
  55875. }
  55876. function upperCase (str) { return str[1].toUpperCase(); }
  55877. },{}],184:[function(_dereq_,module,exports){
  55878. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  55879. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  55880. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  55881. /**
  55882. * Called on controller component `.play` handlers.
  55883. * Check if controller matches parameters and inject tracked-controls component.
  55884. * Handle event listeners.
  55885. * Generate controllerconnected or controllerdisconnected events.
  55886. *
  55887. * @param {object} component - Tracked controls component.
  55888. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55889. * @param {object} queryObject - Map of values to match.
  55890. */
  55891. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  55892. var el = component.el;
  55893. var controller;
  55894. var hasWebXR = el.sceneEl.hasWebXR;
  55895. var isControllerPresent = hasWebXR ? isControllerPresentWebXR : isControllerPresentWebVR;
  55896. var isPresent;
  55897. controller = isControllerPresent(component, idPrefix, queryObject);
  55898. isPresent = !!controller;
  55899. // If component was previously paused and now playing, re-add event listeners.
  55900. // Handle the event listeners here since this helper method is control of calling
  55901. // `.addEventListeners` and `.removeEventListeners`.
  55902. if (component.controllerPresent && !component.controllerEventsActive && !hasWebXR) {
  55903. component.addEventListeners();
  55904. }
  55905. // Nothing changed, no need to do anything.
  55906. if (isPresent === component.controllerPresent) { return isPresent; }
  55907. component.controllerPresent = isPresent;
  55908. // Update controller presence.
  55909. if (isPresent) {
  55910. component.injectTrackedControls();
  55911. if (!hasWebXR) { component.addEventListeners(); }
  55912. el.emit('controllerconnected', {name: component.name, component: component});
  55913. } else {
  55914. component.removeEventListeners();
  55915. el.emit('controllerdisconnected', {name: component.name, component: component});
  55916. }
  55917. };
  55918. /**
  55919. * Enumerate controller (that have pose) and check if they match parameters for WebVR
  55920. *
  55921. * @param {object} component - Tracked controls component.
  55922. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55923. * @param {object} queryObject - Map of values to match.
  55924. */
  55925. function isControllerPresentWebVR (component, idPrefix, queryObject) {
  55926. var gamepads;
  55927. var sceneEl = component.el.sceneEl;
  55928. var trackedControlsSystem;
  55929. var filterControllerIndex = queryObject.index || 0;
  55930. if (!idPrefix) { return false; }
  55931. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webvr'];
  55932. if (!trackedControlsSystem) { return false; }
  55933. gamepads = trackedControlsSystem.controllers;
  55934. if (!gamepads.length) { return false; }
  55935. return !!findMatchingControllerWebVR(gamepads, null, idPrefix, queryObject.hand,
  55936. filterControllerIndex);
  55937. }
  55938. /**
  55939. *
  55940. * @param {object} component - Tracked controls component.
  55941. */
  55942. function isControllerPresentWebXR (component, idPrefix, queryObject) {
  55943. var controllers;
  55944. var sceneEl = component.el.sceneEl;
  55945. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls-webxr'];
  55946. if (!trackedControlsSystem) { return false; }
  55947. controllers = trackedControlsSystem.controllers;
  55948. if (!controllers || !controllers.length) { return false; }
  55949. return findMatchingControllerWebXR(controllers, queryObject.hand);
  55950. }
  55951. module.exports.isControllerPresentWebVR = isControllerPresentWebVR;
  55952. module.exports.isControllerPresentWebXR = isControllerPresentWebXR;
  55953. /**
  55954. * Walk through the given controllers to find any where the device ID equals
  55955. * filterIdExact, or startsWith filterIdPrefix.
  55956. * A controller where this considered true is considered a 'match'.
  55957. *
  55958. * For each matching controller:
  55959. * If filterHand is set, and the controller:
  55960. * is handed, we further verify that controller.hand equals filterHand.
  55961. * is unhanded (controller.hand is ''), we skip until we have found a
  55962. * number of matching controllers that equals filterControllerIndex
  55963. * If filterHand is not set, we skip until we have found the nth matching
  55964. * controller, where n equals filterControllerIndex
  55965. *
  55966. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND
  55967. * one or both of: [filterHand, filterControllerIndex]
  55968. *
  55969. * @param {object} controllers - Array of gamepads to search
  55970. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  55971. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  55972. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  55973. * @param {object} filterControllerIndex - Find the nth matching controller,
  55974. * where n equals filterControllerIndex. defaults to 0.
  55975. */
  55976. function findMatchingControllerWebVR (controllers, filterIdExact, filterIdPrefix, filterHand,
  55977. filterControllerIndex) {
  55978. var controller;
  55979. var i;
  55980. var matchingControllerOccurence = 0;
  55981. var targetControllerMatch = filterControllerIndex || 0;
  55982. for (i = 0; i < controllers.length; i++) {
  55983. controller = controllers[i];
  55984. // Determine if the controller ID matches our criteria.
  55985. if (filterIdPrefix && !controller.id.startsWith(filterIdPrefix)) {
  55986. continue;
  55987. }
  55988. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  55989. // If the hand filter and controller handedness are defined we compare them.
  55990. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  55991. // If we have detected an unhanded controller and the component was asking
  55992. // for a particular hand, we need to treat the controllers in the array as
  55993. // pairs of controllers. This effectively means that we need to skip
  55994. // NUM_HANDS matches for each controller number, instead of 1.
  55995. if (filterHand && !controller.hand) {
  55996. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  55997. }
  55998. // We are looking for the nth occurence of a matching controller
  55999. // (n equals targetControllerMatch).
  56000. if (matchingControllerOccurence === targetControllerMatch) { return controller; }
  56001. ++matchingControllerOccurence;
  56002. }
  56003. return undefined;
  56004. }
  56005. function findMatchingControllerWebXR (controllers, handedness) {
  56006. var i;
  56007. var controllerHandedness;
  56008. for (i = 0; i < controllers.length; i++) {
  56009. controllerHandedness = controllers[i].handedness;
  56010. if (!handedness || (controllerHandedness === '' && handedness === 'right') ||
  56011. controllers[i].handedness === handedness) {
  56012. return controllers[i];
  56013. }
  56014. }
  56015. return undefined;
  56016. }
  56017. module.exports.findMatchingControllerWebVR = findMatchingControllerWebVR;
  56018. module.exports.findMatchingControllerWebXR = findMatchingControllerWebXR;
  56019. /**
  56020. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  56021. *
  56022. * @param {object} component - Controller component in use.
  56023. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  56024. * @param {object} evt - Event to process.
  56025. */
  56026. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  56027. var axes;
  56028. var buttonType;
  56029. var changed;
  56030. var detail;
  56031. var j;
  56032. for (buttonType in axesMapping) {
  56033. axes = axesMapping[buttonType];
  56034. changed = false;
  56035. for (j = 0; j < axes.length; j++) {
  56036. if (evt.detail.changed[axes[j]]) { changed = true; }
  56037. }
  56038. if (!changed) { continue; }
  56039. // Axis has changed. Emit the specific moved event with axis values in detail.
  56040. detail = {};
  56041. for (j = 0; j < axes.length; j++) {
  56042. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  56043. }
  56044. component.el.emit(buttonType + 'moved', detail);
  56045. }
  56046. };
  56047. /**
  56048. * Handle a button event and reemits the events.
  56049. *
  56050. * @param {string} id - id of the button.
  56051. * @param {string} evtName - name of the reemitted event
  56052. * @param {object} component - reference to the component
  56053. * @param {string} hand - handedness of the controller: left or right.
  56054. */
  56055. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  56056. var mapping = hand ? component.mapping[hand] : component.mapping;
  56057. var buttonName = mapping.buttons[id];
  56058. component.el.emit(buttonName + evtName);
  56059. if (component.updateModel) {
  56060. component.updateModel(buttonName, evtName);
  56061. }
  56062. };
  56063. },{"../constants":95}],185:[function(_dereq_,module,exports){
  56064. window.glStats = function () {
  56065. var _rS = null;
  56066. var _totalDrawArraysCalls = 0,
  56067. _totalDrawElementsCalls = 0,
  56068. _totalUseProgramCalls = 0,
  56069. _totalFaces = 0,
  56070. _totalVertices = 0,
  56071. _totalPoints = 0,
  56072. _totalBindTexures = 0;
  56073. function _h ( f, c ) {
  56074. return function () {
  56075. c.apply( this, arguments );
  56076. f.apply( this, arguments );
  56077. };
  56078. }
  56079. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  56080. _totalDrawArraysCalls++;
  56081. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  56082. else _totalVertices += arguments[ 2 ];
  56083. } );
  56084. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  56085. _totalDrawElementsCalls++;
  56086. _totalFaces += arguments[ 1 ] / 3;
  56087. _totalVertices += arguments[ 1 ];
  56088. } );
  56089. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  56090. _totalUseProgramCalls++;
  56091. } );
  56092. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  56093. _totalBindTexures++;
  56094. } );
  56095. var _values = {
  56096. allcalls: {
  56097. over: 3000,
  56098. caption: 'Calls (hook)'
  56099. },
  56100. drawelements: {
  56101. caption: 'drawElements (hook)'
  56102. },
  56103. drawarrays: {
  56104. caption: 'drawArrays (hook)'
  56105. }
  56106. };
  56107. var _groups = [ {
  56108. caption: 'WebGL',
  56109. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  56110. } ];
  56111. var _fractions = [ {
  56112. base: 'allcalls',
  56113. steps: [ 'drawelements', 'drawarrays' ]
  56114. } ];
  56115. function _update () {
  56116. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  56117. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  56118. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  56119. _rS( 'bindTexture' ).set( _totalBindTexures );
  56120. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  56121. _rS( 'glfaces' ).set( _totalFaces );
  56122. _rS( 'glvertices' ).set( _totalVertices );
  56123. _rS( 'glpoints' ).set( _totalPoints );
  56124. }
  56125. function _start () {
  56126. _totalDrawArraysCalls = 0;
  56127. _totalDrawElementsCalls = 0;
  56128. _totalUseProgramCalls = 0;
  56129. _totalFaces = 0;
  56130. _totalVertices = 0;
  56131. _totalPoints = 0;
  56132. _totalBindTexures = 0;
  56133. }
  56134. function _end () {}
  56135. function _attach ( r ) {
  56136. _rS = r;
  56137. }
  56138. return {
  56139. update: _update,
  56140. start: _start,
  56141. end: _end,
  56142. attach: _attach,
  56143. values: _values,
  56144. groups: _groups,
  56145. fractions: _fractions
  56146. };
  56147. };
  56148. window.threeStats = function ( renderer ) {
  56149. var _rS = null;
  56150. var _values = {
  56151. 'renderer.info.memory.geometries': {
  56152. caption: 'Geometries'
  56153. },
  56154. 'renderer.info.memory.textures': {
  56155. caption: 'Textures'
  56156. },
  56157. 'renderer.info.programs': {
  56158. caption: 'Programs'
  56159. },
  56160. 'renderer.info.render.calls': {
  56161. caption: 'Calls'
  56162. },
  56163. 'renderer.info.render.triangles': {
  56164. caption: 'Triangles',
  56165. over: 1000
  56166. },
  56167. 'renderer.info.render.points': {
  56168. caption: 'Points'
  56169. }
  56170. };
  56171. var _groups = [ {
  56172. caption: 'Three.js - Memory',
  56173. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  56174. }, {
  56175. caption: 'Three.js - Render',
  56176. values: [ 'renderer.info.render.calls', 'renderer.info.render.triangles', 'renderer.info.render.points' ]
  56177. } ];
  56178. var _fractions = [];
  56179. function _update () {
  56180. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  56181. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  56182. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  56183. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  56184. _rS( 'renderer.info.render.triangles' ).set( renderer.info.render.triangles );
  56185. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  56186. }
  56187. function _start () {}
  56188. function _end () {}
  56189. function _attach ( r ) {
  56190. _rS = r;
  56191. }
  56192. return {
  56193. update: _update,
  56194. start: _start,
  56195. end: _end,
  56196. attach: _attach,
  56197. values: _values,
  56198. groups: _groups,
  56199. fractions: _fractions
  56200. };
  56201. };
  56202. /*
  56203. * From https://github.com/paulirish/memory-stats.js
  56204. */
  56205. window.BrowserStats = function () {
  56206. var _rS = null;
  56207. var _usedJSHeapSize = 0,
  56208. _totalJSHeapSize = 0;
  56209. if ( window.performance && !performance.memory ) {
  56210. performance.memory = {
  56211. usedJSHeapSize: 0,
  56212. totalJSHeapSize: 0
  56213. };
  56214. }
  56215. if ( performance.memory.totalJSHeapSize === 0 ) {
  56216. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  56217. }
  56218. var _values = {
  56219. memory: {
  56220. caption: 'Used Memory',
  56221. average: true,
  56222. avgMs: 1000,
  56223. over: 22
  56224. },
  56225. total: {
  56226. caption: 'Total Memory'
  56227. }
  56228. };
  56229. var _groups = [ {
  56230. caption: 'Browser',
  56231. values: [ 'memory', 'total' ]
  56232. } ];
  56233. var _fractions = [ {
  56234. base: 'total',
  56235. steps: [ 'memory' ]
  56236. } ];
  56237. var log1024 = Math.log( 1024 );
  56238. function _size ( v ) {
  56239. var precision = 100; //Math.pow(10, 2);
  56240. var i = Math.floor( Math.log( v ) / log1024 );
  56241. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  56242. }
  56243. function _update () {
  56244. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  56245. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  56246. _rS( 'memory' ).set( _usedJSHeapSize );
  56247. _rS( 'total' ).set( _totalJSHeapSize );
  56248. }
  56249. function _start () {
  56250. _usedJSHeapSize = 0;
  56251. }
  56252. function _end () {}
  56253. function _attach ( r ) {
  56254. _rS = r;
  56255. }
  56256. return {
  56257. update: _update,
  56258. start: _start,
  56259. end: _end,
  56260. attach: _attach,
  56261. values: _values,
  56262. groups: _groups,
  56263. fractions: _fractions
  56264. };
  56265. };
  56266. if (typeof module === 'object') {
  56267. module.exports = {
  56268. glStats: window.glStats,
  56269. threeStats: window.threeStats,
  56270. BrowserStats: window.BrowserStats
  56271. };
  56272. }
  56273. },{}],186:[function(_dereq_,module,exports){
  56274. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  56275. 'use strict';
  56276. ( function () {
  56277. if ( 'performance' in window == false ) {
  56278. window.performance = {};
  56279. }
  56280. var performance = window.performance;
  56281. if ( 'now' in performance == false ) {
  56282. var nowOffset = Date.now();
  56283. if ( performance.timing && performance.timing.navigationStart ) {
  56284. nowOffset = performance.timing.navigationStart;
  56285. }
  56286. performance.now = function now () {
  56287. return Date.now() - nowOffset;
  56288. };
  56289. }
  56290. if( !performance.mark ) {
  56291. performance.mark = function(){}
  56292. }
  56293. if( !performance.measure ) {
  56294. performance.measure = function(){}
  56295. }
  56296. } )();
  56297. window.rStats = function rStats ( settings ) {
  56298. function iterateKeys ( array, callback ) {
  56299. var keys = Object.keys( array );
  56300. for ( var j = 0, l = keys.length; j < l; j++ ) {
  56301. callback( keys[ j ] );
  56302. }
  56303. }
  56304. function importCSS ( url ) {
  56305. var element = document.createElement( 'link' );
  56306. element.href = url;
  56307. element.rel = 'stylesheet';
  56308. element.type = 'text/css';
  56309. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  56310. }
  56311. var _settings = settings || {};
  56312. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  56313. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  56314. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  56315. var _css = _settings.css || [ _cssFont, _cssRStats ];
  56316. _css.forEach(function (uri) {
  56317. importCSS( uri );
  56318. });
  56319. if ( !_settings.values ) _settings.values = {};
  56320. var _base, _div, _elHeight = 10, _elWidth = 200;
  56321. var _perfCounters = {};
  56322. function Graph ( _dom, _id, _defArg ) {
  56323. var _def = _defArg || {};
  56324. var _canvas = document.createElement( 'canvas' ),
  56325. _ctx = _canvas.getContext( '2d' ),
  56326. _max = 0,
  56327. _current = 0;
  56328. var c = _def.color ? _def.color : '#666666';
  56329. var _dotCanvas = document.createElement( 'canvas' ),
  56330. _dotCtx = _dotCanvas.getContext( '2d' );
  56331. _dotCanvas.width = 1;
  56332. _dotCanvas.height = 2 * _elHeight;
  56333. _dotCtx.fillStyle = '#444444';
  56334. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56335. _dotCtx.fillStyle = c;
  56336. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56337. _dotCtx.fillStyle = '#ffffff';
  56338. _dotCtx.globalAlpha = 0.5;
  56339. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  56340. _dotCtx.globalAlpha = 1;
  56341. var _alarmCanvas = document.createElement( 'canvas' ),
  56342. _alarmCtx = _alarmCanvas.getContext( '2d' );
  56343. _alarmCanvas.width = 1;
  56344. _alarmCanvas.height = 2 * _elHeight;
  56345. _alarmCtx.fillStyle = '#444444';
  56346. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56347. _alarmCtx.fillStyle = '#b70000';
  56348. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56349. _alarmCtx.globalAlpha = 0.5;
  56350. _alarmCtx.fillStyle = '#ffffff';
  56351. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  56352. _alarmCtx.globalAlpha = 1;
  56353. function _init () {
  56354. _canvas.width = _elWidth;
  56355. _canvas.height = _elHeight;
  56356. _canvas.style.width = _canvas.width + 'px';
  56357. _canvas.style.height = _canvas.height + 'px';
  56358. _canvas.className = 'rs-canvas';
  56359. _dom.appendChild( _canvas );
  56360. _ctx.fillStyle = '#444444';
  56361. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56362. }
  56363. function _draw ( v, alarm ) {
  56364. _current += ( v - _current ) * 0.1;
  56365. _max *= 0.99;
  56366. if ( _current > _max ) _max = _current;
  56367. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56368. if ( alarm ) {
  56369. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56370. } else {
  56371. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56372. }
  56373. }
  56374. _init();
  56375. return {
  56376. draw: _draw
  56377. };
  56378. }
  56379. function StackGraph ( _dom, _num ) {
  56380. var _canvas = document.createElement( 'canvas' ),
  56381. _ctx = _canvas.getContext( '2d' );
  56382. function _init () {
  56383. _canvas.width = _elWidth;
  56384. _canvas.height = _elHeight * _num;
  56385. _canvas.style.width = _canvas.width + 'px';
  56386. _canvas.style.height = _canvas.height + 'px';
  56387. _canvas.className = 'rs-canvas';
  56388. _dom.appendChild( _canvas );
  56389. _ctx.fillStyle = '#444444';
  56390. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56391. }
  56392. function _draw ( v ) {
  56393. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56394. var th = 0;
  56395. iterateKeys( v, function ( j ) {
  56396. var h = v[ j ] * _canvas.height;
  56397. _ctx.fillStyle = _colours[ j ];
  56398. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  56399. th += h;
  56400. } );
  56401. }
  56402. _init();
  56403. return {
  56404. draw: _draw
  56405. };
  56406. }
  56407. function PerfCounter ( id, group ) {
  56408. var _id = id,
  56409. _time,
  56410. _value = 0,
  56411. _total = 0,
  56412. _averageValue = 0,
  56413. _accumValue = 0,
  56414. _accumStart = performance.now(),
  56415. _accumSamples = 0,
  56416. _dom = document.createElement( 'div' ),
  56417. _spanId = document.createElement( 'span' ),
  56418. _spanValue = document.createElement( 'div' ),
  56419. _spanValueText = document.createTextNode( '' ),
  56420. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  56421. _graph = new Graph( _dom, _id, _def ),
  56422. _started = false;
  56423. _spanId.className = 'rs-counter-id';
  56424. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  56425. _spanValue.className = 'rs-counter-value';
  56426. _spanValue.appendChild( _spanValueText );
  56427. _dom.appendChild( _spanId );
  56428. _dom.appendChild( _spanValue );
  56429. if ( group ) group.div.appendChild( _dom );
  56430. else _div.appendChild( _dom );
  56431. _time = performance.now();
  56432. function _average ( v ) {
  56433. if ( _def && _def.average ) {
  56434. _accumValue += v;
  56435. _accumSamples++;
  56436. var t = performance.now();
  56437. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  56438. _averageValue = _accumValue / _accumSamples;
  56439. _accumValue = 0;
  56440. _accumStart = t;
  56441. _accumSamples = 0;
  56442. }
  56443. }
  56444. }
  56445. function _start () {
  56446. _time = performance.now();
  56447. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  56448. _started = true;
  56449. }
  56450. function _end () {
  56451. _value = performance.now() - _time;
  56452. if( _settings.userTimingAPI ) {
  56453. performance.mark( _id + '-end' );
  56454. if( _started ) {
  56455. performance.measure( _id, _id + '-start', _id + '-end' );
  56456. }
  56457. }
  56458. _average( _value );
  56459. }
  56460. function _tick () {
  56461. _end();
  56462. _start();
  56463. }
  56464. function _draw () {
  56465. var v = ( _def && _def.average ) ? _averageValue : _value;
  56466. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  56467. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  56468. _graph.draw( _value, a );
  56469. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  56470. }
  56471. function _frame () {
  56472. var t = performance.now();
  56473. var e = t - _time;
  56474. _total++;
  56475. if ( e > 1000 ) {
  56476. if ( _def && _def.interpolate === false ) {
  56477. _value = _total;
  56478. } else {
  56479. _value = _total * 1000 / e;
  56480. }
  56481. _total = 0;
  56482. _time = t;
  56483. _average( _value );
  56484. }
  56485. }
  56486. function _set ( v ) {
  56487. _value = v;
  56488. _average( _value );
  56489. }
  56490. return {
  56491. set: _set,
  56492. start: _start,
  56493. tick: _tick,
  56494. end: _end,
  56495. frame: _frame,
  56496. value: function () {
  56497. return _value;
  56498. },
  56499. draw: _draw
  56500. };
  56501. }
  56502. function sample () {
  56503. var _value = 0;
  56504. function _set ( v ) {
  56505. _value = v;
  56506. }
  56507. return {
  56508. set: _set,
  56509. value: function () {
  56510. return _value;
  56511. }
  56512. };
  56513. }
  56514. function _perf ( idArg ) {
  56515. var id = idArg.toLowerCase();
  56516. if ( id === undefined ) id = 'default';
  56517. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  56518. var group = null;
  56519. if ( _settings && _settings.groups ) {
  56520. iterateKeys( _settings.groups, function ( j ) {
  56521. var g = _settings.groups[ parseInt( j, 10 ) ];
  56522. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  56523. group = g;
  56524. }
  56525. } );
  56526. }
  56527. var p = new PerfCounter( id, group );
  56528. _perfCounters[ id ] = p;
  56529. return p;
  56530. }
  56531. function _init () {
  56532. if ( _settings.plugins ) {
  56533. if ( !_settings.values ) _settings.values = {};
  56534. if ( !_settings.groups ) _settings.groups = [];
  56535. if ( !_settings.fractions ) _settings.fractions = [];
  56536. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  56537. _settings.plugins[ j ].attach( _perf );
  56538. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  56539. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  56540. } );
  56541. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  56542. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  56543. }
  56544. } else {
  56545. _settings.plugins = {};
  56546. }
  56547. _base = document.createElement( 'div' );
  56548. _base.className = 'rs-base';
  56549. _div = document.createElement( 'div' );
  56550. _div.className = 'rs-container';
  56551. _div.style.height = 'auto';
  56552. _base.appendChild( _div );
  56553. document.body.appendChild( _base );
  56554. if ( !_settings ) return;
  56555. if ( _settings.groups ) {
  56556. iterateKeys( _settings.groups, function ( j ) {
  56557. var g = _settings.groups[ parseInt( j, 10 ) ];
  56558. var div = document.createElement( 'div' );
  56559. div.className = 'rs-group';
  56560. g.div = div;
  56561. var h1 = document.createElement( 'h1' );
  56562. h1.textContent = g.caption;
  56563. h1.addEventListener( 'click', function ( e ) {
  56564. this.classList.toggle( 'hidden' );
  56565. e.preventDefault();
  56566. }.bind( div ) );
  56567. _div.appendChild( h1 );
  56568. _div.appendChild( div );
  56569. } );
  56570. }
  56571. if ( _settings.fractions ) {
  56572. iterateKeys( _settings.fractions, function ( j ) {
  56573. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56574. var div = document.createElement( 'div' );
  56575. div.className = 'rs-fraction';
  56576. var legend = document.createElement( 'div' );
  56577. legend.className = 'rs-legend';
  56578. var h = 0;
  56579. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56580. var p = document.createElement( 'p' );
  56581. p.textContent = _settings.fractions[ j ].steps[ k ];
  56582. p.style.color = _colours[ h ];
  56583. legend.appendChild( p );
  56584. h++;
  56585. } );
  56586. div.appendChild( legend );
  56587. div.style.height = h * _elHeight + 'px';
  56588. f.div = div;
  56589. var graph = new StackGraph( div, h );
  56590. f.graph = graph;
  56591. _div.appendChild( div );
  56592. } );
  56593. }
  56594. }
  56595. function _update () {
  56596. iterateKeys( _settings.plugins, function ( j ) {
  56597. _settings.plugins[ j ].update();
  56598. } );
  56599. iterateKeys( _perfCounters, function ( j ) {
  56600. _perfCounters[ j ].draw();
  56601. } );
  56602. if ( _settings && _settings.fractions ) {
  56603. iterateKeys( _settings.fractions, function ( j ) {
  56604. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56605. var v = [];
  56606. var base = _perfCounters[ f.base.toLowerCase() ];
  56607. if ( base ) {
  56608. base = base.value();
  56609. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56610. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  56611. var val = _perfCounters[ s ];
  56612. if ( val ) {
  56613. v.push( val.value() / base );
  56614. }
  56615. } );
  56616. }
  56617. f.graph.draw( v );
  56618. } );
  56619. }
  56620. /*if( _height != _div.clientHeight ) {
  56621. _height = _div.clientHeight;
  56622. _base.style.height = _height + 2 * _elHeight + 'px';
  56623. console.log( _base.clientHeight );
  56624. }*/
  56625. }
  56626. _init();
  56627. return function ( id ) {
  56628. if ( id ) return _perf( id );
  56629. return {
  56630. element: _base,
  56631. update: _update
  56632. };
  56633. };
  56634. }
  56635. if (typeof module === 'object') {
  56636. module.exports = window.rStats;
  56637. }
  56638. },{}],187:[function(_dereq_,module,exports){
  56639. // https://stackoverflow.com/a/36213464
  56640. if (!String.prototype.startsWith) {
  56641. String.prototype.startsWith = function(searchString, position){
  56642. position = position || 0;
  56643. return this.substr(position, searchString.length) === searchString;
  56644. };
  56645. }
  56646. },{}],188:[function(_dereq_,module,exports){
  56647. /*
  56648. * Copyright 2015 Google Inc. All Rights Reserved.
  56649. * Licensed under the Apache License, Version 2.0 (the "License");
  56650. * you may not use this file except in compliance with the License.
  56651. * You may obtain a copy of the License at
  56652. *
  56653. * http://www.apache.org/licenses/LICENSE-2.0
  56654. *
  56655. * Unless required by applicable law or agreed to in writing, software
  56656. * distributed under the License is distributed on an "AS IS" BASIS,
  56657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56658. * See the License for the specific language governing permissions and
  56659. * limitations under the License.
  56660. */
  56661. var Util = {};
  56662. Util.base64 = function(mimeType, base64) {
  56663. return 'data:' + mimeType + ';base64,' + base64;
  56664. };
  56665. Util.isMobile = function() {
  56666. var check = false;
  56667. (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);
  56668. return check;
  56669. };
  56670. Util.isIOS = function() {
  56671. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  56672. };
  56673. Util.isIFrame = function() {
  56674. try {
  56675. return window.self !== window.top;
  56676. } catch (e) {
  56677. return true;
  56678. }
  56679. };
  56680. Util.appendQueryParameter = function(url, key, value) {
  56681. // Determine delimiter based on if the URL already GET parameters in it.
  56682. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  56683. url += delimiter + key + '=' + value;
  56684. return url;
  56685. };
  56686. // From http://goo.gl/4WX3tg
  56687. Util.getQueryParameter = function(name) {
  56688. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  56689. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  56690. results = regex.exec(location.search);
  56691. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  56692. };
  56693. Util.isLandscapeMode = function() {
  56694. return (window.orientation == 90 || window.orientation == -90);
  56695. };
  56696. module.exports = Util;
  56697. },{}],189:[function(_dereq_,module,exports){
  56698. /*
  56699. * Copyright 2015 Google Inc. All Rights Reserved.
  56700. * Licensed under the Apache License, Version 2.0 (the "License");
  56701. * you may not use this file except in compliance with the License.
  56702. * You may obtain a copy of the License at
  56703. *
  56704. * http://www.apache.org/licenses/LICENSE-2.0
  56705. *
  56706. * Unless required by applicable law or agreed to in writing, software
  56707. * distributed under the License is distributed on an "AS IS" BASIS,
  56708. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56709. * See the License for the specific language governing permissions and
  56710. * limitations under the License.
  56711. */
  56712. var Util = _dereq_('./util.js');
  56713. /**
  56714. * Android and iOS compatible wakelock implementation.
  56715. *
  56716. * Refactored thanks to dkovalev@.
  56717. */
  56718. function AndroidWakeLock() {
  56719. var video = document.createElement('video');
  56720. video.addEventListener('ended', function() {
  56721. video.play();
  56722. });
  56723. this.request = function() {
  56724. if (video.paused) {
  56725. // Base64 version of videos_src/no-sleep-60s.webm.
  56726. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  56727. video.play();
  56728. }
  56729. };
  56730. this.release = function() {
  56731. video.pause();
  56732. video.src = '';
  56733. };
  56734. }
  56735. function iOSWakeLock() {
  56736. var timer = null;
  56737. this.request = function() {
  56738. if (!timer) {
  56739. timer = setInterval(function() {
  56740. window.location.href = '/';
  56741. setTimeout(window.stop, 0);
  56742. }, 15000);
  56743. }
  56744. }
  56745. this.release = function() {
  56746. if (timer) {
  56747. clearInterval(timer);
  56748. timer = null;
  56749. }
  56750. }
  56751. }
  56752. function getWakeLock() {
  56753. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  56754. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  56755. return iOSWakeLock;
  56756. } else {
  56757. return AndroidWakeLock;
  56758. }
  56759. }
  56760. module.exports = getWakeLock();
  56761. },{"./util.js":188}]},{},[149])(149)
  56762. });
  56763. //# sourceMappingURL=aframe-master.js.map