aframe-master.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563
  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 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})({1:[function(_dereq_,module,exports){
  2. (function (process){
  3. /**
  4. * Tween.js - Licensed under the MIT license
  5. * https://github.com/tweenjs/tween.js
  6. * ----------------------------------------------
  7. *
  8. * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
  9. * Thank you all, you're awesome!
  10. */
  11. var TWEEN = TWEEN || (function () {
  12. var _tweens = [];
  13. return {
  14. getAll: function () {
  15. return _tweens;
  16. },
  17. removeAll: function () {
  18. _tweens = [];
  19. },
  20. add: function (tween) {
  21. _tweens.push(tween);
  22. },
  23. remove: function (tween) {
  24. var i = _tweens.indexOf(tween);
  25. if (i !== -1) {
  26. _tweens.splice(i, 1);
  27. }
  28. },
  29. update: function (time, preserve) {
  30. if (_tweens.length === 0) {
  31. return false;
  32. }
  33. var i = 0;
  34. time = time !== undefined ? time : TWEEN.now();
  35. while (i < _tweens.length) {
  36. if (_tweens[i].update(time) || preserve) {
  37. i++;
  38. } else {
  39. _tweens.splice(i, 1);
  40. }
  41. }
  42. return true;
  43. }
  44. };
  45. })();
  46. // Include a performance.now polyfill.
  47. // In node.js, use process.hrtime.
  48. if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') {
  49. TWEEN.now = function () {
  50. var time = process.hrtime();
  51. // Convert [seconds, nanoseconds] to milliseconds.
  52. return time[0] * 1000 + time[1] / 1000000;
  53. };
  54. }
  55. // In a browser, use window.performance.now if it is available.
  56. else if (typeof (window) !== 'undefined' &&
  57. window.performance !== undefined &&
  58. window.performance.now !== undefined) {
  59. // This must be bound, because directly assigning this function
  60. // leads to an invocation exception in Chrome.
  61. TWEEN.now = window.performance.now.bind(window.performance);
  62. }
  63. // Use Date.now if it is available.
  64. else if (Date.now !== undefined) {
  65. TWEEN.now = Date.now;
  66. }
  67. // Otherwise, use 'new Date().getTime()'.
  68. else {
  69. TWEEN.now = function () {
  70. return new Date().getTime();
  71. };
  72. }
  73. TWEEN.Tween = function (object) {
  74. var _object = object;
  75. var _valuesStart = {};
  76. var _valuesEnd = {};
  77. var _valuesStartRepeat = {};
  78. var _duration = 1000;
  79. var _repeat = 0;
  80. var _repeatDelayTime;
  81. var _yoyo = false;
  82. var _isPlaying = false;
  83. var _reversed = false;
  84. var _delayTime = 0;
  85. var _startTime = null;
  86. var _easingFunction = TWEEN.Easing.Linear.None;
  87. var _interpolationFunction = TWEEN.Interpolation.Linear;
  88. var _chainedTweens = [];
  89. var _onStartCallback = null;
  90. var _onStartCallbackFired = false;
  91. var _onUpdateCallback = null;
  92. var _onCompleteCallback = null;
  93. var _onStopCallback = null;
  94. this.to = function (properties, duration) {
  95. _valuesEnd = properties;
  96. if (duration !== undefined) {
  97. _duration = duration;
  98. }
  99. return this;
  100. };
  101. this.start = function (time) {
  102. TWEEN.add(this);
  103. _isPlaying = true;
  104. _onStartCallbackFired = false;
  105. _startTime = time !== undefined ? time : TWEEN.now();
  106. _startTime += _delayTime;
  107. for (var property in _valuesEnd) {
  108. // Check if an Array was provided as property value
  109. if (_valuesEnd[property] instanceof Array) {
  110. if (_valuesEnd[property].length === 0) {
  111. continue;
  112. }
  113. // Create a local copy of the Array with the start value at the front
  114. _valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]);
  115. }
  116. // If `to()` specifies a property that doesn't exist in the source object,
  117. // we should not set that property in the object
  118. if (_object[property] === undefined) {
  119. continue;
  120. }
  121. // Save the starting value.
  122. _valuesStart[property] = _object[property];
  123. if ((_valuesStart[property] instanceof Array) === false) {
  124. _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  125. }
  126. _valuesStartRepeat[property] = _valuesStart[property] || 0;
  127. }
  128. return this;
  129. };
  130. this.stop = function () {
  131. if (!_isPlaying) {
  132. return this;
  133. }
  134. TWEEN.remove(this);
  135. _isPlaying = false;
  136. if (_onStopCallback !== null) {
  137. _onStopCallback.call(_object, _object);
  138. }
  139. this.stopChainedTweens();
  140. return this;
  141. };
  142. this.end = function () {
  143. this.update(_startTime + _duration);
  144. return this;
  145. };
  146. this.stopChainedTweens = function () {
  147. for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  148. _chainedTweens[i].stop();
  149. }
  150. };
  151. this.delay = function (amount) {
  152. _delayTime = amount;
  153. return this;
  154. };
  155. this.repeat = function (times) {
  156. _repeat = times;
  157. return this;
  158. };
  159. this.repeatDelay = function (amount) {
  160. _repeatDelayTime = amount;
  161. return this;
  162. };
  163. this.yoyo = function (yoyo) {
  164. _yoyo = yoyo;
  165. return this;
  166. };
  167. this.easing = function (easing) {
  168. _easingFunction = easing;
  169. return this;
  170. };
  171. this.interpolation = function (interpolation) {
  172. _interpolationFunction = interpolation;
  173. return this;
  174. };
  175. this.chain = function () {
  176. _chainedTweens = arguments;
  177. return this;
  178. };
  179. this.onStart = function (callback) {
  180. _onStartCallback = callback;
  181. return this;
  182. };
  183. this.onUpdate = function (callback) {
  184. _onUpdateCallback = callback;
  185. return this;
  186. };
  187. this.onComplete = function (callback) {
  188. _onCompleteCallback = callback;
  189. return this;
  190. };
  191. this.onStop = function (callback) {
  192. _onStopCallback = callback;
  193. return this;
  194. };
  195. this.update = function (time) {
  196. var property;
  197. var elapsed;
  198. var value;
  199. if (time < _startTime) {
  200. return true;
  201. }
  202. if (_onStartCallbackFired === false) {
  203. if (_onStartCallback !== null) {
  204. _onStartCallback.call(_object, _object);
  205. }
  206. _onStartCallbackFired = true;
  207. }
  208. elapsed = (time - _startTime) / _duration;
  209. elapsed = elapsed > 1 ? 1 : elapsed;
  210. value = _easingFunction(elapsed);
  211. for (property in _valuesEnd) {
  212. // Don't update properties that do not exist in the source object
  213. if (_valuesStart[property] === undefined) {
  214. continue;
  215. }
  216. var start = _valuesStart[property] || 0;
  217. var end = _valuesEnd[property];
  218. if (end instanceof Array) {
  219. _object[property] = _interpolationFunction(end, value);
  220. } else {
  221. // Parses relative end values with start as base (e.g.: +10, -3)
  222. if (typeof (end) === 'string') {
  223. if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  224. end = start + parseFloat(end);
  225. } else {
  226. end = parseFloat(end);
  227. }
  228. }
  229. // Protect against non numeric properties.
  230. if (typeof (end) === 'number') {
  231. _object[property] = start + (end - start) * value;
  232. }
  233. }
  234. }
  235. if (_onUpdateCallback !== null) {
  236. _onUpdateCallback.call(_object, value);
  237. }
  238. if (elapsed === 1) {
  239. if (_repeat > 0) {
  240. if (isFinite(_repeat)) {
  241. _repeat--;
  242. }
  243. // Reassign starting values, restart by making startTime = now
  244. for (property in _valuesStartRepeat) {
  245. if (typeof (_valuesEnd[property]) === 'string') {
  246. _valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property]);
  247. }
  248. if (_yoyo) {
  249. var tmp = _valuesStartRepeat[property];
  250. _valuesStartRepeat[property] = _valuesEnd[property];
  251. _valuesEnd[property] = tmp;
  252. }
  253. _valuesStart[property] = _valuesStartRepeat[property];
  254. }
  255. if (_yoyo) {
  256. _reversed = !_reversed;
  257. }
  258. if (_repeatDelayTime !== undefined) {
  259. _startTime = time + _repeatDelayTime;
  260. } else {
  261. _startTime = time + _delayTime;
  262. }
  263. return true;
  264. } else {
  265. if (_onCompleteCallback !== null) {
  266. _onCompleteCallback.call(_object, _object);
  267. }
  268. for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  269. // Make the chained tweens start exactly at the time they should,
  270. // even if the `update()` method was called way past the duration of the tween
  271. _chainedTweens[i].start(_startTime + _duration);
  272. }
  273. return false;
  274. }
  275. }
  276. return true;
  277. };
  278. };
  279. TWEEN.Easing = {
  280. Linear: {
  281. None: function (k) {
  282. return k;
  283. }
  284. },
  285. Quadratic: {
  286. In: function (k) {
  287. return k * k;
  288. },
  289. Out: function (k) {
  290. return k * (2 - k);
  291. },
  292. InOut: function (k) {
  293. if ((k *= 2) < 1) {
  294. return 0.5 * k * k;
  295. }
  296. return - 0.5 * (--k * (k - 2) - 1);
  297. }
  298. },
  299. Cubic: {
  300. In: function (k) {
  301. return k * k * k;
  302. },
  303. Out: function (k) {
  304. return --k * k * k + 1;
  305. },
  306. InOut: function (k) {
  307. if ((k *= 2) < 1) {
  308. return 0.5 * k * k * k;
  309. }
  310. return 0.5 * ((k -= 2) * k * k + 2);
  311. }
  312. },
  313. Quartic: {
  314. In: function (k) {
  315. return k * k * k * k;
  316. },
  317. Out: function (k) {
  318. return 1 - (--k * k * k * k);
  319. },
  320. InOut: function (k) {
  321. if ((k *= 2) < 1) {
  322. return 0.5 * k * k * k * k;
  323. }
  324. return - 0.5 * ((k -= 2) * k * k * k - 2);
  325. }
  326. },
  327. Quintic: {
  328. In: function (k) {
  329. return k * k * k * k * k;
  330. },
  331. Out: function (k) {
  332. return --k * k * k * k * k + 1;
  333. },
  334. InOut: function (k) {
  335. if ((k *= 2) < 1) {
  336. return 0.5 * k * k * k * k * k;
  337. }
  338. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  339. }
  340. },
  341. Sinusoidal: {
  342. In: function (k) {
  343. return 1 - Math.cos(k * Math.PI / 2);
  344. },
  345. Out: function (k) {
  346. return Math.sin(k * Math.PI / 2);
  347. },
  348. InOut: function (k) {
  349. return 0.5 * (1 - Math.cos(Math.PI * k));
  350. }
  351. },
  352. Exponential: {
  353. In: function (k) {
  354. return k === 0 ? 0 : Math.pow(1024, k - 1);
  355. },
  356. Out: function (k) {
  357. return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);
  358. },
  359. InOut: function (k) {
  360. if (k === 0) {
  361. return 0;
  362. }
  363. if (k === 1) {
  364. return 1;
  365. }
  366. if ((k *= 2) < 1) {
  367. return 0.5 * Math.pow(1024, k - 1);
  368. }
  369. return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);
  370. }
  371. },
  372. Circular: {
  373. In: function (k) {
  374. return 1 - Math.sqrt(1 - k * k);
  375. },
  376. Out: function (k) {
  377. return Math.sqrt(1 - (--k * k));
  378. },
  379. InOut: function (k) {
  380. if ((k *= 2) < 1) {
  381. return - 0.5 * (Math.sqrt(1 - k * k) - 1);
  382. }
  383. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  384. }
  385. },
  386. Elastic: {
  387. In: function (k) {
  388. if (k === 0) {
  389. return 0;
  390. }
  391. if (k === 1) {
  392. return 1;
  393. }
  394. return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  395. },
  396. Out: function (k) {
  397. if (k === 0) {
  398. return 0;
  399. }
  400. if (k === 1) {
  401. return 1;
  402. }
  403. return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1;
  404. },
  405. InOut: function (k) {
  406. if (k === 0) {
  407. return 0;
  408. }
  409. if (k === 1) {
  410. return 1;
  411. }
  412. k *= 2;
  413. if (k < 1) {
  414. return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  415. }
  416. return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1;
  417. }
  418. },
  419. Back: {
  420. In: function (k) {
  421. var s = 1.70158;
  422. return k * k * ((s + 1) * k - s);
  423. },
  424. Out: function (k) {
  425. var s = 1.70158;
  426. return --k * k * ((s + 1) * k + s) + 1;
  427. },
  428. InOut: function (k) {
  429. var s = 1.70158 * 1.525;
  430. if ((k *= 2) < 1) {
  431. return 0.5 * (k * k * ((s + 1) * k - s));
  432. }
  433. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  434. }
  435. },
  436. Bounce: {
  437. In: function (k) {
  438. return 1 - TWEEN.Easing.Bounce.Out(1 - k);
  439. },
  440. Out: function (k) {
  441. if (k < (1 / 2.75)) {
  442. return 7.5625 * k * k;
  443. } else if (k < (2 / 2.75)) {
  444. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  445. } else if (k < (2.5 / 2.75)) {
  446. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  447. } else {
  448. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  449. }
  450. },
  451. InOut: function (k) {
  452. if (k < 0.5) {
  453. return TWEEN.Easing.Bounce.In(k * 2) * 0.5;
  454. }
  455. return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;
  456. }
  457. }
  458. };
  459. TWEEN.Interpolation = {
  460. Linear: function (v, k) {
  461. var m = v.length - 1;
  462. var f = m * k;
  463. var i = Math.floor(f);
  464. var fn = TWEEN.Interpolation.Utils.Linear;
  465. if (k < 0) {
  466. return fn(v[0], v[1], f);
  467. }
  468. if (k > 1) {
  469. return fn(v[m], v[m - 1], m - f);
  470. }
  471. return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
  472. },
  473. Bezier: function (v, k) {
  474. var b = 0;
  475. var n = v.length - 1;
  476. var pw = Math.pow;
  477. var bn = TWEEN.Interpolation.Utils.Bernstein;
  478. for (var i = 0; i <= n; i++) {
  479. b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  480. }
  481. return b;
  482. },
  483. CatmullRom: function (v, k) {
  484. var m = v.length - 1;
  485. var f = m * k;
  486. var i = Math.floor(f);
  487. var fn = TWEEN.Interpolation.Utils.CatmullRom;
  488. if (v[0] === v[m]) {
  489. if (k < 0) {
  490. i = Math.floor(f = m * (1 + k));
  491. }
  492. return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  493. } else {
  494. if (k < 0) {
  495. return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  496. }
  497. if (k > 1) {
  498. return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  499. }
  500. return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  501. }
  502. },
  503. Utils: {
  504. Linear: function (p0, p1, t) {
  505. return (p1 - p0) * t + p0;
  506. },
  507. Bernstein: function (n, i) {
  508. var fc = TWEEN.Interpolation.Utils.Factorial;
  509. return fc(n) / fc(i) / fc(n - i);
  510. },
  511. Factorial: (function () {
  512. var a = [1];
  513. return function (n) {
  514. var s = 1;
  515. if (a[n]) {
  516. return a[n];
  517. }
  518. for (var i = n; i > 1; i--) {
  519. s *= i;
  520. }
  521. a[n] = s;
  522. return s;
  523. };
  524. })(),
  525. CatmullRom: function (p0, p1, p2, p3, t) {
  526. var v0 = (p2 - p0) * 0.5;
  527. var v1 = (p3 - p1) * 0.5;
  528. var t2 = t * t;
  529. var t3 = t * t2;
  530. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  531. }
  532. }
  533. };
  534. // UMD (Universal Module Definition)
  535. (function (root) {
  536. if (typeof define === 'function' && define.amd) {
  537. // AMD
  538. define([], function () {
  539. return TWEEN;
  540. });
  541. } else if (typeof module !== 'undefined' && typeof exports === 'object') {
  542. // Node.js
  543. module.exports = TWEEN;
  544. } else if (root !== undefined) {
  545. // Global variable
  546. root.TWEEN = TWEEN;
  547. }
  548. })(this);
  549. }).call(this,_dereq_('_process'))
  550. },{"_process":33}],2:[function(_dereq_,module,exports){
  551. var str = Object.prototype.toString
  552. module.exports = anArray
  553. function anArray(arr) {
  554. return (
  555. arr.BYTES_PER_ELEMENT
  556. && str.call(arr.buffer) === '[object ArrayBuffer]'
  557. || Array.isArray(arr)
  558. )
  559. }
  560. },{}],3:[function(_dereq_,module,exports){
  561. module.exports = function numtype(num, def) {
  562. return typeof num === 'number'
  563. ? num
  564. : (typeof def === 'number' ? def : 0)
  565. }
  566. },{}],4:[function(_dereq_,module,exports){
  567. 'use strict'
  568. exports.byteLength = byteLength
  569. exports.toByteArray = toByteArray
  570. exports.fromByteArray = fromByteArray
  571. var lookup = []
  572. var revLookup = []
  573. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  574. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  575. for (var i = 0, len = code.length; i < len; ++i) {
  576. lookup[i] = code[i]
  577. revLookup[code.charCodeAt(i)] = i
  578. }
  579. revLookup['-'.charCodeAt(0)] = 62
  580. revLookup['_'.charCodeAt(0)] = 63
  581. function placeHoldersCount (b64) {
  582. var len = b64.length
  583. if (len % 4 > 0) {
  584. throw new Error('Invalid string. Length must be a multiple of 4')
  585. }
  586. // the number of equal signs (place holders)
  587. // if there are two placeholders, than the two characters before it
  588. // represent one byte
  589. // if there is only one, then the three characters before it represent 2 bytes
  590. // this is just a cheap hack to not do indexOf twice
  591. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  592. }
  593. function byteLength (b64) {
  594. // base64 is 4/3 + up to two characters of the original data
  595. return b64.length * 3 / 4 - placeHoldersCount(b64)
  596. }
  597. function toByteArray (b64) {
  598. var i, j, l, tmp, placeHolders, arr
  599. var len = b64.length
  600. placeHolders = placeHoldersCount(b64)
  601. arr = new Arr(len * 3 / 4 - placeHolders)
  602. // if there are placeholders, only get up to the last complete 4 chars
  603. l = placeHolders > 0 ? len - 4 : len
  604. var L = 0
  605. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  606. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  607. arr[L++] = (tmp >> 16) & 0xFF
  608. arr[L++] = (tmp >> 8) & 0xFF
  609. arr[L++] = tmp & 0xFF
  610. }
  611. if (placeHolders === 2) {
  612. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  613. arr[L++] = tmp & 0xFF
  614. } else if (placeHolders === 1) {
  615. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  616. arr[L++] = (tmp >> 8) & 0xFF
  617. arr[L++] = tmp & 0xFF
  618. }
  619. return arr
  620. }
  621. function tripletToBase64 (num) {
  622. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  623. }
  624. function encodeChunk (uint8, start, end) {
  625. var tmp
  626. var output = []
  627. for (var i = start; i < end; i += 3) {
  628. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  629. output.push(tripletToBase64(tmp))
  630. }
  631. return output.join('')
  632. }
  633. function fromByteArray (uint8) {
  634. var tmp
  635. var len = uint8.length
  636. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  637. var output = ''
  638. var parts = []
  639. var maxChunkLength = 16383 // must be multiple of 3
  640. // go through the array every three bytes, we'll deal with trailing stuff later
  641. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  642. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  643. }
  644. // pad the end with zeros, but make sure to not forget the extra bytes
  645. if (extraBytes === 1) {
  646. tmp = uint8[len - 1]
  647. output += lookup[tmp >> 2]
  648. output += lookup[(tmp << 4) & 0x3F]
  649. output += '=='
  650. } else if (extraBytes === 2) {
  651. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  652. output += lookup[tmp >> 10]
  653. output += lookup[(tmp >> 4) & 0x3F]
  654. output += lookup[(tmp << 2) & 0x3F]
  655. output += '='
  656. }
  657. parts.push(output)
  658. return parts.join('')
  659. }
  660. },{}],5:[function(_dereq_,module,exports){
  661. 'use strict';
  662. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  663. module.exports = {
  664. // Create a <link> tag with optional data attributes
  665. createLink: function(href, attributes) {
  666. var head = document.head || document.getElementsByTagName('head')[0];
  667. var link = document.createElement('link');
  668. link.href = href;
  669. link.rel = 'stylesheet';
  670. for (var key in attributes) {
  671. if ( ! attributes.hasOwnProperty(key)) {
  672. continue;
  673. }
  674. var value = attributes[key];
  675. link.setAttribute('data-' + key, value);
  676. }
  677. head.appendChild(link);
  678. },
  679. // Create a <style> tag with optional data attributes
  680. createStyle: function(cssText, attributes) {
  681. var head = document.head || document.getElementsByTagName('head')[0],
  682. style = document.createElement('style');
  683. style.type = 'text/css';
  684. for (var key in attributes) {
  685. if ( ! attributes.hasOwnProperty(key)) {
  686. continue;
  687. }
  688. var value = attributes[key];
  689. style.setAttribute('data-' + key, value);
  690. }
  691. if (style.sheet) { // for jsdom and IE9+
  692. style.innerHTML = cssText;
  693. style.sheet.cssText = cssText;
  694. head.appendChild(style);
  695. } else if (style.styleSheet) { // for IE8 and below
  696. head.appendChild(style);
  697. style.styleSheet.cssText = cssText;
  698. } else { // for Chrome, Firefox, and Safari
  699. style.appendChild(document.createTextNode(cssText));
  700. head.appendChild(style);
  701. }
  702. }
  703. };
  704. },{}],6:[function(_dereq_,module,exports){
  705. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  706. module.exports = function (a, b) {
  707. if (!Buffer.isBuffer(a)) return undefined;
  708. if (!Buffer.isBuffer(b)) return undefined;
  709. if (typeof a.equals === 'function') return a.equals(b);
  710. if (a.length !== b.length) return false;
  711. for (var i = 0; i < a.length; i++) {
  712. if (a[i] !== b[i]) return false;
  713. }
  714. return true;
  715. };
  716. },{"buffer":7}],7:[function(_dereq_,module,exports){
  717. (function (global){
  718. /*!
  719. * The buffer module from node.js, for the browser.
  720. *
  721. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  722. * @license MIT
  723. */
  724. /* eslint-disable no-proto */
  725. 'use strict'
  726. var base64 = _dereq_('base64-js')
  727. var ieee754 = _dereq_('ieee754')
  728. var isArray = _dereq_('isarray')
  729. exports.Buffer = Buffer
  730. exports.SlowBuffer = SlowBuffer
  731. exports.INSPECT_MAX_BYTES = 50
  732. /**
  733. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  734. * === true Use Uint8Array implementation (fastest)
  735. * === false Use Object implementation (most compatible, even IE6)
  736. *
  737. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  738. * Opera 11.6+, iOS 4.2+.
  739. *
  740. * Due to various browser bugs, sometimes the Object implementation will be used even
  741. * when the browser supports typed arrays.
  742. *
  743. * Note:
  744. *
  745. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  746. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  747. *
  748. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  749. *
  750. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  751. * incorrect length in some situations.
  752. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  753. * get the Object implementation, which is slower but behaves correctly.
  754. */
  755. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  756. ? global.TYPED_ARRAY_SUPPORT
  757. : typedArraySupport()
  758. /*
  759. * Export kMaxLength after typed array support is determined.
  760. */
  761. exports.kMaxLength = kMaxLength()
  762. function typedArraySupport () {
  763. try {
  764. var arr = new Uint8Array(1)
  765. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  766. return arr.foo() === 42 && // typed array instances can be augmented
  767. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  768. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  769. } catch (e) {
  770. return false
  771. }
  772. }
  773. function kMaxLength () {
  774. return Buffer.TYPED_ARRAY_SUPPORT
  775. ? 0x7fffffff
  776. : 0x3fffffff
  777. }
  778. function createBuffer (that, length) {
  779. if (kMaxLength() < length) {
  780. throw new RangeError('Invalid typed array length')
  781. }
  782. if (Buffer.TYPED_ARRAY_SUPPORT) {
  783. // Return an augmented `Uint8Array` instance, for best performance
  784. that = new Uint8Array(length)
  785. that.__proto__ = Buffer.prototype
  786. } else {
  787. // Fallback: Return an object instance of the Buffer class
  788. if (that === null) {
  789. that = new Buffer(length)
  790. }
  791. that.length = length
  792. }
  793. return that
  794. }
  795. /**
  796. * The Buffer constructor returns instances of `Uint8Array` that have their
  797. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  798. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  799. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  800. * returns a single octet.
  801. *
  802. * The `Uint8Array` prototype remains unmodified.
  803. */
  804. function Buffer (arg, encodingOrOffset, length) {
  805. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  806. return new Buffer(arg, encodingOrOffset, length)
  807. }
  808. // Common case.
  809. if (typeof arg === 'number') {
  810. if (typeof encodingOrOffset === 'string') {
  811. throw new Error(
  812. 'If encoding is specified then the first argument must be a string'
  813. )
  814. }
  815. return allocUnsafe(this, arg)
  816. }
  817. return from(this, arg, encodingOrOffset, length)
  818. }
  819. Buffer.poolSize = 8192 // not used by this implementation
  820. // TODO: Legacy, not needed anymore. Remove in next major version.
  821. Buffer._augment = function (arr) {
  822. arr.__proto__ = Buffer.prototype
  823. return arr
  824. }
  825. function from (that, value, encodingOrOffset, length) {
  826. if (typeof value === 'number') {
  827. throw new TypeError('"value" argument must not be a number')
  828. }
  829. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  830. return fromArrayBuffer(that, value, encodingOrOffset, length)
  831. }
  832. if (typeof value === 'string') {
  833. return fromString(that, value, encodingOrOffset)
  834. }
  835. return fromObject(that, value)
  836. }
  837. /**
  838. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  839. * if value is a number.
  840. * Buffer.from(str[, encoding])
  841. * Buffer.from(array)
  842. * Buffer.from(buffer)
  843. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  844. **/
  845. Buffer.from = function (value, encodingOrOffset, length) {
  846. return from(null, value, encodingOrOffset, length)
  847. }
  848. if (Buffer.TYPED_ARRAY_SUPPORT) {
  849. Buffer.prototype.__proto__ = Uint8Array.prototype
  850. Buffer.__proto__ = Uint8Array
  851. if (typeof Symbol !== 'undefined' && Symbol.species &&
  852. Buffer[Symbol.species] === Buffer) {
  853. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  854. Object.defineProperty(Buffer, Symbol.species, {
  855. value: null,
  856. configurable: true
  857. })
  858. }
  859. }
  860. function assertSize (size) {
  861. if (typeof size !== 'number') {
  862. throw new TypeError('"size" argument must be a number')
  863. } else if (size < 0) {
  864. throw new RangeError('"size" argument must not be negative')
  865. }
  866. }
  867. function alloc (that, size, fill, encoding) {
  868. assertSize(size)
  869. if (size <= 0) {
  870. return createBuffer(that, size)
  871. }
  872. if (fill !== undefined) {
  873. // Only pay attention to encoding if it's a string. This
  874. // prevents accidentally sending in a number that would
  875. // be interpretted as a start offset.
  876. return typeof encoding === 'string'
  877. ? createBuffer(that, size).fill(fill, encoding)
  878. : createBuffer(that, size).fill(fill)
  879. }
  880. return createBuffer(that, size)
  881. }
  882. /**
  883. * Creates a new filled Buffer instance.
  884. * alloc(size[, fill[, encoding]])
  885. **/
  886. Buffer.alloc = function (size, fill, encoding) {
  887. return alloc(null, size, fill, encoding)
  888. }
  889. function allocUnsafe (that, size) {
  890. assertSize(size)
  891. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  892. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  893. for (var i = 0; i < size; ++i) {
  894. that[i] = 0
  895. }
  896. }
  897. return that
  898. }
  899. /**
  900. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  901. * */
  902. Buffer.allocUnsafe = function (size) {
  903. return allocUnsafe(null, size)
  904. }
  905. /**
  906. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  907. */
  908. Buffer.allocUnsafeSlow = function (size) {
  909. return allocUnsafe(null, size)
  910. }
  911. function fromString (that, string, encoding) {
  912. if (typeof encoding !== 'string' || encoding === '') {
  913. encoding = 'utf8'
  914. }
  915. if (!Buffer.isEncoding(encoding)) {
  916. throw new TypeError('"encoding" must be a valid string encoding')
  917. }
  918. var length = byteLength(string, encoding) | 0
  919. that = createBuffer(that, length)
  920. var actual = that.write(string, encoding)
  921. if (actual !== length) {
  922. // Writing a hex string, for example, that contains invalid characters will
  923. // cause everything after the first invalid character to be ignored. (e.g.
  924. // 'abxxcd' will be treated as 'ab')
  925. that = that.slice(0, actual)
  926. }
  927. return that
  928. }
  929. function fromArrayLike (that, array) {
  930. var length = array.length < 0 ? 0 : checked(array.length) | 0
  931. that = createBuffer(that, length)
  932. for (var i = 0; i < length; i += 1) {
  933. that[i] = array[i] & 255
  934. }
  935. return that
  936. }
  937. function fromArrayBuffer (that, array, byteOffset, length) {
  938. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  939. if (byteOffset < 0 || array.byteLength < byteOffset) {
  940. throw new RangeError('\'offset\' is out of bounds')
  941. }
  942. if (array.byteLength < byteOffset + (length || 0)) {
  943. throw new RangeError('\'length\' is out of bounds')
  944. }
  945. if (byteOffset === undefined && length === undefined) {
  946. array = new Uint8Array(array)
  947. } else if (length === undefined) {
  948. array = new Uint8Array(array, byteOffset)
  949. } else {
  950. array = new Uint8Array(array, byteOffset, length)
  951. }
  952. if (Buffer.TYPED_ARRAY_SUPPORT) {
  953. // Return an augmented `Uint8Array` instance, for best performance
  954. that = array
  955. that.__proto__ = Buffer.prototype
  956. } else {
  957. // Fallback: Return an object instance of the Buffer class
  958. that = fromArrayLike(that, array)
  959. }
  960. return that
  961. }
  962. function fromObject (that, obj) {
  963. if (Buffer.isBuffer(obj)) {
  964. var len = checked(obj.length) | 0
  965. that = createBuffer(that, len)
  966. if (that.length === 0) {
  967. return that
  968. }
  969. obj.copy(that, 0, 0, len)
  970. return that
  971. }
  972. if (obj) {
  973. if ((typeof ArrayBuffer !== 'undefined' &&
  974. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  975. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  976. return createBuffer(that, 0)
  977. }
  978. return fromArrayLike(that, obj)
  979. }
  980. if (obj.type === 'Buffer' && isArray(obj.data)) {
  981. return fromArrayLike(that, obj.data)
  982. }
  983. }
  984. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  985. }
  986. function checked (length) {
  987. // Note: cannot use `length < kMaxLength()` here because that fails when
  988. // length is NaN (which is otherwise coerced to zero.)
  989. if (length >= kMaxLength()) {
  990. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  991. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  992. }
  993. return length | 0
  994. }
  995. function SlowBuffer (length) {
  996. if (+length != length) { // eslint-disable-line eqeqeq
  997. length = 0
  998. }
  999. return Buffer.alloc(+length)
  1000. }
  1001. Buffer.isBuffer = function isBuffer (b) {
  1002. return !!(b != null && b._isBuffer)
  1003. }
  1004. Buffer.compare = function compare (a, b) {
  1005. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  1006. throw new TypeError('Arguments must be Buffers')
  1007. }
  1008. if (a === b) return 0
  1009. var x = a.length
  1010. var y = b.length
  1011. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1012. if (a[i] !== b[i]) {
  1013. x = a[i]
  1014. y = b[i]
  1015. break
  1016. }
  1017. }
  1018. if (x < y) return -1
  1019. if (y < x) return 1
  1020. return 0
  1021. }
  1022. Buffer.isEncoding = function isEncoding (encoding) {
  1023. switch (String(encoding).toLowerCase()) {
  1024. case 'hex':
  1025. case 'utf8':
  1026. case 'utf-8':
  1027. case 'ascii':
  1028. case 'latin1':
  1029. case 'binary':
  1030. case 'base64':
  1031. case 'ucs2':
  1032. case 'ucs-2':
  1033. case 'utf16le':
  1034. case 'utf-16le':
  1035. return true
  1036. default:
  1037. return false
  1038. }
  1039. }
  1040. Buffer.concat = function concat (list, length) {
  1041. if (!isArray(list)) {
  1042. throw new TypeError('"list" argument must be an Array of Buffers')
  1043. }
  1044. if (list.length === 0) {
  1045. return Buffer.alloc(0)
  1046. }
  1047. var i
  1048. if (length === undefined) {
  1049. length = 0
  1050. for (i = 0; i < list.length; ++i) {
  1051. length += list[i].length
  1052. }
  1053. }
  1054. var buffer = Buffer.allocUnsafe(length)
  1055. var pos = 0
  1056. for (i = 0; i < list.length; ++i) {
  1057. var buf = list[i]
  1058. if (!Buffer.isBuffer(buf)) {
  1059. throw new TypeError('"list" argument must be an Array of Buffers')
  1060. }
  1061. buf.copy(buffer, pos)
  1062. pos += buf.length
  1063. }
  1064. return buffer
  1065. }
  1066. function byteLength (string, encoding) {
  1067. if (Buffer.isBuffer(string)) {
  1068. return string.length
  1069. }
  1070. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1071. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1072. return string.byteLength
  1073. }
  1074. if (typeof string !== 'string') {
  1075. string = '' + string
  1076. }
  1077. var len = string.length
  1078. if (len === 0) return 0
  1079. // Use a for loop to avoid recursion
  1080. var loweredCase = false
  1081. for (;;) {
  1082. switch (encoding) {
  1083. case 'ascii':
  1084. case 'latin1':
  1085. case 'binary':
  1086. return len
  1087. case 'utf8':
  1088. case 'utf-8':
  1089. case undefined:
  1090. return utf8ToBytes(string).length
  1091. case 'ucs2':
  1092. case 'ucs-2':
  1093. case 'utf16le':
  1094. case 'utf-16le':
  1095. return len * 2
  1096. case 'hex':
  1097. return len >>> 1
  1098. case 'base64':
  1099. return base64ToBytes(string).length
  1100. default:
  1101. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1102. encoding = ('' + encoding).toLowerCase()
  1103. loweredCase = true
  1104. }
  1105. }
  1106. }
  1107. Buffer.byteLength = byteLength
  1108. function slowToString (encoding, start, end) {
  1109. var loweredCase = false
  1110. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1111. // property of a typed array.
  1112. // This behaves neither like String nor Uint8Array in that we set start/end
  1113. // to their upper/lower bounds if the value passed is out of range.
  1114. // undefined is handled specially as per ECMA-262 6th Edition,
  1115. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1116. if (start === undefined || start < 0) {
  1117. start = 0
  1118. }
  1119. // Return early if start > this.length. Done here to prevent potential uint32
  1120. // coercion fail below.
  1121. if (start > this.length) {
  1122. return ''
  1123. }
  1124. if (end === undefined || end > this.length) {
  1125. end = this.length
  1126. }
  1127. if (end <= 0) {
  1128. return ''
  1129. }
  1130. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1131. end >>>= 0
  1132. start >>>= 0
  1133. if (end <= start) {
  1134. return ''
  1135. }
  1136. if (!encoding) encoding = 'utf8'
  1137. while (true) {
  1138. switch (encoding) {
  1139. case 'hex':
  1140. return hexSlice(this, start, end)
  1141. case 'utf8':
  1142. case 'utf-8':
  1143. return utf8Slice(this, start, end)
  1144. case 'ascii':
  1145. return asciiSlice(this, start, end)
  1146. case 'latin1':
  1147. case 'binary':
  1148. return latin1Slice(this, start, end)
  1149. case 'base64':
  1150. return base64Slice(this, start, end)
  1151. case 'ucs2':
  1152. case 'ucs-2':
  1153. case 'utf16le':
  1154. case 'utf-16le':
  1155. return utf16leSlice(this, start, end)
  1156. default:
  1157. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1158. encoding = (encoding + '').toLowerCase()
  1159. loweredCase = true
  1160. }
  1161. }
  1162. }
  1163. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1164. // Buffer instances.
  1165. Buffer.prototype._isBuffer = true
  1166. function swap (b, n, m) {
  1167. var i = b[n]
  1168. b[n] = b[m]
  1169. b[m] = i
  1170. }
  1171. Buffer.prototype.swap16 = function swap16 () {
  1172. var len = this.length
  1173. if (len % 2 !== 0) {
  1174. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1175. }
  1176. for (var i = 0; i < len; i += 2) {
  1177. swap(this, i, i + 1)
  1178. }
  1179. return this
  1180. }
  1181. Buffer.prototype.swap32 = function swap32 () {
  1182. var len = this.length
  1183. if (len % 4 !== 0) {
  1184. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1185. }
  1186. for (var i = 0; i < len; i += 4) {
  1187. swap(this, i, i + 3)
  1188. swap(this, i + 1, i + 2)
  1189. }
  1190. return this
  1191. }
  1192. Buffer.prototype.swap64 = function swap64 () {
  1193. var len = this.length
  1194. if (len % 8 !== 0) {
  1195. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1196. }
  1197. for (var i = 0; i < len; i += 8) {
  1198. swap(this, i, i + 7)
  1199. swap(this, i + 1, i + 6)
  1200. swap(this, i + 2, i + 5)
  1201. swap(this, i + 3, i + 4)
  1202. }
  1203. return this
  1204. }
  1205. Buffer.prototype.toString = function toString () {
  1206. var length = this.length | 0
  1207. if (length === 0) return ''
  1208. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1209. return slowToString.apply(this, arguments)
  1210. }
  1211. Buffer.prototype.equals = function equals (b) {
  1212. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1213. if (this === b) return true
  1214. return Buffer.compare(this, b) === 0
  1215. }
  1216. Buffer.prototype.inspect = function inspect () {
  1217. var str = ''
  1218. var max = exports.INSPECT_MAX_BYTES
  1219. if (this.length > 0) {
  1220. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1221. if (this.length > max) str += ' ... '
  1222. }
  1223. return '<Buffer ' + str + '>'
  1224. }
  1225. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1226. if (!Buffer.isBuffer(target)) {
  1227. throw new TypeError('Argument must be a Buffer')
  1228. }
  1229. if (start === undefined) {
  1230. start = 0
  1231. }
  1232. if (end === undefined) {
  1233. end = target ? target.length : 0
  1234. }
  1235. if (thisStart === undefined) {
  1236. thisStart = 0
  1237. }
  1238. if (thisEnd === undefined) {
  1239. thisEnd = this.length
  1240. }
  1241. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1242. throw new RangeError('out of range index')
  1243. }
  1244. if (thisStart >= thisEnd && start >= end) {
  1245. return 0
  1246. }
  1247. if (thisStart >= thisEnd) {
  1248. return -1
  1249. }
  1250. if (start >= end) {
  1251. return 1
  1252. }
  1253. start >>>= 0
  1254. end >>>= 0
  1255. thisStart >>>= 0
  1256. thisEnd >>>= 0
  1257. if (this === target) return 0
  1258. var x = thisEnd - thisStart
  1259. var y = end - start
  1260. var len = Math.min(x, y)
  1261. var thisCopy = this.slice(thisStart, thisEnd)
  1262. var targetCopy = target.slice(start, end)
  1263. for (var i = 0; i < len; ++i) {
  1264. if (thisCopy[i] !== targetCopy[i]) {
  1265. x = thisCopy[i]
  1266. y = targetCopy[i]
  1267. break
  1268. }
  1269. }
  1270. if (x < y) return -1
  1271. if (y < x) return 1
  1272. return 0
  1273. }
  1274. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1275. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1276. //
  1277. // Arguments:
  1278. // - buffer - a Buffer to search
  1279. // - val - a string, Buffer, or number
  1280. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1281. // - encoding - an optional encoding, relevant is val is a string
  1282. // - dir - true for indexOf, false for lastIndexOf
  1283. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1284. // Empty buffer means no match
  1285. if (buffer.length === 0) return -1
  1286. // Normalize byteOffset
  1287. if (typeof byteOffset === 'string') {
  1288. encoding = byteOffset
  1289. byteOffset = 0
  1290. } else if (byteOffset > 0x7fffffff) {
  1291. byteOffset = 0x7fffffff
  1292. } else if (byteOffset < -0x80000000) {
  1293. byteOffset = -0x80000000
  1294. }
  1295. byteOffset = +byteOffset // Coerce to Number.
  1296. if (isNaN(byteOffset)) {
  1297. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1298. byteOffset = dir ? 0 : (buffer.length - 1)
  1299. }
  1300. // Normalize byteOffset: negative offsets start from the end of the buffer
  1301. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  1302. if (byteOffset >= buffer.length) {
  1303. if (dir) return -1
  1304. else byteOffset = buffer.length - 1
  1305. } else if (byteOffset < 0) {
  1306. if (dir) byteOffset = 0
  1307. else return -1
  1308. }
  1309. // Normalize val
  1310. if (typeof val === 'string') {
  1311. val = Buffer.from(val, encoding)
  1312. }
  1313. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1314. if (Buffer.isBuffer(val)) {
  1315. // Special case: looking for empty string/buffer always fails
  1316. if (val.length === 0) {
  1317. return -1
  1318. }
  1319. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1320. } else if (typeof val === 'number') {
  1321. val = val & 0xFF // Search for a byte value [0-255]
  1322. if (Buffer.TYPED_ARRAY_SUPPORT &&
  1323. typeof Uint8Array.prototype.indexOf === 'function') {
  1324. if (dir) {
  1325. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1326. } else {
  1327. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1328. }
  1329. }
  1330. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1331. }
  1332. throw new TypeError('val must be string, number or Buffer')
  1333. }
  1334. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1335. var indexSize = 1
  1336. var arrLength = arr.length
  1337. var valLength = val.length
  1338. if (encoding !== undefined) {
  1339. encoding = String(encoding).toLowerCase()
  1340. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1341. encoding === 'utf16le' || encoding === 'utf-16le') {
  1342. if (arr.length < 2 || val.length < 2) {
  1343. return -1
  1344. }
  1345. indexSize = 2
  1346. arrLength /= 2
  1347. valLength /= 2
  1348. byteOffset /= 2
  1349. }
  1350. }
  1351. function read (buf, i) {
  1352. if (indexSize === 1) {
  1353. return buf[i]
  1354. } else {
  1355. return buf.readUInt16BE(i * indexSize)
  1356. }
  1357. }
  1358. var i
  1359. if (dir) {
  1360. var foundIndex = -1
  1361. for (i = byteOffset; i < arrLength; i++) {
  1362. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1363. if (foundIndex === -1) foundIndex = i
  1364. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1365. } else {
  1366. if (foundIndex !== -1) i -= i - foundIndex
  1367. foundIndex = -1
  1368. }
  1369. }
  1370. } else {
  1371. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  1372. for (i = byteOffset; i >= 0; i--) {
  1373. var found = true
  1374. for (var j = 0; j < valLength; j++) {
  1375. if (read(arr, i + j) !== read(val, j)) {
  1376. found = false
  1377. break
  1378. }
  1379. }
  1380. if (found) return i
  1381. }
  1382. }
  1383. return -1
  1384. }
  1385. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  1386. return this.indexOf(val, byteOffset, encoding) !== -1
  1387. }
  1388. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1389. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1390. }
  1391. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1392. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1393. }
  1394. function hexWrite (buf, string, offset, length) {
  1395. offset = Number(offset) || 0
  1396. var remaining = buf.length - offset
  1397. if (!length) {
  1398. length = remaining
  1399. } else {
  1400. length = Number(length)
  1401. if (length > remaining) {
  1402. length = remaining
  1403. }
  1404. }
  1405. // must be an even number of digits
  1406. var strLen = string.length
  1407. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1408. if (length > strLen / 2) {
  1409. length = strLen / 2
  1410. }
  1411. for (var i = 0; i < length; ++i) {
  1412. var parsed = parseInt(string.substr(i * 2, 2), 16)
  1413. if (isNaN(parsed)) return i
  1414. buf[offset + i] = parsed
  1415. }
  1416. return i
  1417. }
  1418. function utf8Write (buf, string, offset, length) {
  1419. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1420. }
  1421. function asciiWrite (buf, string, offset, length) {
  1422. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1423. }
  1424. function latin1Write (buf, string, offset, length) {
  1425. return asciiWrite(buf, string, offset, length)
  1426. }
  1427. function base64Write (buf, string, offset, length) {
  1428. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1429. }
  1430. function ucs2Write (buf, string, offset, length) {
  1431. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1432. }
  1433. Buffer.prototype.write = function write (string, offset, length, encoding) {
  1434. // Buffer#write(string)
  1435. if (offset === undefined) {
  1436. encoding = 'utf8'
  1437. length = this.length
  1438. offset = 0
  1439. // Buffer#write(string, encoding)
  1440. } else if (length === undefined && typeof offset === 'string') {
  1441. encoding = offset
  1442. length = this.length
  1443. offset = 0
  1444. // Buffer#write(string, offset[, length][, encoding])
  1445. } else if (isFinite(offset)) {
  1446. offset = offset | 0
  1447. if (isFinite(length)) {
  1448. length = length | 0
  1449. if (encoding === undefined) encoding = 'utf8'
  1450. } else {
  1451. encoding = length
  1452. length = undefined
  1453. }
  1454. // legacy write(string, encoding, offset, length) - remove in v0.13
  1455. } else {
  1456. throw new Error(
  1457. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1458. )
  1459. }
  1460. var remaining = this.length - offset
  1461. if (length === undefined || length > remaining) length = remaining
  1462. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1463. throw new RangeError('Attempt to write outside buffer bounds')
  1464. }
  1465. if (!encoding) encoding = 'utf8'
  1466. var loweredCase = false
  1467. for (;;) {
  1468. switch (encoding) {
  1469. case 'hex':
  1470. return hexWrite(this, string, offset, length)
  1471. case 'utf8':
  1472. case 'utf-8':
  1473. return utf8Write(this, string, offset, length)
  1474. case 'ascii':
  1475. return asciiWrite(this, string, offset, length)
  1476. case 'latin1':
  1477. case 'binary':
  1478. return latin1Write(this, string, offset, length)
  1479. case 'base64':
  1480. // Warning: maxLength not taken into account in base64Write
  1481. return base64Write(this, string, offset, length)
  1482. case 'ucs2':
  1483. case 'ucs-2':
  1484. case 'utf16le':
  1485. case 'utf-16le':
  1486. return ucs2Write(this, string, offset, length)
  1487. default:
  1488. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1489. encoding = ('' + encoding).toLowerCase()
  1490. loweredCase = true
  1491. }
  1492. }
  1493. }
  1494. Buffer.prototype.toJSON = function toJSON () {
  1495. return {
  1496. type: 'Buffer',
  1497. data: Array.prototype.slice.call(this._arr || this, 0)
  1498. }
  1499. }
  1500. function base64Slice (buf, start, end) {
  1501. if (start === 0 && end === buf.length) {
  1502. return base64.fromByteArray(buf)
  1503. } else {
  1504. return base64.fromByteArray(buf.slice(start, end))
  1505. }
  1506. }
  1507. function utf8Slice (buf, start, end) {
  1508. end = Math.min(buf.length, end)
  1509. var res = []
  1510. var i = start
  1511. while (i < end) {
  1512. var firstByte = buf[i]
  1513. var codePoint = null
  1514. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1515. : (firstByte > 0xDF) ? 3
  1516. : (firstByte > 0xBF) ? 2
  1517. : 1
  1518. if (i + bytesPerSequence <= end) {
  1519. var secondByte, thirdByte, fourthByte, tempCodePoint
  1520. switch (bytesPerSequence) {
  1521. case 1:
  1522. if (firstByte < 0x80) {
  1523. codePoint = firstByte
  1524. }
  1525. break
  1526. case 2:
  1527. secondByte = buf[i + 1]
  1528. if ((secondByte & 0xC0) === 0x80) {
  1529. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1530. if (tempCodePoint > 0x7F) {
  1531. codePoint = tempCodePoint
  1532. }
  1533. }
  1534. break
  1535. case 3:
  1536. secondByte = buf[i + 1]
  1537. thirdByte = buf[i + 2]
  1538. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1539. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1540. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1541. codePoint = tempCodePoint
  1542. }
  1543. }
  1544. break
  1545. case 4:
  1546. secondByte = buf[i + 1]
  1547. thirdByte = buf[i + 2]
  1548. fourthByte = buf[i + 3]
  1549. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1550. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1551. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1552. codePoint = tempCodePoint
  1553. }
  1554. }
  1555. }
  1556. }
  1557. if (codePoint === null) {
  1558. // we did not generate a valid codePoint so insert a
  1559. // replacement char (U+FFFD) and advance only 1 byte
  1560. codePoint = 0xFFFD
  1561. bytesPerSequence = 1
  1562. } else if (codePoint > 0xFFFF) {
  1563. // encode to utf16 (surrogate pair dance)
  1564. codePoint -= 0x10000
  1565. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1566. codePoint = 0xDC00 | codePoint & 0x3FF
  1567. }
  1568. res.push(codePoint)
  1569. i += bytesPerSequence
  1570. }
  1571. return decodeCodePointsArray(res)
  1572. }
  1573. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1574. // the lowest limit is Chrome, with 0x10000 args.
  1575. // We go 1 magnitude less, for safety
  1576. var MAX_ARGUMENTS_LENGTH = 0x1000
  1577. function decodeCodePointsArray (codePoints) {
  1578. var len = codePoints.length
  1579. if (len <= MAX_ARGUMENTS_LENGTH) {
  1580. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1581. }
  1582. // Decode in chunks to avoid "call stack size exceeded".
  1583. var res = ''
  1584. var i = 0
  1585. while (i < len) {
  1586. res += String.fromCharCode.apply(
  1587. String,
  1588. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1589. )
  1590. }
  1591. return res
  1592. }
  1593. function asciiSlice (buf, start, end) {
  1594. var ret = ''
  1595. end = Math.min(buf.length, end)
  1596. for (var i = start; i < end; ++i) {
  1597. ret += String.fromCharCode(buf[i] & 0x7F)
  1598. }
  1599. return ret
  1600. }
  1601. function latin1Slice (buf, start, end) {
  1602. var ret = ''
  1603. end = Math.min(buf.length, end)
  1604. for (var i = start; i < end; ++i) {
  1605. ret += String.fromCharCode(buf[i])
  1606. }
  1607. return ret
  1608. }
  1609. function hexSlice (buf, start, end) {
  1610. var len = buf.length
  1611. if (!start || start < 0) start = 0
  1612. if (!end || end < 0 || end > len) end = len
  1613. var out = ''
  1614. for (var i = start; i < end; ++i) {
  1615. out += toHex(buf[i])
  1616. }
  1617. return out
  1618. }
  1619. function utf16leSlice (buf, start, end) {
  1620. var bytes = buf.slice(start, end)
  1621. var res = ''
  1622. for (var i = 0; i < bytes.length; i += 2) {
  1623. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1624. }
  1625. return res
  1626. }
  1627. Buffer.prototype.slice = function slice (start, end) {
  1628. var len = this.length
  1629. start = ~~start
  1630. end = end === undefined ? len : ~~end
  1631. if (start < 0) {
  1632. start += len
  1633. if (start < 0) start = 0
  1634. } else if (start > len) {
  1635. start = len
  1636. }
  1637. if (end < 0) {
  1638. end += len
  1639. if (end < 0) end = 0
  1640. } else if (end > len) {
  1641. end = len
  1642. }
  1643. if (end < start) end = start
  1644. var newBuf
  1645. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1646. newBuf = this.subarray(start, end)
  1647. newBuf.__proto__ = Buffer.prototype
  1648. } else {
  1649. var sliceLen = end - start
  1650. newBuf = new Buffer(sliceLen, undefined)
  1651. for (var i = 0; i < sliceLen; ++i) {
  1652. newBuf[i] = this[i + start]
  1653. }
  1654. }
  1655. return newBuf
  1656. }
  1657. /*
  1658. * Need to make sure that buffer isn't trying to write out of bounds.
  1659. */
  1660. function checkOffset (offset, ext, length) {
  1661. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1662. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1663. }
  1664. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1665. offset = offset | 0
  1666. byteLength = byteLength | 0
  1667. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1668. var val = this[offset]
  1669. var mul = 1
  1670. var i = 0
  1671. while (++i < byteLength && (mul *= 0x100)) {
  1672. val += this[offset + i] * mul
  1673. }
  1674. return val
  1675. }
  1676. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1677. offset = offset | 0
  1678. byteLength = byteLength | 0
  1679. if (!noAssert) {
  1680. checkOffset(offset, byteLength, this.length)
  1681. }
  1682. var val = this[offset + --byteLength]
  1683. var mul = 1
  1684. while (byteLength > 0 && (mul *= 0x100)) {
  1685. val += this[offset + --byteLength] * mul
  1686. }
  1687. return val
  1688. }
  1689. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1690. if (!noAssert) checkOffset(offset, 1, this.length)
  1691. return this[offset]
  1692. }
  1693. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1694. if (!noAssert) checkOffset(offset, 2, this.length)
  1695. return this[offset] | (this[offset + 1] << 8)
  1696. }
  1697. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1698. if (!noAssert) checkOffset(offset, 2, this.length)
  1699. return (this[offset] << 8) | this[offset + 1]
  1700. }
  1701. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1702. if (!noAssert) checkOffset(offset, 4, this.length)
  1703. return ((this[offset]) |
  1704. (this[offset + 1] << 8) |
  1705. (this[offset + 2] << 16)) +
  1706. (this[offset + 3] * 0x1000000)
  1707. }
  1708. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1709. if (!noAssert) checkOffset(offset, 4, this.length)
  1710. return (this[offset] * 0x1000000) +
  1711. ((this[offset + 1] << 16) |
  1712. (this[offset + 2] << 8) |
  1713. this[offset + 3])
  1714. }
  1715. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1716. offset = offset | 0
  1717. byteLength = byteLength | 0
  1718. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1719. var val = this[offset]
  1720. var mul = 1
  1721. var i = 0
  1722. while (++i < byteLength && (mul *= 0x100)) {
  1723. val += this[offset + i] * mul
  1724. }
  1725. mul *= 0x80
  1726. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1727. return val
  1728. }
  1729. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1730. offset = offset | 0
  1731. byteLength = byteLength | 0
  1732. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1733. var i = byteLength
  1734. var mul = 1
  1735. var val = this[offset + --i]
  1736. while (i > 0 && (mul *= 0x100)) {
  1737. val += this[offset + --i] * mul
  1738. }
  1739. mul *= 0x80
  1740. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1741. return val
  1742. }
  1743. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1744. if (!noAssert) checkOffset(offset, 1, this.length)
  1745. if (!(this[offset] & 0x80)) return (this[offset])
  1746. return ((0xff - this[offset] + 1) * -1)
  1747. }
  1748. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1749. if (!noAssert) checkOffset(offset, 2, this.length)
  1750. var val = this[offset] | (this[offset + 1] << 8)
  1751. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1752. }
  1753. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1754. if (!noAssert) checkOffset(offset, 2, this.length)
  1755. var val = this[offset + 1] | (this[offset] << 8)
  1756. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1757. }
  1758. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1759. if (!noAssert) checkOffset(offset, 4, this.length)
  1760. return (this[offset]) |
  1761. (this[offset + 1] << 8) |
  1762. (this[offset + 2] << 16) |
  1763. (this[offset + 3] << 24)
  1764. }
  1765. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1766. if (!noAssert) checkOffset(offset, 4, this.length)
  1767. return (this[offset] << 24) |
  1768. (this[offset + 1] << 16) |
  1769. (this[offset + 2] << 8) |
  1770. (this[offset + 3])
  1771. }
  1772. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1773. if (!noAssert) checkOffset(offset, 4, this.length)
  1774. return ieee754.read(this, offset, true, 23, 4)
  1775. }
  1776. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1777. if (!noAssert) checkOffset(offset, 4, this.length)
  1778. return ieee754.read(this, offset, false, 23, 4)
  1779. }
  1780. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1781. if (!noAssert) checkOffset(offset, 8, this.length)
  1782. return ieee754.read(this, offset, true, 52, 8)
  1783. }
  1784. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1785. if (!noAssert) checkOffset(offset, 8, this.length)
  1786. return ieee754.read(this, offset, false, 52, 8)
  1787. }
  1788. function checkInt (buf, value, offset, ext, max, min) {
  1789. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1790. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1791. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1792. }
  1793. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1794. value = +value
  1795. offset = offset | 0
  1796. byteLength = byteLength | 0
  1797. if (!noAssert) {
  1798. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1799. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1800. }
  1801. var mul = 1
  1802. var i = 0
  1803. this[offset] = value & 0xFF
  1804. while (++i < byteLength && (mul *= 0x100)) {
  1805. this[offset + i] = (value / mul) & 0xFF
  1806. }
  1807. return offset + byteLength
  1808. }
  1809. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1810. value = +value
  1811. offset = offset | 0
  1812. byteLength = byteLength | 0
  1813. if (!noAssert) {
  1814. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1815. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1816. }
  1817. var i = byteLength - 1
  1818. var mul = 1
  1819. this[offset + i] = value & 0xFF
  1820. while (--i >= 0 && (mul *= 0x100)) {
  1821. this[offset + i] = (value / mul) & 0xFF
  1822. }
  1823. return offset + byteLength
  1824. }
  1825. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1826. value = +value
  1827. offset = offset | 0
  1828. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1829. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1830. this[offset] = (value & 0xff)
  1831. return offset + 1
  1832. }
  1833. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1834. if (value < 0) value = 0xffff + value + 1
  1835. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1836. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1837. (littleEndian ? i : 1 - i) * 8
  1838. }
  1839. }
  1840. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1841. value = +value
  1842. offset = offset | 0
  1843. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1844. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1845. this[offset] = (value & 0xff)
  1846. this[offset + 1] = (value >>> 8)
  1847. } else {
  1848. objectWriteUInt16(this, value, offset, true)
  1849. }
  1850. return offset + 2
  1851. }
  1852. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1853. value = +value
  1854. offset = offset | 0
  1855. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1856. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1857. this[offset] = (value >>> 8)
  1858. this[offset + 1] = (value & 0xff)
  1859. } else {
  1860. objectWriteUInt16(this, value, offset, false)
  1861. }
  1862. return offset + 2
  1863. }
  1864. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1865. if (value < 0) value = 0xffffffff + value + 1
  1866. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1867. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1868. }
  1869. }
  1870. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1871. value = +value
  1872. offset = offset | 0
  1873. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1874. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1875. this[offset + 3] = (value >>> 24)
  1876. this[offset + 2] = (value >>> 16)
  1877. this[offset + 1] = (value >>> 8)
  1878. this[offset] = (value & 0xff)
  1879. } else {
  1880. objectWriteUInt32(this, value, offset, true)
  1881. }
  1882. return offset + 4
  1883. }
  1884. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1885. value = +value
  1886. offset = offset | 0
  1887. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1888. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1889. this[offset] = (value >>> 24)
  1890. this[offset + 1] = (value >>> 16)
  1891. this[offset + 2] = (value >>> 8)
  1892. this[offset + 3] = (value & 0xff)
  1893. } else {
  1894. objectWriteUInt32(this, value, offset, false)
  1895. }
  1896. return offset + 4
  1897. }
  1898. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1899. value = +value
  1900. offset = offset | 0
  1901. if (!noAssert) {
  1902. var limit = Math.pow(2, 8 * byteLength - 1)
  1903. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1904. }
  1905. var i = 0
  1906. var mul = 1
  1907. var sub = 0
  1908. this[offset] = value & 0xFF
  1909. while (++i < byteLength && (mul *= 0x100)) {
  1910. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1911. sub = 1
  1912. }
  1913. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1914. }
  1915. return offset + byteLength
  1916. }
  1917. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1918. value = +value
  1919. offset = offset | 0
  1920. if (!noAssert) {
  1921. var limit = Math.pow(2, 8 * byteLength - 1)
  1922. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1923. }
  1924. var i = byteLength - 1
  1925. var mul = 1
  1926. var sub = 0
  1927. this[offset + i] = value & 0xFF
  1928. while (--i >= 0 && (mul *= 0x100)) {
  1929. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1930. sub = 1
  1931. }
  1932. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1933. }
  1934. return offset + byteLength
  1935. }
  1936. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1937. value = +value
  1938. offset = offset | 0
  1939. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1940. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1941. if (value < 0) value = 0xff + value + 1
  1942. this[offset] = (value & 0xff)
  1943. return offset + 1
  1944. }
  1945. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1946. value = +value
  1947. offset = offset | 0
  1948. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1949. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1950. this[offset] = (value & 0xff)
  1951. this[offset + 1] = (value >>> 8)
  1952. } else {
  1953. objectWriteUInt16(this, value, offset, true)
  1954. }
  1955. return offset + 2
  1956. }
  1957. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1958. value = +value
  1959. offset = offset | 0
  1960. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1961. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1962. this[offset] = (value >>> 8)
  1963. this[offset + 1] = (value & 0xff)
  1964. } else {
  1965. objectWriteUInt16(this, value, offset, false)
  1966. }
  1967. return offset + 2
  1968. }
  1969. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1970. value = +value
  1971. offset = offset | 0
  1972. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1973. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1974. this[offset] = (value & 0xff)
  1975. this[offset + 1] = (value >>> 8)
  1976. this[offset + 2] = (value >>> 16)
  1977. this[offset + 3] = (value >>> 24)
  1978. } else {
  1979. objectWriteUInt32(this, value, offset, true)
  1980. }
  1981. return offset + 4
  1982. }
  1983. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1984. value = +value
  1985. offset = offset | 0
  1986. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1987. if (value < 0) value = 0xffffffff + value + 1
  1988. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1989. this[offset] = (value >>> 24)
  1990. this[offset + 1] = (value >>> 16)
  1991. this[offset + 2] = (value >>> 8)
  1992. this[offset + 3] = (value & 0xff)
  1993. } else {
  1994. objectWriteUInt32(this, value, offset, false)
  1995. }
  1996. return offset + 4
  1997. }
  1998. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1999. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2000. if (offset < 0) throw new RangeError('Index out of range')
  2001. }
  2002. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2003. if (!noAssert) {
  2004. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2005. }
  2006. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2007. return offset + 4
  2008. }
  2009. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2010. return writeFloat(this, value, offset, true, noAssert)
  2011. }
  2012. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2013. return writeFloat(this, value, offset, false, noAssert)
  2014. }
  2015. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2016. if (!noAssert) {
  2017. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2018. }
  2019. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2020. return offset + 8
  2021. }
  2022. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2023. return writeDouble(this, value, offset, true, noAssert)
  2024. }
  2025. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2026. return writeDouble(this, value, offset, false, noAssert)
  2027. }
  2028. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2029. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2030. if (!start) start = 0
  2031. if (!end && end !== 0) end = this.length
  2032. if (targetStart >= target.length) targetStart = target.length
  2033. if (!targetStart) targetStart = 0
  2034. if (end > 0 && end < start) end = start
  2035. // Copy 0 bytes; we're done
  2036. if (end === start) return 0
  2037. if (target.length === 0 || this.length === 0) return 0
  2038. // Fatal error conditions
  2039. if (targetStart < 0) {
  2040. throw new RangeError('targetStart out of bounds')
  2041. }
  2042. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2043. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2044. // Are we oob?
  2045. if (end > this.length) end = this.length
  2046. if (target.length - targetStart < end - start) {
  2047. end = target.length - targetStart + start
  2048. }
  2049. var len = end - start
  2050. var i
  2051. if (this === target && start < targetStart && targetStart < end) {
  2052. // descending copy from end
  2053. for (i = len - 1; i >= 0; --i) {
  2054. target[i + targetStart] = this[i + start]
  2055. }
  2056. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2057. // ascending copy from start
  2058. for (i = 0; i < len; ++i) {
  2059. target[i + targetStart] = this[i + start]
  2060. }
  2061. } else {
  2062. Uint8Array.prototype.set.call(
  2063. target,
  2064. this.subarray(start, start + len),
  2065. targetStart
  2066. )
  2067. }
  2068. return len
  2069. }
  2070. // Usage:
  2071. // buffer.fill(number[, offset[, end]])
  2072. // buffer.fill(buffer[, offset[, end]])
  2073. // buffer.fill(string[, offset[, end]][, encoding])
  2074. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  2075. // Handle string cases:
  2076. if (typeof val === 'string') {
  2077. if (typeof start === 'string') {
  2078. encoding = start
  2079. start = 0
  2080. end = this.length
  2081. } else if (typeof end === 'string') {
  2082. encoding = end
  2083. end = this.length
  2084. }
  2085. if (val.length === 1) {
  2086. var code = val.charCodeAt(0)
  2087. if (code < 256) {
  2088. val = code
  2089. }
  2090. }
  2091. if (encoding !== undefined && typeof encoding !== 'string') {
  2092. throw new TypeError('encoding must be a string')
  2093. }
  2094. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  2095. throw new TypeError('Unknown encoding: ' + encoding)
  2096. }
  2097. } else if (typeof val === 'number') {
  2098. val = val & 255
  2099. }
  2100. // Invalid ranges are not set to a default, so can range check early.
  2101. if (start < 0 || this.length < start || this.length < end) {
  2102. throw new RangeError('Out of range index')
  2103. }
  2104. if (end <= start) {
  2105. return this
  2106. }
  2107. start = start >>> 0
  2108. end = end === undefined ? this.length : end >>> 0
  2109. if (!val) val = 0
  2110. var i
  2111. if (typeof val === 'number') {
  2112. for (i = start; i < end; ++i) {
  2113. this[i] = val
  2114. }
  2115. } else {
  2116. var bytes = Buffer.isBuffer(val)
  2117. ? val
  2118. : utf8ToBytes(new Buffer(val, encoding).toString())
  2119. var len = bytes.length
  2120. for (i = 0; i < end - start; ++i) {
  2121. this[i + start] = bytes[i % len]
  2122. }
  2123. }
  2124. return this
  2125. }
  2126. // HELPER FUNCTIONS
  2127. // ================
  2128. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  2129. function base64clean (str) {
  2130. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2131. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2132. // Node converts strings with length < 2 to ''
  2133. if (str.length < 2) return ''
  2134. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2135. while (str.length % 4 !== 0) {
  2136. str = str + '='
  2137. }
  2138. return str
  2139. }
  2140. function stringtrim (str) {
  2141. if (str.trim) return str.trim()
  2142. return str.replace(/^\s+|\s+$/g, '')
  2143. }
  2144. function toHex (n) {
  2145. if (n < 16) return '0' + n.toString(16)
  2146. return n.toString(16)
  2147. }
  2148. function utf8ToBytes (string, units) {
  2149. units = units || Infinity
  2150. var codePoint
  2151. var length = string.length
  2152. var leadSurrogate = null
  2153. var bytes = []
  2154. for (var i = 0; i < length; ++i) {
  2155. codePoint = string.charCodeAt(i)
  2156. // is surrogate component
  2157. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2158. // last char was a lead
  2159. if (!leadSurrogate) {
  2160. // no lead yet
  2161. if (codePoint > 0xDBFF) {
  2162. // unexpected trail
  2163. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2164. continue
  2165. } else if (i + 1 === length) {
  2166. // unpaired lead
  2167. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2168. continue
  2169. }
  2170. // valid lead
  2171. leadSurrogate = codePoint
  2172. continue
  2173. }
  2174. // 2 leads in a row
  2175. if (codePoint < 0xDC00) {
  2176. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2177. leadSurrogate = codePoint
  2178. continue
  2179. }
  2180. // valid surrogate pair
  2181. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  2182. } else if (leadSurrogate) {
  2183. // valid bmp char, but last char was a lead
  2184. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2185. }
  2186. leadSurrogate = null
  2187. // encode utf8
  2188. if (codePoint < 0x80) {
  2189. if ((units -= 1) < 0) break
  2190. bytes.push(codePoint)
  2191. } else if (codePoint < 0x800) {
  2192. if ((units -= 2) < 0) break
  2193. bytes.push(
  2194. codePoint >> 0x6 | 0xC0,
  2195. codePoint & 0x3F | 0x80
  2196. )
  2197. } else if (codePoint < 0x10000) {
  2198. if ((units -= 3) < 0) break
  2199. bytes.push(
  2200. codePoint >> 0xC | 0xE0,
  2201. codePoint >> 0x6 & 0x3F | 0x80,
  2202. codePoint & 0x3F | 0x80
  2203. )
  2204. } else if (codePoint < 0x110000) {
  2205. if ((units -= 4) < 0) break
  2206. bytes.push(
  2207. codePoint >> 0x12 | 0xF0,
  2208. codePoint >> 0xC & 0x3F | 0x80,
  2209. codePoint >> 0x6 & 0x3F | 0x80,
  2210. codePoint & 0x3F | 0x80
  2211. )
  2212. } else {
  2213. throw new Error('Invalid code point')
  2214. }
  2215. }
  2216. return bytes
  2217. }
  2218. function asciiToBytes (str) {
  2219. var byteArray = []
  2220. for (var i = 0; i < str.length; ++i) {
  2221. // Node's code seems to be doing this and not & 0x7F..
  2222. byteArray.push(str.charCodeAt(i) & 0xFF)
  2223. }
  2224. return byteArray
  2225. }
  2226. function utf16leToBytes (str, units) {
  2227. var c, hi, lo
  2228. var byteArray = []
  2229. for (var i = 0; i < str.length; ++i) {
  2230. if ((units -= 2) < 0) break
  2231. c = str.charCodeAt(i)
  2232. hi = c >> 8
  2233. lo = c % 256
  2234. byteArray.push(lo)
  2235. byteArray.push(hi)
  2236. }
  2237. return byteArray
  2238. }
  2239. function base64ToBytes (str) {
  2240. return base64.toByteArray(base64clean(str))
  2241. }
  2242. function blitBuffer (src, dst, offset, length) {
  2243. for (var i = 0; i < length; ++i) {
  2244. if ((i + offset >= dst.length) || (i >= src.length)) break
  2245. dst[i + offset] = src[i]
  2246. }
  2247. return i
  2248. }
  2249. function isnan (val) {
  2250. return val !== val // eslint-disable-line no-self-compare
  2251. }
  2252. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2253. },{"base64-js":4,"ieee754":16,"isarray":22}],8:[function(_dereq_,module,exports){
  2254. /**
  2255. * This is the web browser implementation of `debug()`.
  2256. *
  2257. * Expose `debug()` as the module.
  2258. */
  2259. exports = module.exports = _dereq_('./debug');
  2260. exports.log = log;
  2261. exports.formatArgs = formatArgs;
  2262. exports.save = save;
  2263. exports.load = load;
  2264. exports.useColors = useColors;
  2265. exports.storage = 'undefined' != typeof chrome
  2266. && 'undefined' != typeof chrome.storage
  2267. ? chrome.storage.local
  2268. : localstorage();
  2269. /**
  2270. * Colors.
  2271. */
  2272. exports.colors = [
  2273. 'lightseagreen',
  2274. 'forestgreen',
  2275. 'goldenrod',
  2276. 'dodgerblue',
  2277. 'darkorchid',
  2278. 'crimson'
  2279. ];
  2280. /**
  2281. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2282. * and the Firebug extension (any Firefox version) are known
  2283. * to support "%c" CSS customizations.
  2284. *
  2285. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2286. */
  2287. function useColors() {
  2288. // is webkit? http://stackoverflow.com/a/16459606/376773
  2289. return ('WebkitAppearance' in document.documentElement.style) ||
  2290. // is firebug? http://stackoverflow.com/a/398120/376773
  2291. (window.console && (console.firebug || (console.exception && console.table))) ||
  2292. // is firefox >= v31?
  2293. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2294. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2295. }
  2296. /**
  2297. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2298. */
  2299. exports.formatters.j = function(v) {
  2300. return JSON.stringify(v);
  2301. };
  2302. /**
  2303. * Colorize log arguments if enabled.
  2304. *
  2305. * @api public
  2306. */
  2307. function formatArgs() {
  2308. var args = arguments;
  2309. var useColors = this.useColors;
  2310. args[0] = (useColors ? '%c' : '')
  2311. + this.namespace
  2312. + (useColors ? ' %c' : ' ')
  2313. + args[0]
  2314. + (useColors ? '%c ' : ' ');
  2315. if (!useColors) return args;
  2316. var c = 'color: ' + this.color;
  2317. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2318. // the final "%c" is somewhat tricky, because there could be other
  2319. // arguments passed either before or after the %c, so we need to
  2320. // figure out the correct index to insert the CSS into
  2321. var index = 0;
  2322. var lastC = 0;
  2323. args[0].replace(/%[a-z%]/g, function(match) {
  2324. if ('%%' === match) return;
  2325. index++;
  2326. if ('%c' === match) {
  2327. // we only are interested in the *last* %c
  2328. // (the user may have provided their own)
  2329. lastC = index;
  2330. }
  2331. });
  2332. args.splice(lastC, 0, c);
  2333. return args;
  2334. }
  2335. /**
  2336. * Invokes `console.log()` when available.
  2337. * No-op when `console.log` is not a "function".
  2338. *
  2339. * @api public
  2340. */
  2341. function log() {
  2342. // this hackery is required for IE8/9, where
  2343. // the `console.log` function doesn't have 'apply'
  2344. return 'object' === typeof console
  2345. && console.log
  2346. && Function.prototype.apply.call(console.log, console, arguments);
  2347. }
  2348. /**
  2349. * Save `namespaces`.
  2350. *
  2351. * @param {String} namespaces
  2352. * @api private
  2353. */
  2354. function save(namespaces) {
  2355. try {
  2356. if (null == namespaces) {
  2357. exports.storage.removeItem('debug');
  2358. } else {
  2359. exports.storage.debug = namespaces;
  2360. }
  2361. } catch(e) {}
  2362. }
  2363. /**
  2364. * Load `namespaces`.
  2365. *
  2366. * @return {String} returns the previously persisted debug modes
  2367. * @api private
  2368. */
  2369. function load() {
  2370. var r;
  2371. try {
  2372. r = exports.storage.debug;
  2373. } catch(e) {}
  2374. return r;
  2375. }
  2376. /**
  2377. * Enable namespaces listed in `localStorage.debug` initially.
  2378. */
  2379. exports.enable(load());
  2380. /**
  2381. * Localstorage attempts to return the localstorage.
  2382. *
  2383. * This is necessary because safari throws
  2384. * when a user disables cookies/localstorage
  2385. * and you attempt to access it.
  2386. *
  2387. * @return {LocalStorage}
  2388. * @api private
  2389. */
  2390. function localstorage(){
  2391. try {
  2392. return window.localStorage;
  2393. } catch (e) {}
  2394. }
  2395. },{"./debug":9}],9:[function(_dereq_,module,exports){
  2396. /**
  2397. * This is the common logic for both the Node.js and web browser
  2398. * implementations of `debug()`.
  2399. *
  2400. * Expose `debug()` as the module.
  2401. */
  2402. exports = module.exports = debug;
  2403. exports.coerce = coerce;
  2404. exports.disable = disable;
  2405. exports.enable = enable;
  2406. exports.enabled = enabled;
  2407. /**
  2408. * The currently active debug mode names, and names to skip.
  2409. */
  2410. exports.names = [];
  2411. exports.skips = [];
  2412. /**
  2413. * Map of special "%n" handling functions, for the debug "format" argument.
  2414. *
  2415. * Valid key names are a single, lowercased letter, i.e. "n".
  2416. */
  2417. exports.formatters = {};
  2418. /**
  2419. * Previously assigned color.
  2420. */
  2421. var prevColor = 0;
  2422. /**
  2423. * Select a color.
  2424. *
  2425. * @return {Number}
  2426. * @api private
  2427. */
  2428. function selectColor() {
  2429. return exports.colors[prevColor++ % exports.colors.length];
  2430. }
  2431. /**
  2432. * Create a debugger with the given `namespace`.
  2433. *
  2434. * @param {String} namespace
  2435. * @return {Function}
  2436. * @api public
  2437. */
  2438. function debug(namespace) {
  2439. // define the `disabled` version
  2440. function disabled() {
  2441. }
  2442. disabled.enabled = false;
  2443. // define the `enabled` version
  2444. function enabled() {
  2445. var self = enabled;
  2446. // add the `color` if not set
  2447. if (null == self.useColors) self.useColors = exports.useColors();
  2448. if (null == self.color && self.useColors) self.color = selectColor();
  2449. var args = Array.prototype.slice.call(arguments);
  2450. args[0] = exports.coerce(args[0]);
  2451. if ('string' !== typeof args[0]) {
  2452. // anything else let's inspect with %o
  2453. args = ['%o'].concat(args);
  2454. }
  2455. // apply any `formatters` transformations
  2456. var index = 0;
  2457. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2458. // if we encounter an escaped % then don't increase the array index
  2459. if (match === '%%') return match;
  2460. index++;
  2461. var formatter = exports.formatters[format];
  2462. if ('function' === typeof formatter) {
  2463. var val = args[index];
  2464. match = formatter.call(self, val);
  2465. // now we need to remove `args[index]` since it's inlined in the `format`
  2466. args.splice(index, 1);
  2467. index--;
  2468. }
  2469. return match;
  2470. });
  2471. if ('function' === typeof exports.formatArgs) {
  2472. args = exports.formatArgs.apply(self, args);
  2473. }
  2474. var logFn = enabled.log || exports.log || console.log.bind(console);
  2475. logFn.apply(self, args);
  2476. }
  2477. enabled.enabled = true;
  2478. var fn = exports.enabled(namespace) ? enabled : disabled;
  2479. fn.namespace = namespace;
  2480. return fn;
  2481. }
  2482. /**
  2483. * Enables a debug mode by namespaces. This can include modes
  2484. * separated by a colon and wildcards.
  2485. *
  2486. * @param {String} namespaces
  2487. * @api public
  2488. */
  2489. function enable(namespaces) {
  2490. exports.save(namespaces);
  2491. var split = (namespaces || '').split(/[\s,]+/);
  2492. var len = split.length;
  2493. for (var i = 0; i < len; i++) {
  2494. if (!split[i]) continue; // ignore empty strings
  2495. namespaces = split[i].replace(/\*/g, '.*?');
  2496. if (namespaces[0] === '-') {
  2497. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2498. } else {
  2499. exports.names.push(new RegExp('^' + namespaces + '$'));
  2500. }
  2501. }
  2502. }
  2503. /**
  2504. * Disable debug output.
  2505. *
  2506. * @api public
  2507. */
  2508. function disable() {
  2509. exports.enable('');
  2510. }
  2511. /**
  2512. * Returns true if the given mode name is enabled, false otherwise.
  2513. *
  2514. * @param {String} name
  2515. * @return {Boolean}
  2516. * @api public
  2517. */
  2518. function enabled(name) {
  2519. var i, len;
  2520. for (i = 0, len = exports.skips.length; i < len; i++) {
  2521. if (exports.skips[i].test(name)) {
  2522. return false;
  2523. }
  2524. }
  2525. for (i = 0, len = exports.names.length; i < len; i++) {
  2526. if (exports.names[i].test(name)) {
  2527. return true;
  2528. }
  2529. }
  2530. return false;
  2531. }
  2532. /**
  2533. * Coerce `val`.
  2534. *
  2535. * @param {Mixed} val
  2536. * @return {Mixed}
  2537. * @api private
  2538. */
  2539. function coerce(val) {
  2540. if (val instanceof Error) return val.stack || val.message;
  2541. return val;
  2542. }
  2543. },{}],10:[function(_dereq_,module,exports){
  2544. 'use strict';
  2545. var isObj = _dereq_('is-obj');
  2546. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2547. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2548. function toObject(val) {
  2549. if (val === null || val === undefined) {
  2550. throw new TypeError('Sources cannot be null or undefined');
  2551. }
  2552. return Object(val);
  2553. }
  2554. function assignKey(to, from, key) {
  2555. var val = from[key];
  2556. if (val === undefined || val === null) {
  2557. return;
  2558. }
  2559. if (hasOwnProperty.call(to, key)) {
  2560. if (to[key] === undefined || to[key] === null) {
  2561. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2562. }
  2563. }
  2564. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2565. to[key] = val;
  2566. } else {
  2567. to[key] = assign(Object(to[key]), from[key]);
  2568. }
  2569. }
  2570. function assign(to, from) {
  2571. if (to === from) {
  2572. return to;
  2573. }
  2574. from = Object(from);
  2575. for (var key in from) {
  2576. if (hasOwnProperty.call(from, key)) {
  2577. assignKey(to, from, key);
  2578. }
  2579. }
  2580. if (Object.getOwnPropertySymbols) {
  2581. var symbols = Object.getOwnPropertySymbols(from);
  2582. for (var i = 0; i < symbols.length; i++) {
  2583. if (propIsEnumerable.call(from, symbols[i])) {
  2584. assignKey(to, from, symbols[i]);
  2585. }
  2586. }
  2587. }
  2588. return to;
  2589. }
  2590. module.exports = function deepAssign(target) {
  2591. target = toObject(target);
  2592. for (var s = 1; s < arguments.length; s++) {
  2593. assign(target, arguments[s]);
  2594. }
  2595. return target;
  2596. };
  2597. },{"is-obj":21}],11:[function(_dereq_,module,exports){
  2598. /*! (C) WebReflection Mit Style License */
  2599. (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");
  2600. },{}],12:[function(_dereq_,module,exports){
  2601. module.exports = function(dtype) {
  2602. switch (dtype) {
  2603. case 'int8':
  2604. return Int8Array
  2605. case 'int16':
  2606. return Int16Array
  2607. case 'int32':
  2608. return Int32Array
  2609. case 'uint8':
  2610. return Uint8Array
  2611. case 'uint16':
  2612. return Uint16Array
  2613. case 'uint32':
  2614. return Uint32Array
  2615. case 'float32':
  2616. return Float32Array
  2617. case 'float64':
  2618. return Float64Array
  2619. case 'array':
  2620. return Array
  2621. case 'uint8_clamped':
  2622. return Uint8ClampedArray
  2623. }
  2624. }
  2625. },{}],13:[function(_dereq_,module,exports){
  2626. /*eslint new-cap:0*/
  2627. var dtype = _dereq_('dtype')
  2628. module.exports = flattenVertexData
  2629. function flattenVertexData (data, output, offset) {
  2630. if (!data) throw new TypeError('must specify data as first parameter')
  2631. offset = +(offset || 0) | 0
  2632. if (Array.isArray(data) && Array.isArray(data[0])) {
  2633. var dim = data[0].length
  2634. var length = data.length * dim
  2635. // no output specified, create a new typed array
  2636. if (!output || typeof output === 'string') {
  2637. output = new (dtype(output || 'float32'))(length + offset)
  2638. }
  2639. var dstLength = output.length - offset
  2640. if (length !== dstLength) {
  2641. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2642. ' does not match destination length ' + dstLength)
  2643. }
  2644. for (var i = 0, k = offset; i < data.length; i++) {
  2645. for (var j = 0; j < dim; j++) {
  2646. output[k++] = data[i][j]
  2647. }
  2648. }
  2649. } else {
  2650. if (!output || typeof output === 'string') {
  2651. // no output, create a new one
  2652. var Ctor = dtype(output || 'float32')
  2653. if (offset === 0) {
  2654. output = new Ctor(data)
  2655. } else {
  2656. output = new Ctor(data.length + offset)
  2657. output.set(data, offset)
  2658. }
  2659. } else {
  2660. // store output in existing array
  2661. output.set(data, offset)
  2662. }
  2663. }
  2664. return output
  2665. }
  2666. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2667. var isFunction = _dereq_('is-function')
  2668. module.exports = forEach
  2669. var toString = Object.prototype.toString
  2670. var hasOwnProperty = Object.prototype.hasOwnProperty
  2671. function forEach(list, iterator, context) {
  2672. if (!isFunction(iterator)) {
  2673. throw new TypeError('iterator must be a function')
  2674. }
  2675. if (arguments.length < 3) {
  2676. context = this
  2677. }
  2678. if (toString.call(list) === '[object Array]')
  2679. forEachArray(list, iterator, context)
  2680. else if (typeof list === 'string')
  2681. forEachString(list, iterator, context)
  2682. else
  2683. forEachObject(list, iterator, context)
  2684. }
  2685. function forEachArray(array, iterator, context) {
  2686. for (var i = 0, len = array.length; i < len; i++) {
  2687. if (hasOwnProperty.call(array, i)) {
  2688. iterator.call(context, array[i], i, array)
  2689. }
  2690. }
  2691. }
  2692. function forEachString(string, iterator, context) {
  2693. for (var i = 0, len = string.length; i < len; i++) {
  2694. // no such thing as a sparse string.
  2695. iterator.call(context, string.charAt(i), i, string)
  2696. }
  2697. }
  2698. function forEachObject(object, iterator, context) {
  2699. for (var k in object) {
  2700. if (hasOwnProperty.call(object, k)) {
  2701. iterator.call(context, object[k], k, object)
  2702. }
  2703. }
  2704. }
  2705. },{"is-function":20}],15:[function(_dereq_,module,exports){
  2706. (function (global){
  2707. if (typeof window !== "undefined") {
  2708. module.exports = window;
  2709. } else if (typeof global !== "undefined") {
  2710. module.exports = global;
  2711. } else if (typeof self !== "undefined"){
  2712. module.exports = self;
  2713. } else {
  2714. module.exports = {};
  2715. }
  2716. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2717. },{}],16:[function(_dereq_,module,exports){
  2718. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2719. var e, m
  2720. var eLen = nBytes * 8 - mLen - 1
  2721. var eMax = (1 << eLen) - 1
  2722. var eBias = eMax >> 1
  2723. var nBits = -7
  2724. var i = isLE ? (nBytes - 1) : 0
  2725. var d = isLE ? -1 : 1
  2726. var s = buffer[offset + i]
  2727. i += d
  2728. e = s & ((1 << (-nBits)) - 1)
  2729. s >>= (-nBits)
  2730. nBits += eLen
  2731. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2732. m = e & ((1 << (-nBits)) - 1)
  2733. e >>= (-nBits)
  2734. nBits += mLen
  2735. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2736. if (e === 0) {
  2737. e = 1 - eBias
  2738. } else if (e === eMax) {
  2739. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2740. } else {
  2741. m = m + Math.pow(2, mLen)
  2742. e = e - eBias
  2743. }
  2744. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2745. }
  2746. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2747. var e, m, c
  2748. var eLen = nBytes * 8 - mLen - 1
  2749. var eMax = (1 << eLen) - 1
  2750. var eBias = eMax >> 1
  2751. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2752. var i = isLE ? 0 : (nBytes - 1)
  2753. var d = isLE ? 1 : -1
  2754. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2755. value = Math.abs(value)
  2756. if (isNaN(value) || value === Infinity) {
  2757. m = isNaN(value) ? 1 : 0
  2758. e = eMax
  2759. } else {
  2760. e = Math.floor(Math.log(value) / Math.LN2)
  2761. if (value * (c = Math.pow(2, -e)) < 1) {
  2762. e--
  2763. c *= 2
  2764. }
  2765. if (e + eBias >= 1) {
  2766. value += rt / c
  2767. } else {
  2768. value += rt * Math.pow(2, 1 - eBias)
  2769. }
  2770. if (value * c >= 2) {
  2771. e++
  2772. c /= 2
  2773. }
  2774. if (e + eBias >= eMax) {
  2775. m = 0
  2776. e = eMax
  2777. } else if (e + eBias >= 1) {
  2778. m = (value * c - 1) * Math.pow(2, mLen)
  2779. e = e + eBias
  2780. } else {
  2781. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2782. e = 0
  2783. }
  2784. }
  2785. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2786. e = (e << mLen) | m
  2787. eLen += mLen
  2788. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2789. buffer[offset + i - d] |= s * 128
  2790. }
  2791. },{}],17:[function(_dereq_,module,exports){
  2792. module.exports = function compile(property) {
  2793. if (!property || typeof property !== 'string')
  2794. throw new Error('must specify property for indexof search')
  2795. return new Function('array', 'value', 'start', [
  2796. 'start = start || 0',
  2797. 'for (var i=start; i<array.length; i++)',
  2798. ' if (array[i]["' + property +'"] === value)',
  2799. ' return i',
  2800. 'return -1'
  2801. ].join('\n'))
  2802. }
  2803. },{}],18:[function(_dereq_,module,exports){
  2804. if (typeof Object.create === 'function') {
  2805. // implementation from standard node.js 'util' module
  2806. module.exports = function inherits(ctor, superCtor) {
  2807. ctor.super_ = superCtor
  2808. ctor.prototype = Object.create(superCtor.prototype, {
  2809. constructor: {
  2810. value: ctor,
  2811. enumerable: false,
  2812. writable: true,
  2813. configurable: true
  2814. }
  2815. });
  2816. };
  2817. } else {
  2818. // old school shim for old browsers
  2819. module.exports = function inherits(ctor, superCtor) {
  2820. ctor.super_ = superCtor
  2821. var TempCtor = function () {}
  2822. TempCtor.prototype = superCtor.prototype
  2823. ctor.prototype = new TempCtor()
  2824. ctor.prototype.constructor = ctor
  2825. }
  2826. }
  2827. },{}],19:[function(_dereq_,module,exports){
  2828. /*!
  2829. * Determine if an object is a Buffer
  2830. *
  2831. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2832. * @license MIT
  2833. */
  2834. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2835. // Object.prototype.constructor. Remove this eventually
  2836. module.exports = function (obj) {
  2837. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2838. }
  2839. function isBuffer (obj) {
  2840. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2841. }
  2842. // For Node v0.10 support. Remove this eventually.
  2843. function isSlowBuffer (obj) {
  2844. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2845. }
  2846. },{}],20:[function(_dereq_,module,exports){
  2847. module.exports = isFunction
  2848. var toString = Object.prototype.toString
  2849. function isFunction (fn) {
  2850. var string = toString.call(fn)
  2851. return string === '[object Function]' ||
  2852. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2853. (typeof window !== 'undefined' &&
  2854. // IE8 and below
  2855. (fn === window.setTimeout ||
  2856. fn === window.alert ||
  2857. fn === window.confirm ||
  2858. fn === window.prompt))
  2859. };
  2860. },{}],21:[function(_dereq_,module,exports){
  2861. 'use strict';
  2862. module.exports = function (x) {
  2863. var type = typeof x;
  2864. return x !== null && (type === 'object' || type === 'function');
  2865. };
  2866. },{}],22:[function(_dereq_,module,exports){
  2867. var toString = {}.toString;
  2868. module.exports = Array.isArray || function (arr) {
  2869. return toString.call(arr) == '[object Array]';
  2870. };
  2871. },{}],23:[function(_dereq_,module,exports){
  2872. var wordWrap = _dereq_('word-wrapper')
  2873. var xtend = _dereq_('xtend')
  2874. var findChar = _dereq_('indexof-property')('id')
  2875. var number = _dereq_('as-number')
  2876. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2877. var M_WIDTHS = ['m', 'w']
  2878. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2879. var TAB_ID = '\t'.charCodeAt(0)
  2880. var SPACE_ID = ' '.charCodeAt(0)
  2881. var ALIGN_LEFT = 0,
  2882. ALIGN_CENTER = 1,
  2883. ALIGN_RIGHT = 2
  2884. module.exports = function createLayout(opt) {
  2885. return new TextLayout(opt)
  2886. }
  2887. function TextLayout(opt) {
  2888. this.glyphs = []
  2889. this._measure = this.computeMetrics.bind(this)
  2890. this.update(opt)
  2891. }
  2892. TextLayout.prototype.update = function(opt) {
  2893. opt = xtend({
  2894. measure: this._measure
  2895. }, opt)
  2896. this._opt = opt
  2897. this._opt.tabSize = number(this._opt.tabSize, 4)
  2898. if (!opt.font)
  2899. throw new Error('must provide a valid bitmap font')
  2900. var glyphs = this.glyphs
  2901. var text = opt.text||''
  2902. var font = opt.font
  2903. this._setupSpaceGlyphs(font)
  2904. var lines = wordWrap.lines(text, opt)
  2905. var minWidth = opt.width || 0
  2906. //clear glyphs
  2907. glyphs.length = 0
  2908. //get max line width
  2909. var maxLineWidth = lines.reduce(function(prev, line) {
  2910. return Math.max(prev, line.width, minWidth)
  2911. }, 0)
  2912. //the pen position
  2913. var x = 0
  2914. var y = 0
  2915. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2916. var baseline = font.common.base
  2917. var descender = lineHeight-baseline
  2918. var letterSpacing = opt.letterSpacing || 0
  2919. var height = lineHeight * lines.length - descender
  2920. var align = getAlignType(this._opt.align)
  2921. //draw text along baseline
  2922. y -= height
  2923. //the metrics for this text layout
  2924. this._width = maxLineWidth
  2925. this._height = height
  2926. this._descender = lineHeight - baseline
  2927. this._baseline = baseline
  2928. this._xHeight = getXHeight(font)
  2929. this._capHeight = getCapHeight(font)
  2930. this._lineHeight = lineHeight
  2931. this._ascender = lineHeight - descender - this._xHeight
  2932. //layout each glyph
  2933. var self = this
  2934. lines.forEach(function(line, lineIndex) {
  2935. var start = line.start
  2936. var end = line.end
  2937. var lineWidth = line.width
  2938. var lastGlyph
  2939. //for each glyph in that line...
  2940. for (var i=start; i<end; i++) {
  2941. var id = text.charCodeAt(i)
  2942. var glyph = self.getGlyph(font, id)
  2943. if (glyph) {
  2944. if (lastGlyph)
  2945. x += getKerning(font, lastGlyph.id, glyph.id)
  2946. var tx = x
  2947. if (align === ALIGN_CENTER)
  2948. tx += (maxLineWidth-lineWidth)/2
  2949. else if (align === ALIGN_RIGHT)
  2950. tx += (maxLineWidth-lineWidth)
  2951. glyphs.push({
  2952. position: [tx, y],
  2953. data: glyph,
  2954. index: i,
  2955. line: lineIndex
  2956. })
  2957. //move pen forward
  2958. x += glyph.xadvance + letterSpacing
  2959. lastGlyph = glyph
  2960. }
  2961. }
  2962. //next line down
  2963. y += lineHeight
  2964. x = 0
  2965. })
  2966. this._linesTotal = lines.length;
  2967. }
  2968. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2969. //These are fallbacks, when the font doesn't include
  2970. //' ' or '\t' glyphs
  2971. this._fallbackSpaceGlyph = null
  2972. this._fallbackTabGlyph = null
  2973. if (!font.chars || font.chars.length === 0)
  2974. return
  2975. //try to get space glyph
  2976. //then fall back to the 'm' or 'w' glyphs
  2977. //then fall back to the first glyph available
  2978. var space = getGlyphById(font, SPACE_ID)
  2979. || getMGlyph(font)
  2980. || font.chars[0]
  2981. //and create a fallback for tab
  2982. var tabWidth = this._opt.tabSize * space.xadvance
  2983. this._fallbackSpaceGlyph = space
  2984. this._fallbackTabGlyph = xtend(space, {
  2985. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2986. xoffset: 0, yoffset: 0, width: 0, height: 0
  2987. })
  2988. }
  2989. TextLayout.prototype.getGlyph = function(font, id) {
  2990. var glyph = getGlyphById(font, id)
  2991. if (glyph)
  2992. return glyph
  2993. else if (id === TAB_ID)
  2994. return this._fallbackTabGlyph
  2995. else if (id === SPACE_ID)
  2996. return this._fallbackSpaceGlyph
  2997. return null
  2998. }
  2999. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3000. var letterSpacing = this._opt.letterSpacing || 0
  3001. var font = this._opt.font
  3002. var curPen = 0
  3003. var curWidth = 0
  3004. var count = 0
  3005. var glyph
  3006. var lastGlyph
  3007. if (!font.chars || font.chars.length === 0) {
  3008. return {
  3009. start: start,
  3010. end: start,
  3011. width: 0
  3012. }
  3013. }
  3014. end = Math.min(text.length, end)
  3015. for (var i=start; i < end; i++) {
  3016. var id = text.charCodeAt(i)
  3017. var glyph = this.getGlyph(font, id)
  3018. if (glyph) {
  3019. //move pen forward
  3020. var xoff = glyph.xoffset
  3021. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3022. curPen += kern
  3023. var nextPen = curPen + glyph.xadvance + letterSpacing
  3024. var nextWidth = curPen + glyph.width
  3025. //we've hit our limit; we can't move onto the next glyph
  3026. if (nextWidth >= width || nextPen >= width)
  3027. break
  3028. //otherwise continue along our line
  3029. curPen = nextPen
  3030. curWidth = nextWidth
  3031. lastGlyph = glyph
  3032. }
  3033. count++
  3034. }
  3035. //make sure rightmost edge lines up with rendered glyphs
  3036. if (lastGlyph)
  3037. curWidth += lastGlyph.xoffset
  3038. return {
  3039. start: start,
  3040. end: start + count,
  3041. width: curWidth
  3042. }
  3043. }
  3044. //getters for the private vars
  3045. ;['width', 'height',
  3046. 'descender', 'ascender',
  3047. 'xHeight', 'baseline',
  3048. 'capHeight',
  3049. 'lineHeight' ].forEach(addGetter)
  3050. function addGetter(name) {
  3051. Object.defineProperty(TextLayout.prototype, name, {
  3052. get: wrapper(name),
  3053. configurable: true
  3054. })
  3055. }
  3056. //create lookups for private vars
  3057. function wrapper(name) {
  3058. return (new Function([
  3059. 'return function '+name+'() {',
  3060. ' return this._'+name,
  3061. '}'
  3062. ].join('\n')))()
  3063. }
  3064. function getGlyphById(font, id) {
  3065. if (!font.chars || font.chars.length === 0)
  3066. return null
  3067. var glyphIdx = findChar(font.chars, id)
  3068. if (glyphIdx >= 0)
  3069. return font.chars[glyphIdx]
  3070. return null
  3071. }
  3072. function getXHeight(font) {
  3073. for (var i=0; i<X_HEIGHTS.length; i++) {
  3074. var id = X_HEIGHTS[i].charCodeAt(0)
  3075. var idx = findChar(font.chars, id)
  3076. if (idx >= 0)
  3077. return font.chars[idx].height
  3078. }
  3079. return 0
  3080. }
  3081. function getMGlyph(font) {
  3082. for (var i=0; i<M_WIDTHS.length; i++) {
  3083. var id = M_WIDTHS[i].charCodeAt(0)
  3084. var idx = findChar(font.chars, id)
  3085. if (idx >= 0)
  3086. return font.chars[idx]
  3087. }
  3088. return 0
  3089. }
  3090. function getCapHeight(font) {
  3091. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3092. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3093. var idx = findChar(font.chars, id)
  3094. if (idx >= 0)
  3095. return font.chars[idx].height
  3096. }
  3097. return 0
  3098. }
  3099. function getKerning(font, left, right) {
  3100. if (!font.kernings || font.kernings.length === 0)
  3101. return 0
  3102. var table = font.kernings
  3103. for (var i=0; i<table.length; i++) {
  3104. var kern = table[i]
  3105. if (kern.first === left && kern.second === right)
  3106. return kern.amount
  3107. }
  3108. return 0
  3109. }
  3110. function getAlignType(align) {
  3111. if (align === 'center')
  3112. return ALIGN_CENTER
  3113. else if (align === 'right')
  3114. return ALIGN_RIGHT
  3115. return ALIGN_LEFT
  3116. }
  3117. },{"as-number":3,"indexof-property":17,"word-wrapper":72,"xtend":75}],24:[function(_dereq_,module,exports){
  3118. (function (Buffer){
  3119. var xhr = _dereq_('xhr')
  3120. var noop = function(){}
  3121. var parseASCII = _dereq_('parse-bmfont-ascii')
  3122. var parseXML = _dereq_('parse-bmfont-xml')
  3123. var readBinary = _dereq_('parse-bmfont-binary')
  3124. var isBinaryFormat = _dereq_('./lib/is-binary')
  3125. var xtend = _dereq_('xtend')
  3126. var xml2 = (function hasXML2() {
  3127. return window.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3128. })()
  3129. module.exports = function(opt, cb) {
  3130. cb = typeof cb === 'function' ? cb : noop
  3131. if (typeof opt === 'string')
  3132. opt = { uri: opt }
  3133. else if (!opt)
  3134. opt = {}
  3135. var expectBinary = opt.binary
  3136. if (expectBinary)
  3137. opt = getBinaryOpts(opt)
  3138. xhr(opt, function(err, res, body) {
  3139. if (err)
  3140. return cb(err)
  3141. if (!/^2/.test(res.statusCode))
  3142. return cb(new Error('http status code: '+res.statusCode))
  3143. if (!body)
  3144. return cb(new Error('no body result'))
  3145. var binary = false
  3146. //if the response type is an array buffer,
  3147. //we need to convert it into a regular Buffer object
  3148. if (isArrayBuffer(body)) {
  3149. var array = new Uint8Array(body)
  3150. body = new Buffer(array, 'binary')
  3151. }
  3152. //now check the string/Buffer response
  3153. //and see if it has a binary BMF header
  3154. if (isBinaryFormat(body)) {
  3155. binary = true
  3156. //if we have a string, turn it into a Buffer
  3157. if (typeof body === 'string')
  3158. body = new Buffer(body, 'binary')
  3159. }
  3160. //we are not parsing a binary format, just ASCII/XML/etc
  3161. if (!binary) {
  3162. //might still be a buffer if responseType is 'arraybuffer'
  3163. if (Buffer.isBuffer(body))
  3164. body = body.toString(opt.encoding)
  3165. body = body.trim()
  3166. }
  3167. var result
  3168. try {
  3169. var type = res.headers['content-type']
  3170. if (binary)
  3171. result = readBinary(body)
  3172. else if (/json/.test(type) || body.charAt(0) === '{')
  3173. result = JSON.parse(body)
  3174. else if (/xml/.test(type) || body.charAt(0) === '<')
  3175. result = parseXML(body)
  3176. else
  3177. result = parseASCII(body)
  3178. } catch (e) {
  3179. cb(new Error('error parsing font '+e.message))
  3180. cb = noop
  3181. }
  3182. cb(null, result)
  3183. })
  3184. }
  3185. function isArrayBuffer(arr) {
  3186. var str = Object.prototype.toString
  3187. return str.call(arr) === '[object ArrayBuffer]'
  3188. }
  3189. function getBinaryOpts(opt) {
  3190. //IE10+ and other modern browsers support array buffers
  3191. if (xml2)
  3192. return xtend(opt, { responseType: 'arraybuffer' })
  3193. if (typeof window.XMLHttpRequest === 'undefined')
  3194. throw new Error('your browser does not support XHR loading')
  3195. //IE9 and XML1 browsers could still use an override
  3196. var req = new window.XMLHttpRequest()
  3197. req.overrideMimeType('text/plain; charset=x-user-defined')
  3198. return xtend({
  3199. xhr: req
  3200. }, opt)
  3201. }
  3202. }).call(this,_dereq_("buffer").Buffer)
  3203. },{"./lib/is-binary":25,"buffer":7,"parse-bmfont-ascii":27,"parse-bmfont-binary":28,"parse-bmfont-xml":29,"xhr":73,"xtend":75}],25:[function(_dereq_,module,exports){
  3204. (function (Buffer){
  3205. var equal = _dereq_('buffer-equal')
  3206. var HEADER = new Buffer([66, 77, 70, 3])
  3207. module.exports = function(buf) {
  3208. if (typeof buf === 'string')
  3209. return buf.substring(0, 3) === 'BMF'
  3210. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3211. }
  3212. }).call(this,_dereq_("buffer").Buffer)
  3213. },{"buffer":7,"buffer-equal":6}],26:[function(_dereq_,module,exports){
  3214. 'use strict';
  3215. /* eslint-disable no-unused-vars */
  3216. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3217. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3218. function toObject(val) {
  3219. if (val === null || val === undefined) {
  3220. throw new TypeError('Object.assign cannot be called with null or undefined');
  3221. }
  3222. return Object(val);
  3223. }
  3224. function shouldUseNative() {
  3225. try {
  3226. if (!Object.assign) {
  3227. return false;
  3228. }
  3229. // Detect buggy property enumeration order in older V8 versions.
  3230. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3231. var test1 = new String('abc'); // eslint-disable-line
  3232. test1[5] = 'de';
  3233. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3234. return false;
  3235. }
  3236. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3237. var test2 = {};
  3238. for (var i = 0; i < 10; i++) {
  3239. test2['_' + String.fromCharCode(i)] = i;
  3240. }
  3241. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3242. return test2[n];
  3243. });
  3244. if (order2.join('') !== '0123456789') {
  3245. return false;
  3246. }
  3247. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3248. var test3 = {};
  3249. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3250. test3[letter] = letter;
  3251. });
  3252. if (Object.keys(Object.assign({}, test3)).join('') !==
  3253. 'abcdefghijklmnopqrst') {
  3254. return false;
  3255. }
  3256. return true;
  3257. } catch (e) {
  3258. // We don't expect any of the above to throw, but better to be safe.
  3259. return false;
  3260. }
  3261. }
  3262. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3263. var from;
  3264. var to = toObject(target);
  3265. var symbols;
  3266. for (var s = 1; s < arguments.length; s++) {
  3267. from = Object(arguments[s]);
  3268. for (var key in from) {
  3269. if (hasOwnProperty.call(from, key)) {
  3270. to[key] = from[key];
  3271. }
  3272. }
  3273. if (Object.getOwnPropertySymbols) {
  3274. symbols = Object.getOwnPropertySymbols(from);
  3275. for (var i = 0; i < symbols.length; i++) {
  3276. if (propIsEnumerable.call(from, symbols[i])) {
  3277. to[symbols[i]] = from[symbols[i]];
  3278. }
  3279. }
  3280. }
  3281. }
  3282. return to;
  3283. };
  3284. },{}],27:[function(_dereq_,module,exports){
  3285. module.exports = function parseBMFontAscii(data) {
  3286. if (!data)
  3287. throw new Error('no data provided')
  3288. data = data.toString().trim()
  3289. var output = {
  3290. pages: [],
  3291. chars: [],
  3292. kernings: []
  3293. }
  3294. var lines = data.split(/\r\n?|\n/g)
  3295. if (lines.length === 0)
  3296. throw new Error('no data in BMFont file')
  3297. for (var i = 0; i < lines.length; i++) {
  3298. var lineData = splitLine(lines[i], i)
  3299. if (!lineData) //skip empty lines
  3300. continue
  3301. if (lineData.key === 'page') {
  3302. if (typeof lineData.data.id !== 'number')
  3303. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3304. if (typeof lineData.data.file !== 'string')
  3305. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3306. output.pages[lineData.data.id] = lineData.data.file
  3307. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3308. //... do nothing for these two ...
  3309. } else if (lineData.key === 'char') {
  3310. output.chars.push(lineData.data)
  3311. } else if (lineData.key === 'kerning') {
  3312. output.kernings.push(lineData.data)
  3313. } else {
  3314. output[lineData.key] = lineData.data
  3315. }
  3316. }
  3317. return output
  3318. }
  3319. function splitLine(line, idx) {
  3320. line = line.replace(/\t+/g, ' ').trim()
  3321. if (!line)
  3322. return null
  3323. var space = line.indexOf(' ')
  3324. if (space === -1)
  3325. throw new Error("no named row at line " + idx)
  3326. var key = line.substring(0, space)
  3327. line = line.substring(space + 1)
  3328. //clear "letter" field as it is non-standard and
  3329. //requires additional complexity to parse " / = symbols
  3330. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3331. line = line.split("=")
  3332. line = line.map(function(str) {
  3333. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3334. })
  3335. var data = []
  3336. for (var i = 0; i < line.length; i++) {
  3337. var dt = line[i]
  3338. if (i === 0) {
  3339. data.push({
  3340. key: dt[0],
  3341. data: ""
  3342. })
  3343. } else if (i === line.length - 1) {
  3344. data[data.length - 1].data = parseData(dt[0])
  3345. } else {
  3346. data[data.length - 1].data = parseData(dt[0])
  3347. data.push({
  3348. key: dt[1],
  3349. data: ""
  3350. })
  3351. }
  3352. }
  3353. var out = {
  3354. key: key,
  3355. data: {}
  3356. }
  3357. data.forEach(function(v) {
  3358. out.data[v.key] = v.data;
  3359. })
  3360. return out
  3361. }
  3362. function parseData(data) {
  3363. if (!data || data.length === 0)
  3364. return ""
  3365. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3366. return data.substring(1, data.length - 1)
  3367. if (data.indexOf(',') !== -1)
  3368. return parseIntList(data)
  3369. return parseInt(data, 10)
  3370. }
  3371. function parseIntList(data) {
  3372. return data.split(',').map(function(val) {
  3373. return parseInt(val, 10)
  3374. })
  3375. }
  3376. },{}],28:[function(_dereq_,module,exports){
  3377. var HEADER = [66, 77, 70]
  3378. module.exports = function readBMFontBinary(buf) {
  3379. if (buf.length < 6)
  3380. throw new Error('invalid buffer length for BMFont')
  3381. var header = HEADER.every(function(byte, i) {
  3382. return buf.readUInt8(i) === byte
  3383. })
  3384. if (!header)
  3385. throw new Error('BMFont missing BMF byte header')
  3386. var i = 3
  3387. var vers = buf.readUInt8(i++)
  3388. if (vers > 3)
  3389. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3390. var target = { kernings: [], chars: [] }
  3391. for (var b=0; b<5; b++)
  3392. i += readBlock(target, buf, i)
  3393. return target
  3394. }
  3395. function readBlock(target, buf, i) {
  3396. if (i > buf.length-1)
  3397. return 0
  3398. var blockID = buf.readUInt8(i++)
  3399. var blockSize = buf.readInt32LE(i)
  3400. i += 4
  3401. switch(blockID) {
  3402. case 1:
  3403. target.info = readInfo(buf, i)
  3404. break
  3405. case 2:
  3406. target.common = readCommon(buf, i)
  3407. break
  3408. case 3:
  3409. target.pages = readPages(buf, i, blockSize)
  3410. break
  3411. case 4:
  3412. target.chars = readChars(buf, i, blockSize)
  3413. break
  3414. case 5:
  3415. target.kernings = readKernings(buf, i, blockSize)
  3416. break
  3417. }
  3418. return 5 + blockSize
  3419. }
  3420. function readInfo(buf, i) {
  3421. var info = {}
  3422. info.size = buf.readInt16LE(i)
  3423. var bitField = buf.readUInt8(i+2)
  3424. info.smooth = (bitField >> 7) & 1
  3425. info.unicode = (bitField >> 6) & 1
  3426. info.italic = (bitField >> 5) & 1
  3427. info.bold = (bitField >> 4) & 1
  3428. //fixedHeight is only mentioned in binary spec
  3429. if ((bitField >> 3) & 1)
  3430. info.fixedHeight = 1
  3431. info.charset = buf.readUInt8(i+3) || ''
  3432. info.stretchH = buf.readUInt16LE(i+4)
  3433. info.aa = buf.readUInt8(i+6)
  3434. info.padding = [
  3435. buf.readInt8(i+7),
  3436. buf.readInt8(i+8),
  3437. buf.readInt8(i+9),
  3438. buf.readInt8(i+10)
  3439. ]
  3440. info.spacing = [
  3441. buf.readInt8(i+11),
  3442. buf.readInt8(i+12)
  3443. ]
  3444. info.outline = buf.readUInt8(i+13)
  3445. info.face = readStringNT(buf, i+14)
  3446. return info
  3447. }
  3448. function readCommon(buf, i) {
  3449. var common = {}
  3450. common.lineHeight = buf.readUInt16LE(i)
  3451. common.base = buf.readUInt16LE(i+2)
  3452. common.scaleW = buf.readUInt16LE(i+4)
  3453. common.scaleH = buf.readUInt16LE(i+6)
  3454. common.pages = buf.readUInt16LE(i+8)
  3455. var bitField = buf.readUInt8(i+10)
  3456. common.packed = 0
  3457. common.alphaChnl = buf.readUInt8(i+11)
  3458. common.redChnl = buf.readUInt8(i+12)
  3459. common.greenChnl = buf.readUInt8(i+13)
  3460. common.blueChnl = buf.readUInt8(i+14)
  3461. return common
  3462. }
  3463. function readPages(buf, i, size) {
  3464. var pages = []
  3465. var text = readNameNT(buf, i)
  3466. var len = text.length+1
  3467. var count = size / len
  3468. for (var c=0; c<count; c++) {
  3469. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3470. i += len
  3471. }
  3472. return pages
  3473. }
  3474. function readChars(buf, i, blockSize) {
  3475. var chars = []
  3476. var count = blockSize / 20
  3477. for (var c=0; c<count; c++) {
  3478. var char = {}
  3479. var off = c*20
  3480. char.id = buf.readUInt32LE(i + 0 + off)
  3481. char.x = buf.readUInt16LE(i + 4 + off)
  3482. char.y = buf.readUInt16LE(i + 6 + off)
  3483. char.width = buf.readUInt16LE(i + 8 + off)
  3484. char.height = buf.readUInt16LE(i + 10 + off)
  3485. char.xoffset = buf.readInt16LE(i + 12 + off)
  3486. char.yoffset = buf.readInt16LE(i + 14 + off)
  3487. char.xadvance = buf.readInt16LE(i + 16 + off)
  3488. char.page = buf.readUInt8(i + 18 + off)
  3489. char.chnl = buf.readUInt8(i + 19 + off)
  3490. chars[c] = char
  3491. }
  3492. return chars
  3493. }
  3494. function readKernings(buf, i, blockSize) {
  3495. var kernings = []
  3496. var count = blockSize / 10
  3497. for (var c=0; c<count; c++) {
  3498. var kern = {}
  3499. var off = c*10
  3500. kern.first = buf.readUInt32LE(i + 0 + off)
  3501. kern.second = buf.readUInt32LE(i + 4 + off)
  3502. kern.amount = buf.readInt16LE(i + 8 + off)
  3503. kernings[c] = kern
  3504. }
  3505. return kernings
  3506. }
  3507. function readNameNT(buf, offset) {
  3508. var pos=offset
  3509. for (; pos<buf.length; pos++) {
  3510. if (buf[pos] === 0x00)
  3511. break
  3512. }
  3513. return buf.slice(offset, pos)
  3514. }
  3515. function readStringNT(buf, offset) {
  3516. return readNameNT(buf, offset).toString('utf8')
  3517. }
  3518. },{}],29:[function(_dereq_,module,exports){
  3519. var parseAttributes = _dereq_('./parse-attribs')
  3520. var parseFromString = _dereq_('xml-parse-from-string')
  3521. //In some cases element.attribute.nodeName can return
  3522. //all lowercase values.. so we need to map them to the correct
  3523. //case
  3524. var NAME_MAP = {
  3525. scaleh: 'scaleH',
  3526. scalew: 'scaleW',
  3527. stretchh: 'stretchH',
  3528. lineheight: 'lineHeight',
  3529. alphachnl: 'alphaChnl',
  3530. redchnl: 'redChnl',
  3531. greenchnl: 'greenChnl',
  3532. bluechnl: 'blueChnl'
  3533. }
  3534. module.exports = function parse(data) {
  3535. data = data.toString()
  3536. var xmlRoot = parseFromString(data)
  3537. var output = {
  3538. pages: [],
  3539. chars: [],
  3540. kernings: []
  3541. }
  3542. //get config settings
  3543. ;['info', 'common'].forEach(function(key) {
  3544. var element = xmlRoot.getElementsByTagName(key)[0]
  3545. if (element)
  3546. output[key] = parseAttributes(getAttribs(element))
  3547. })
  3548. //get page info
  3549. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3550. if (!pageRoot)
  3551. throw new Error('malformed file -- no <pages> element')
  3552. var pages = pageRoot.getElementsByTagName('page')
  3553. for (var i=0; i<pages.length; i++) {
  3554. var p = pages[i]
  3555. var id = parseInt(p.getAttribute('id'), 10)
  3556. var file = p.getAttribute('file')
  3557. if (isNaN(id))
  3558. throw new Error('malformed file -- page "id" attribute is NaN')
  3559. if (!file)
  3560. throw new Error('malformed file -- needs page "file" attribute')
  3561. output.pages[parseInt(id, 10)] = file
  3562. }
  3563. //get kernings / chars
  3564. ;['chars', 'kernings'].forEach(function(key) {
  3565. var element = xmlRoot.getElementsByTagName(key)[0]
  3566. if (!element)
  3567. return
  3568. var childTag = key.substring(0, key.length-1)
  3569. var children = element.getElementsByTagName(childTag)
  3570. for (var i=0; i<children.length; i++) {
  3571. var child = children[i]
  3572. output[key].push(parseAttributes(getAttribs(child)))
  3573. }
  3574. })
  3575. return output
  3576. }
  3577. function getAttribs(element) {
  3578. var attribs = getAttribList(element)
  3579. return attribs.reduce(function(dict, attrib) {
  3580. var key = mapName(attrib.nodeName)
  3581. dict[key] = attrib.nodeValue
  3582. return dict
  3583. }, {})
  3584. }
  3585. function getAttribList(element) {
  3586. //IE8+ and modern browsers
  3587. var attribs = []
  3588. for (var i=0; i<element.attributes.length; i++)
  3589. attribs.push(element.attributes[i])
  3590. return attribs
  3591. }
  3592. function mapName(nodeName) {
  3593. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3594. }
  3595. },{"./parse-attribs":30,"xml-parse-from-string":74}],30:[function(_dereq_,module,exports){
  3596. //Some versions of GlyphDesigner have a typo
  3597. //that causes some bugs with parsing.
  3598. //Need to confirm with recent version of the software
  3599. //to see whether this is still an issue or not.
  3600. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3601. module.exports = function parseAttributes(obj) {
  3602. if (GLYPH_DESIGNER_ERROR in obj) {
  3603. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3604. delete obj[GLYPH_DESIGNER_ERROR]
  3605. }
  3606. for (var k in obj) {
  3607. if (k === 'face' || k === 'charset')
  3608. continue
  3609. else if (k === 'padding' || k === 'spacing')
  3610. obj[k] = parseIntList(obj[k])
  3611. else
  3612. obj[k] = parseInt(obj[k], 10)
  3613. }
  3614. return obj
  3615. }
  3616. function parseIntList(data) {
  3617. return data.split(',').map(function(val) {
  3618. return parseInt(val, 10)
  3619. })
  3620. }
  3621. },{}],31:[function(_dereq_,module,exports){
  3622. var trim = _dereq_('trim')
  3623. , forEach = _dereq_('for-each')
  3624. , isArray = function(arg) {
  3625. return Object.prototype.toString.call(arg) === '[object Array]';
  3626. }
  3627. module.exports = function (headers) {
  3628. if (!headers)
  3629. return {}
  3630. var result = {}
  3631. forEach(
  3632. trim(headers).split('\n')
  3633. , function (row) {
  3634. var index = row.indexOf(':')
  3635. , key = trim(row.slice(0, index)).toLowerCase()
  3636. , value = trim(row.slice(index + 1))
  3637. if (typeof(result[key]) === 'undefined') {
  3638. result[key] = value
  3639. } else if (isArray(result[key])) {
  3640. result[key].push(value)
  3641. } else {
  3642. result[key] = [ result[key], value ]
  3643. }
  3644. }
  3645. )
  3646. return result
  3647. }
  3648. },{"for-each":14,"trim":46}],32:[function(_dereq_,module,exports){
  3649. (function (global){
  3650. var performance = global.performance || {};
  3651. var present = (function () {
  3652. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3653. while (names.length) {
  3654. var name = names.shift();
  3655. if (name in performance) {
  3656. return performance[name].bind(performance);
  3657. }
  3658. }
  3659. var dateNow = Date.now || function () { return new Date().getTime(); };
  3660. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3661. return function () {
  3662. return dateNow() - navigationStart;
  3663. };
  3664. }());
  3665. present.performanceNow = performance.now;
  3666. present.noConflict = function () {
  3667. performance.now = present.performanceNow;
  3668. };
  3669. present.conflict = function () {
  3670. performance.now = present;
  3671. };
  3672. present.conflict();
  3673. module.exports = present;
  3674. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3675. },{}],33:[function(_dereq_,module,exports){
  3676. // shim for using process in browser
  3677. var process = module.exports = {};
  3678. // cached from whatever global is present so that test runners that stub it
  3679. // don't break things. But we need to wrap it in a try catch in case it is
  3680. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3681. // function because try/catches deoptimize in certain engines.
  3682. var cachedSetTimeout;
  3683. var cachedClearTimeout;
  3684. function defaultSetTimout() {
  3685. throw new Error('setTimeout has not been defined');
  3686. }
  3687. function defaultClearTimeout () {
  3688. throw new Error('clearTimeout has not been defined');
  3689. }
  3690. (function () {
  3691. try {
  3692. if (typeof setTimeout === 'function') {
  3693. cachedSetTimeout = setTimeout;
  3694. } else {
  3695. cachedSetTimeout = defaultSetTimout;
  3696. }
  3697. } catch (e) {
  3698. cachedSetTimeout = defaultSetTimout;
  3699. }
  3700. try {
  3701. if (typeof clearTimeout === 'function') {
  3702. cachedClearTimeout = clearTimeout;
  3703. } else {
  3704. cachedClearTimeout = defaultClearTimeout;
  3705. }
  3706. } catch (e) {
  3707. cachedClearTimeout = defaultClearTimeout;
  3708. }
  3709. } ())
  3710. function runTimeout(fun) {
  3711. if (cachedSetTimeout === setTimeout) {
  3712. //normal enviroments in sane situations
  3713. return setTimeout(fun, 0);
  3714. }
  3715. // if setTimeout wasn't available but was latter defined
  3716. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3717. cachedSetTimeout = setTimeout;
  3718. return setTimeout(fun, 0);
  3719. }
  3720. try {
  3721. // when when somebody has screwed with setTimeout but no I.E. maddness
  3722. return cachedSetTimeout(fun, 0);
  3723. } catch(e){
  3724. try {
  3725. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3726. return cachedSetTimeout.call(null, fun, 0);
  3727. } catch(e){
  3728. // 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
  3729. return cachedSetTimeout.call(this, fun, 0);
  3730. }
  3731. }
  3732. }
  3733. function runClearTimeout(marker) {
  3734. if (cachedClearTimeout === clearTimeout) {
  3735. //normal enviroments in sane situations
  3736. return clearTimeout(marker);
  3737. }
  3738. // if clearTimeout wasn't available but was latter defined
  3739. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3740. cachedClearTimeout = clearTimeout;
  3741. return clearTimeout(marker);
  3742. }
  3743. try {
  3744. // when when somebody has screwed with setTimeout but no I.E. maddness
  3745. return cachedClearTimeout(marker);
  3746. } catch (e){
  3747. try {
  3748. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3749. return cachedClearTimeout.call(null, marker);
  3750. } catch (e){
  3751. // 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.
  3752. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3753. return cachedClearTimeout.call(this, marker);
  3754. }
  3755. }
  3756. }
  3757. var queue = [];
  3758. var draining = false;
  3759. var currentQueue;
  3760. var queueIndex = -1;
  3761. function cleanUpNextTick() {
  3762. if (!draining || !currentQueue) {
  3763. return;
  3764. }
  3765. draining = false;
  3766. if (currentQueue.length) {
  3767. queue = currentQueue.concat(queue);
  3768. } else {
  3769. queueIndex = -1;
  3770. }
  3771. if (queue.length) {
  3772. drainQueue();
  3773. }
  3774. }
  3775. function drainQueue() {
  3776. if (draining) {
  3777. return;
  3778. }
  3779. var timeout = runTimeout(cleanUpNextTick);
  3780. draining = true;
  3781. var len = queue.length;
  3782. while(len) {
  3783. currentQueue = queue;
  3784. queue = [];
  3785. while (++queueIndex < len) {
  3786. if (currentQueue) {
  3787. currentQueue[queueIndex].run();
  3788. }
  3789. }
  3790. queueIndex = -1;
  3791. len = queue.length;
  3792. }
  3793. currentQueue = null;
  3794. draining = false;
  3795. runClearTimeout(timeout);
  3796. }
  3797. process.nextTick = function (fun) {
  3798. var args = new Array(arguments.length - 1);
  3799. if (arguments.length > 1) {
  3800. for (var i = 1; i < arguments.length; i++) {
  3801. args[i - 1] = arguments[i];
  3802. }
  3803. }
  3804. queue.push(new Item(fun, args));
  3805. if (queue.length === 1 && !draining) {
  3806. runTimeout(drainQueue);
  3807. }
  3808. };
  3809. // v8 likes predictible objects
  3810. function Item(fun, array) {
  3811. this.fun = fun;
  3812. this.array = array;
  3813. }
  3814. Item.prototype.run = function () {
  3815. this.fun.apply(null, this.array);
  3816. };
  3817. process.title = 'browser';
  3818. process.browser = true;
  3819. process.env = {};
  3820. process.argv = [];
  3821. process.version = ''; // empty string to avoid regexp issues
  3822. process.versions = {};
  3823. function noop() {}
  3824. process.on = noop;
  3825. process.addListener = noop;
  3826. process.once = noop;
  3827. process.off = noop;
  3828. process.removeListener = noop;
  3829. process.removeAllListeners = noop;
  3830. process.emit = noop;
  3831. process.binding = function (name) {
  3832. throw new Error('process.binding is not supported');
  3833. };
  3834. process.cwd = function () { return '/' };
  3835. process.chdir = function (dir) {
  3836. throw new Error('process.chdir is not supported');
  3837. };
  3838. process.umask = function() { return 0; };
  3839. },{}],34:[function(_dereq_,module,exports){
  3840. (function(root) {
  3841. // Store setTimeout reference so promise-polyfill will be unaffected by
  3842. // other code modifying setTimeout (like sinon.useFakeTimers())
  3843. var setTimeoutFunc = setTimeout;
  3844. // Use polyfill for setImmediate for performance gains
  3845. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3846. function(fn) { setTimeoutFunc(fn, 1); };
  3847. // Polyfill for Function.prototype.bind
  3848. function bind(fn, thisArg) {
  3849. return function() {
  3850. fn.apply(thisArg, arguments);
  3851. }
  3852. }
  3853. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3854. function Promise(fn) {
  3855. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3856. if (typeof fn !== 'function') throw new TypeError('not a function');
  3857. this._state = null;
  3858. this._value = null;
  3859. this._deferreds = []
  3860. doResolve(fn, bind(resolve, this), bind(reject, this))
  3861. }
  3862. function handle(deferred) {
  3863. var me = this;
  3864. if (this._state === null) {
  3865. this._deferreds.push(deferred);
  3866. return
  3867. }
  3868. asap(function() {
  3869. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3870. if (cb === null) {
  3871. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3872. return;
  3873. }
  3874. var ret;
  3875. try {
  3876. ret = cb(me._value);
  3877. }
  3878. catch (e) {
  3879. deferred.reject(e);
  3880. return;
  3881. }
  3882. deferred.resolve(ret);
  3883. })
  3884. }
  3885. function resolve(newValue) {
  3886. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3887. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3888. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3889. var then = newValue.then;
  3890. if (typeof then === 'function') {
  3891. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3892. return;
  3893. }
  3894. }
  3895. this._state = true;
  3896. this._value = newValue;
  3897. finale.call(this);
  3898. } catch (e) { reject.call(this, e); }
  3899. }
  3900. function reject(newValue) {
  3901. this._state = false;
  3902. this._value = newValue;
  3903. finale.call(this);
  3904. }
  3905. function finale() {
  3906. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3907. handle.call(this, this._deferreds[i]);
  3908. }
  3909. this._deferreds = null;
  3910. }
  3911. function Handler(onFulfilled, onRejected, resolve, reject){
  3912. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3913. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3914. this.resolve = resolve;
  3915. this.reject = reject;
  3916. }
  3917. /**
  3918. * Take a potentially misbehaving resolver function and make sure
  3919. * onFulfilled and onRejected are only called once.
  3920. *
  3921. * Makes no guarantees about asynchrony.
  3922. */
  3923. function doResolve(fn, onFulfilled, onRejected) {
  3924. var done = false;
  3925. try {
  3926. fn(function (value) {
  3927. if (done) return;
  3928. done = true;
  3929. onFulfilled(value);
  3930. }, function (reason) {
  3931. if (done) return;
  3932. done = true;
  3933. onRejected(reason);
  3934. })
  3935. } catch (ex) {
  3936. if (done) return;
  3937. done = true;
  3938. onRejected(ex);
  3939. }
  3940. }
  3941. Promise.prototype['catch'] = function (onRejected) {
  3942. return this.then(null, onRejected);
  3943. };
  3944. Promise.prototype.then = function(onFulfilled, onRejected) {
  3945. var me = this;
  3946. return new Promise(function(resolve, reject) {
  3947. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3948. })
  3949. };
  3950. Promise.all = function () {
  3951. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3952. return new Promise(function (resolve, reject) {
  3953. if (args.length === 0) return resolve([]);
  3954. var remaining = args.length;
  3955. function res(i, val) {
  3956. try {
  3957. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3958. var then = val.then;
  3959. if (typeof then === 'function') {
  3960. then.call(val, function (val) { res(i, val) }, reject);
  3961. return;
  3962. }
  3963. }
  3964. args[i] = val;
  3965. if (--remaining === 0) {
  3966. resolve(args);
  3967. }
  3968. } catch (ex) {
  3969. reject(ex);
  3970. }
  3971. }
  3972. for (var i = 0; i < args.length; i++) {
  3973. res(i, args[i]);
  3974. }
  3975. });
  3976. };
  3977. Promise.resolve = function (value) {
  3978. if (value && typeof value === 'object' && value.constructor === Promise) {
  3979. return value;
  3980. }
  3981. return new Promise(function (resolve) {
  3982. resolve(value);
  3983. });
  3984. };
  3985. Promise.reject = function (value) {
  3986. return new Promise(function (resolve, reject) {
  3987. reject(value);
  3988. });
  3989. };
  3990. Promise.race = function (values) {
  3991. return new Promise(function (resolve, reject) {
  3992. for(var i = 0, len = values.length; i < len; i++) {
  3993. values[i].then(resolve, reject);
  3994. }
  3995. });
  3996. };
  3997. /**
  3998. * Set the immediate function to execute callbacks
  3999. * @param fn {function} Function to execute
  4000. * @private
  4001. */
  4002. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4003. asap = fn;
  4004. };
  4005. if (typeof module !== 'undefined' && module.exports) {
  4006. module.exports = Promise;
  4007. } else if (!root.Promise) {
  4008. root.Promise = Promise;
  4009. }
  4010. })(this);
  4011. },{}],35:[function(_dereq_,module,exports){
  4012. var dtype = _dereq_('dtype')
  4013. var anArray = _dereq_('an-array')
  4014. var isBuffer = _dereq_('is-buffer')
  4015. var CW = [0, 2, 3]
  4016. var CCW = [2, 1, 3]
  4017. module.exports = function createQuadElements(array, opt) {
  4018. //if user didn't specify an output array
  4019. if (!array || !(anArray(array) || isBuffer(array))) {
  4020. opt = array || {}
  4021. array = null
  4022. }
  4023. if (typeof opt === 'number') //backwards-compatible
  4024. opt = { count: opt }
  4025. else
  4026. opt = opt || {}
  4027. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4028. var count = typeof opt.count === 'number' ? opt.count : 1
  4029. var start = (opt.start || 0)
  4030. var dir = opt.clockwise !== false ? CW : CCW,
  4031. a = dir[0],
  4032. b = dir[1],
  4033. c = dir[2]
  4034. var numIndices = count * 6
  4035. var indices = array || new (dtype(type))(numIndices)
  4036. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4037. var x = i + start
  4038. indices[x + 0] = j + 0
  4039. indices[x + 1] = j + 1
  4040. indices[x + 2] = j + 2
  4041. indices[x + 3] = j + a
  4042. indices[x + 4] = j + b
  4043. indices[x + 5] = j + c
  4044. }
  4045. return indices
  4046. }
  4047. },{"an-array":2,"dtype":12,"is-buffer":19}],36:[function(_dereq_,module,exports){
  4048. /*:: type Attr = { [key: string]: string } */
  4049. /*
  4050. style-attr
  4051. ====
  4052. Very simple parsing and stringifying of style attributes.
  4053. `parse`
  4054. ----
  4055. Convert a style attribute string to an object.
  4056. */
  4057. /*:: declare function parse (raw: string): Attr */
  4058. function parse(raw) {
  4059. var trim = function (s) {
  4060. return s.trim();
  4061. };
  4062. var obj = {};
  4063. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  4064. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  4065. var pos = item.indexOf(':');
  4066. var key = item.substr(0, pos).trim();
  4067. var val = item.substr(pos + 1).trim();
  4068. obj[key] = val;
  4069. });
  4070. return obj;
  4071. }
  4072. /*
  4073. `getKeyValueChunks`
  4074. ----
  4075. Split a string into chunks matching `<key>: <value>`
  4076. */
  4077. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  4078. function getKeyValueChunks(raw) {
  4079. var chunks = [];
  4080. var offset = 0;
  4081. var sep = ';';
  4082. var hasUnclosedUrl = /url\([^\)]+$/;
  4083. var chunk = '';
  4084. var nextSplit;
  4085. while (offset < raw.length) {
  4086. nextSplit = raw.indexOf(sep, offset);
  4087. if (nextSplit === -1) {
  4088. nextSplit = raw.length;
  4089. }
  4090. chunk += raw.substring(offset, nextSplit);
  4091. // data URIs can contain semicolons, so make sure we get the whole thing
  4092. if (hasUnclosedUrl.test(chunk)) {
  4093. chunk += ';';
  4094. offset = nextSplit + 1;
  4095. continue;
  4096. }
  4097. chunks.push(chunk);
  4098. chunk = '';
  4099. offset = nextSplit + 1;
  4100. }
  4101. return chunks;
  4102. }
  4103. /*
  4104. `stringify`
  4105. ----
  4106. Convert an object into an attribute string
  4107. */
  4108. /*:: declare function stringify (obj: Attr): string */
  4109. function stringify(obj) {
  4110. return Object.keys(obj).map(function (key) {
  4111. return key + ':' + obj[key];
  4112. }).join(';');
  4113. }
  4114. /*
  4115. `normalize`
  4116. ----
  4117. Normalize an attribute string (eg. collapse duplicates)
  4118. */
  4119. /*:: declare function normalize (str: string): string */
  4120. function normalize(str) {
  4121. return stringify(parse(str));
  4122. }
  4123. module.exports.parse = parse;
  4124. module.exports.stringify = stringify;
  4125. module.exports.normalize = normalize;
  4126. },{}],37:[function(_dereq_,module,exports){
  4127. var createLayout = _dereq_('layout-bmfont-text')
  4128. var inherits = _dereq_('inherits')
  4129. var createIndices = _dereq_('quad-indices')
  4130. var buffer = _dereq_('three-buffer-vertex-data')
  4131. var assign = _dereq_('object-assign')
  4132. var vertices = _dereq_('./lib/vertices')
  4133. var utils = _dereq_('./lib/utils')
  4134. var Base = THREE.BufferGeometry
  4135. module.exports = function createTextGeometry (opt) {
  4136. return new TextGeometry(opt)
  4137. }
  4138. function TextGeometry (opt) {
  4139. Base.call(this)
  4140. if (typeof opt === 'string') {
  4141. opt = { text: opt }
  4142. }
  4143. // use these as default values for any subsequent
  4144. // calls to update()
  4145. this._opt = assign({}, opt)
  4146. // also do an initial setup...
  4147. if (opt) this.update(opt)
  4148. }
  4149. inherits(TextGeometry, Base)
  4150. TextGeometry.prototype.update = function (opt) {
  4151. if (typeof opt === 'string') {
  4152. opt = { text: opt }
  4153. }
  4154. // use constructor defaults
  4155. opt = assign({}, this._opt, opt)
  4156. if (!opt.font) {
  4157. throw new TypeError('must specify a { font } in options')
  4158. }
  4159. this.layout = createLayout(opt)
  4160. // get vec2 texcoords
  4161. var flipY = opt.flipY !== false
  4162. // the desired BMFont data
  4163. var font = opt.font
  4164. // determine texture size from font file
  4165. var texWidth = font.common.scaleW
  4166. var texHeight = font.common.scaleH
  4167. // get visible glyphs
  4168. var glyphs = this.layout.glyphs.filter(function (glyph) {
  4169. var bitmap = glyph.data
  4170. return bitmap.width * bitmap.height > 0
  4171. })
  4172. // provide visible glyphs for convenience
  4173. this.visibleGlyphs = glyphs
  4174. // get common vertex data
  4175. var positions = vertices.positions(glyphs)
  4176. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  4177. var indices = createIndices({
  4178. clockwise: true,
  4179. type: 'uint16',
  4180. count: glyphs.length
  4181. })
  4182. // update vertex data
  4183. buffer.index(this, indices, 1, 'uint16')
  4184. buffer.attr(this, 'position', positions, 2)
  4185. buffer.attr(this, 'uv', uvs, 2)
  4186. // update multipage data
  4187. if (!opt.multipage && 'page' in this.attributes) {
  4188. // disable multipage rendering
  4189. this.removeAttribute('page')
  4190. } else if (opt.multipage) {
  4191. var pages = vertices.pages(glyphs)
  4192. // enable multipage rendering
  4193. buffer.attr(this, 'page', pages, 1)
  4194. }
  4195. }
  4196. TextGeometry.prototype.computeBoundingSphere = function () {
  4197. if (this.boundingSphere === null) {
  4198. this.boundingSphere = new THREE.Sphere()
  4199. }
  4200. var positions = this.attributes.position.array
  4201. var itemSize = this.attributes.position.itemSize
  4202. if (!positions || !itemSize || positions.length < 2) {
  4203. this.boundingSphere.radius = 0
  4204. this.boundingSphere.center.set(0, 0, 0)
  4205. return
  4206. }
  4207. utils.computeSphere(positions, this.boundingSphere)
  4208. if (isNaN(this.boundingSphere.radius)) {
  4209. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  4210. 'Computed radius is NaN. The ' +
  4211. '"position" attribute is likely to have NaN values.')
  4212. }
  4213. }
  4214. TextGeometry.prototype.computeBoundingBox = function () {
  4215. if (this.boundingBox === null) {
  4216. this.boundingBox = new THREE.Box3()
  4217. }
  4218. var bbox = this.boundingBox
  4219. var positions = this.attributes.position.array
  4220. var itemSize = this.attributes.position.itemSize
  4221. if (!positions || !itemSize || positions.length < 2) {
  4222. bbox.makeEmpty()
  4223. return
  4224. }
  4225. utils.computeBox(positions, bbox)
  4226. }
  4227. },{"./lib/utils":38,"./lib/vertices":39,"inherits":18,"layout-bmfont-text":23,"object-assign":26,"quad-indices":35,"three-buffer-vertex-data":40}],38:[function(_dereq_,module,exports){
  4228. var itemSize = 2
  4229. var box = { min: [0, 0], max: [0, 0] }
  4230. function bounds (positions) {
  4231. var count = positions.length / itemSize
  4232. box.min[0] = positions[0]
  4233. box.min[1] = positions[1]
  4234. box.max[0] = positions[0]
  4235. box.max[1] = positions[1]
  4236. for (var i = 0; i < count; i++) {
  4237. var x = positions[i * itemSize + 0]
  4238. var y = positions[i * itemSize + 1]
  4239. box.min[0] = Math.min(x, box.min[0])
  4240. box.min[1] = Math.min(y, box.min[1])
  4241. box.max[0] = Math.max(x, box.max[0])
  4242. box.max[1] = Math.max(y, box.max[1])
  4243. }
  4244. }
  4245. module.exports.computeBox = function (positions, output) {
  4246. bounds(positions)
  4247. output.min.set(box.min[0], box.min[1], 0)
  4248. output.max.set(box.max[0], box.max[1], 0)
  4249. }
  4250. module.exports.computeSphere = function (positions, output) {
  4251. bounds(positions)
  4252. var minX = box.min[0]
  4253. var minY = box.min[1]
  4254. var maxX = box.max[0]
  4255. var maxY = box.max[1]
  4256. var width = maxX - minX
  4257. var height = maxY - minY
  4258. var length = Math.sqrt(width * width + height * height)
  4259. output.center.set(minX + width / 2, minY + height / 2, 0)
  4260. output.radius = length / 2
  4261. }
  4262. },{}],39:[function(_dereq_,module,exports){
  4263. module.exports.pages = function pages (glyphs) {
  4264. var pages = new Float32Array(glyphs.length * 4 * 1)
  4265. var i = 0
  4266. glyphs.forEach(function (glyph) {
  4267. var id = glyph.data.page || 0
  4268. pages[i++] = id
  4269. pages[i++] = id
  4270. pages[i++] = id
  4271. pages[i++] = id
  4272. })
  4273. return pages
  4274. }
  4275. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  4276. var uvs = new Float32Array(glyphs.length * 4 * 2)
  4277. var i = 0
  4278. glyphs.forEach(function (glyph) {
  4279. var bitmap = glyph.data
  4280. var bw = (bitmap.x + bitmap.width)
  4281. var bh = (bitmap.y + bitmap.height)
  4282. // top left position
  4283. var u0 = bitmap.x / texWidth
  4284. var v1 = bitmap.y / texHeight
  4285. var u1 = bw / texWidth
  4286. var v0 = bh / texHeight
  4287. if (flipY) {
  4288. v1 = (texHeight - bitmap.y) / texHeight
  4289. v0 = (texHeight - bh) / texHeight
  4290. }
  4291. // BL
  4292. uvs[i++] = u0
  4293. uvs[i++] = v1
  4294. // TL
  4295. uvs[i++] = u0
  4296. uvs[i++] = v0
  4297. // TR
  4298. uvs[i++] = u1
  4299. uvs[i++] = v0
  4300. // BR
  4301. uvs[i++] = u1
  4302. uvs[i++] = v1
  4303. })
  4304. return uvs
  4305. }
  4306. module.exports.positions = function positions (glyphs) {
  4307. var positions = new Float32Array(glyphs.length * 4 * 2)
  4308. var i = 0
  4309. glyphs.forEach(function (glyph) {
  4310. var bitmap = glyph.data
  4311. // bottom left position
  4312. var x = glyph.position[0] + bitmap.xoffset
  4313. var y = glyph.position[1] + bitmap.yoffset
  4314. // quad size
  4315. var w = bitmap.width
  4316. var h = bitmap.height
  4317. // BL
  4318. positions[i++] = x
  4319. positions[i++] = y
  4320. // TL
  4321. positions[i++] = x
  4322. positions[i++] = y + h
  4323. // TR
  4324. positions[i++] = x + w
  4325. positions[i++] = y + h
  4326. // BR
  4327. positions[i++] = x + w
  4328. positions[i++] = y
  4329. })
  4330. return positions
  4331. }
  4332. },{}],40:[function(_dereq_,module,exports){
  4333. var flatten = _dereq_('flatten-vertex-data')
  4334. var warned = false;
  4335. module.exports.attr = setAttribute
  4336. module.exports.index = setIndex
  4337. function setIndex (geometry, data, itemSize, dtype) {
  4338. if (typeof itemSize !== 'number') itemSize = 1
  4339. if (typeof dtype !== 'string') dtype = 'uint16'
  4340. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  4341. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  4342. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4343. if (newAttrib) {
  4344. if (isR69) geometry.addAttribute('index', newAttrib)
  4345. else geometry.index = newAttrib
  4346. }
  4347. }
  4348. function setAttribute (geometry, key, data, itemSize, dtype) {
  4349. if (typeof itemSize !== 'number') itemSize = 3
  4350. if (typeof dtype !== 'string') dtype = 'float32'
  4351. if (Array.isArray(data) &&
  4352. Array.isArray(data[0]) &&
  4353. data[0].length !== itemSize) {
  4354. throw new Error('Nested vertex array has unexpected size; expected ' +
  4355. itemSize + ' but found ' + data[0].length)
  4356. }
  4357. var attrib = geometry.getAttribute(key)
  4358. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4359. if (newAttrib) {
  4360. geometry.addAttribute(key, newAttrib)
  4361. }
  4362. }
  4363. function updateAttribute (attrib, data, itemSize, dtype) {
  4364. data = data || []
  4365. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  4366. // create a new array with desired type
  4367. data = flatten(data, dtype)
  4368. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  4369. if (!attrib || needsNewBuffer) {
  4370. // We are on an old version of ThreeJS which can't
  4371. // support growing / shrinking buffers, so we need
  4372. // to build a new buffer
  4373. if (needsNewBuffer && !warned) {
  4374. warned = true
  4375. console.warn([
  4376. 'A WebGL buffer is being updated with a new size or itemSize, ',
  4377. 'however this version of ThreeJS only supports fixed-size buffers.',
  4378. '\nThe old buffer may still be kept in memory.\n',
  4379. 'To avoid memory leaks, it is recommended that you dispose ',
  4380. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  4381. 'See here for discussion:\n',
  4382. 'https://github.com/mrdoob/three.js/pull/9631'
  4383. ].join(''))
  4384. }
  4385. // Build a new attribute
  4386. attrib = new THREE.BufferAttribute(data, itemSize);
  4387. }
  4388. attrib.itemSize = itemSize
  4389. attrib.needsUpdate = true
  4390. // New versions of ThreeJS suggest using setArray
  4391. // to change the data. It will use bufferData internally,
  4392. // so you can change the array size without any issues
  4393. if (typeof attrib.setArray === 'function') {
  4394. attrib.setArray(data)
  4395. }
  4396. return attrib
  4397. } else {
  4398. // copy data into the existing array
  4399. flatten(data, attrib.array)
  4400. attrib.needsUpdate = true
  4401. return null
  4402. }
  4403. }
  4404. // Test whether the attribute needs to be re-created,
  4405. // returns false if we can re-use it as-is.
  4406. function rebuildAttribute (attrib, data, itemSize) {
  4407. if (attrib.itemSize !== itemSize) return true
  4408. if (!attrib.array) return true
  4409. var attribLength = attrib.array.length
  4410. if (Array.isArray(data) && Array.isArray(data[0])) {
  4411. // [ [ x, y, z ] ]
  4412. return attribLength !== data.length * itemSize
  4413. } else {
  4414. // [ x, y, z ]
  4415. return attribLength !== data.length
  4416. }
  4417. return false
  4418. }
  4419. },{"flatten-vertex-data":13}],41:[function(_dereq_,module,exports){
  4420. (function (global, factory) {
  4421. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4422. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4423. (factory((global.THREE = global.THREE || {})));
  4424. }(this, (function (exports) { 'use strict';
  4425. // Polyfills
  4426. if ( Number.EPSILON === undefined ) {
  4427. Number.EPSILON = Math.pow( 2, - 52 );
  4428. }
  4429. if ( Number.isInteger === undefined ) {
  4430. // Missing in IE
  4431. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  4432. Number.isInteger = function ( value ) {
  4433. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  4434. };
  4435. }
  4436. //
  4437. if ( Math.sign === undefined ) {
  4438. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4439. Math.sign = function ( x ) {
  4440. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4441. };
  4442. }
  4443. if ( Function.prototype.name === undefined ) {
  4444. // Missing in IE
  4445. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4446. Object.defineProperty( Function.prototype, 'name', {
  4447. get: function () {
  4448. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4449. }
  4450. } );
  4451. }
  4452. if ( Object.assign === undefined ) {
  4453. // Missing in IE
  4454. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4455. ( function () {
  4456. Object.assign = function ( target ) {
  4457. 'use strict';
  4458. if ( target === undefined || target === null ) {
  4459. throw new TypeError( 'Cannot convert undefined or null to object' );
  4460. }
  4461. var output = Object( target );
  4462. for ( var index = 1; index < arguments.length; index ++ ) {
  4463. var source = arguments[ index ];
  4464. if ( source !== undefined && source !== null ) {
  4465. for ( var nextKey in source ) {
  4466. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4467. output[ nextKey ] = source[ nextKey ];
  4468. }
  4469. }
  4470. }
  4471. }
  4472. return output;
  4473. };
  4474. } )();
  4475. }
  4476. /**
  4477. * https://github.com/mrdoob/eventdispatcher.js/
  4478. */
  4479. function EventDispatcher() {}
  4480. Object.assign( EventDispatcher.prototype, {
  4481. addEventListener: function ( type, listener ) {
  4482. if ( this._listeners === undefined ) this._listeners = {};
  4483. var listeners = this._listeners;
  4484. if ( listeners[ type ] === undefined ) {
  4485. listeners[ type ] = [];
  4486. }
  4487. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4488. listeners[ type ].push( listener );
  4489. }
  4490. },
  4491. hasEventListener: function ( type, listener ) {
  4492. if ( this._listeners === undefined ) return false;
  4493. var listeners = this._listeners;
  4494. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4495. },
  4496. removeEventListener: function ( type, listener ) {
  4497. if ( this._listeners === undefined ) return;
  4498. var listeners = this._listeners;
  4499. var listenerArray = listeners[ type ];
  4500. if ( listenerArray !== undefined ) {
  4501. var index = listenerArray.indexOf( listener );
  4502. if ( index !== - 1 ) {
  4503. listenerArray.splice( index, 1 );
  4504. }
  4505. }
  4506. },
  4507. dispatchEvent: function ( event ) {
  4508. if ( this._listeners === undefined ) return;
  4509. var listeners = this._listeners;
  4510. var listenerArray = listeners[ event.type ];
  4511. if ( listenerArray !== undefined ) {
  4512. event.target = this;
  4513. var array = listenerArray.slice( 0 );
  4514. for ( var i = 0, l = array.length; i < l; i ++ ) {
  4515. array[ i ].call( this, event );
  4516. }
  4517. }
  4518. }
  4519. } );
  4520. var REVISION = '87';
  4521. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4522. var CullFaceNone = 0;
  4523. var CullFaceBack = 1;
  4524. var CullFaceFront = 2;
  4525. var CullFaceFrontBack = 3;
  4526. var FrontFaceDirectionCW = 0;
  4527. var FrontFaceDirectionCCW = 1;
  4528. var BasicShadowMap = 0;
  4529. var PCFShadowMap = 1;
  4530. var PCFSoftShadowMap = 2;
  4531. var FrontSide = 0;
  4532. var BackSide = 1;
  4533. var DoubleSide = 2;
  4534. var FlatShading = 1;
  4535. var SmoothShading = 2;
  4536. var NoColors = 0;
  4537. var FaceColors = 1;
  4538. var VertexColors = 2;
  4539. var NoBlending = 0;
  4540. var NormalBlending = 1;
  4541. var AdditiveBlending = 2;
  4542. var SubtractiveBlending = 3;
  4543. var MultiplyBlending = 4;
  4544. var CustomBlending = 5;
  4545. var AddEquation = 100;
  4546. var SubtractEquation = 101;
  4547. var ReverseSubtractEquation = 102;
  4548. var MinEquation = 103;
  4549. var MaxEquation = 104;
  4550. var ZeroFactor = 200;
  4551. var OneFactor = 201;
  4552. var SrcColorFactor = 202;
  4553. var OneMinusSrcColorFactor = 203;
  4554. var SrcAlphaFactor = 204;
  4555. var OneMinusSrcAlphaFactor = 205;
  4556. var DstAlphaFactor = 206;
  4557. var OneMinusDstAlphaFactor = 207;
  4558. var DstColorFactor = 208;
  4559. var OneMinusDstColorFactor = 209;
  4560. var SrcAlphaSaturateFactor = 210;
  4561. var NeverDepth = 0;
  4562. var AlwaysDepth = 1;
  4563. var LessDepth = 2;
  4564. var LessEqualDepth = 3;
  4565. var EqualDepth = 4;
  4566. var GreaterEqualDepth = 5;
  4567. var GreaterDepth = 6;
  4568. var NotEqualDepth = 7;
  4569. var MultiplyOperation = 0;
  4570. var MixOperation = 1;
  4571. var AddOperation = 2;
  4572. var NoToneMapping = 0;
  4573. var LinearToneMapping = 1;
  4574. var ReinhardToneMapping = 2;
  4575. var Uncharted2ToneMapping = 3;
  4576. var CineonToneMapping = 4;
  4577. var UVMapping = 300;
  4578. var CubeReflectionMapping = 301;
  4579. var CubeRefractionMapping = 302;
  4580. var EquirectangularReflectionMapping = 303;
  4581. var EquirectangularRefractionMapping = 304;
  4582. var SphericalReflectionMapping = 305;
  4583. var CubeUVReflectionMapping = 306;
  4584. var CubeUVRefractionMapping = 307;
  4585. var RepeatWrapping = 1000;
  4586. var ClampToEdgeWrapping = 1001;
  4587. var MirroredRepeatWrapping = 1002;
  4588. var NearestFilter = 1003;
  4589. var NearestMipMapNearestFilter = 1004;
  4590. var NearestMipMapLinearFilter = 1005;
  4591. var LinearFilter = 1006;
  4592. var LinearMipMapNearestFilter = 1007;
  4593. var LinearMipMapLinearFilter = 1008;
  4594. var UnsignedByteType = 1009;
  4595. var ByteType = 1010;
  4596. var ShortType = 1011;
  4597. var UnsignedShortType = 1012;
  4598. var IntType = 1013;
  4599. var UnsignedIntType = 1014;
  4600. var FloatType = 1015;
  4601. var HalfFloatType = 1016;
  4602. var UnsignedShort4444Type = 1017;
  4603. var UnsignedShort5551Type = 1018;
  4604. var UnsignedShort565Type = 1019;
  4605. var UnsignedInt248Type = 1020;
  4606. var AlphaFormat = 1021;
  4607. var RGBFormat = 1022;
  4608. var RGBAFormat = 1023;
  4609. var LuminanceFormat = 1024;
  4610. var LuminanceAlphaFormat = 1025;
  4611. var RGBEFormat = RGBAFormat;
  4612. var DepthFormat = 1026;
  4613. var DepthStencilFormat = 1027;
  4614. var RGB_S3TC_DXT1_Format = 2001;
  4615. var RGBA_S3TC_DXT1_Format = 2002;
  4616. var RGBA_S3TC_DXT3_Format = 2003;
  4617. var RGBA_S3TC_DXT5_Format = 2004;
  4618. var RGB_PVRTC_4BPPV1_Format = 2100;
  4619. var RGB_PVRTC_2BPPV1_Format = 2101;
  4620. var RGBA_PVRTC_4BPPV1_Format = 2102;
  4621. var RGBA_PVRTC_2BPPV1_Format = 2103;
  4622. var RGB_ETC1_Format = 2151;
  4623. var LoopOnce = 2200;
  4624. var LoopRepeat = 2201;
  4625. var LoopPingPong = 2202;
  4626. var InterpolateDiscrete = 2300;
  4627. var InterpolateLinear = 2301;
  4628. var InterpolateSmooth = 2302;
  4629. var ZeroCurvatureEnding = 2400;
  4630. var ZeroSlopeEnding = 2401;
  4631. var WrapAroundEnding = 2402;
  4632. var TrianglesDrawMode = 0;
  4633. var TriangleStripDrawMode = 1;
  4634. var TriangleFanDrawMode = 2;
  4635. var LinearEncoding = 3000;
  4636. var sRGBEncoding = 3001;
  4637. var GammaEncoding = 3007;
  4638. var RGBEEncoding = 3002;
  4639. var LogLuvEncoding = 3003;
  4640. var RGBM7Encoding = 3004;
  4641. var RGBM16Encoding = 3005;
  4642. var RGBDEncoding = 3006;
  4643. var BasicDepthPacking = 3200;
  4644. var RGBADepthPacking = 3201;
  4645. /**
  4646. * @author alteredq / http://alteredqualia.com/
  4647. * @author mrdoob / http://mrdoob.com/
  4648. */
  4649. var _Math = {
  4650. DEG2RAD: Math.PI / 180,
  4651. RAD2DEG: 180 / Math.PI,
  4652. generateUUID: function () {
  4653. // http://www.broofa.com/Tools/Math.uuid.htm
  4654. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4655. var uuid = new Array( 36 );
  4656. var rnd = 0, r;
  4657. return function generateUUID() {
  4658. for ( var i = 0; i < 36; i ++ ) {
  4659. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4660. uuid[ i ] = '-';
  4661. } else if ( i === 14 ) {
  4662. uuid[ i ] = '4';
  4663. } else {
  4664. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4665. r = rnd & 0xf;
  4666. rnd = rnd >> 4;
  4667. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4668. }
  4669. }
  4670. return uuid.join( '' );
  4671. };
  4672. }(),
  4673. clamp: function ( value, min, max ) {
  4674. return Math.max( min, Math.min( max, value ) );
  4675. },
  4676. // compute euclidian modulo of m % n
  4677. // https://en.wikipedia.org/wiki/Modulo_operation
  4678. euclideanModulo: function ( n, m ) {
  4679. return ( ( n % m ) + m ) % m;
  4680. },
  4681. // Linear mapping from range <a1, a2> to range <b1, b2>
  4682. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4683. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4684. },
  4685. // https://en.wikipedia.org/wiki/Linear_interpolation
  4686. lerp: function ( x, y, t ) {
  4687. return ( 1 - t ) * x + t * y;
  4688. },
  4689. // http://en.wikipedia.org/wiki/Smoothstep
  4690. smoothstep: function ( x, min, max ) {
  4691. if ( x <= min ) return 0;
  4692. if ( x >= max ) return 1;
  4693. x = ( x - min ) / ( max - min );
  4694. return x * x * ( 3 - 2 * x );
  4695. },
  4696. smootherstep: function ( x, min, max ) {
  4697. if ( x <= min ) return 0;
  4698. if ( x >= max ) return 1;
  4699. x = ( x - min ) / ( max - min );
  4700. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4701. },
  4702. // Random integer from <low, high> interval
  4703. randInt: function ( low, high ) {
  4704. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4705. },
  4706. // Random float from <low, high> interval
  4707. randFloat: function ( low, high ) {
  4708. return low + Math.random() * ( high - low );
  4709. },
  4710. // Random float from <-range/2, range/2> interval
  4711. randFloatSpread: function ( range ) {
  4712. return range * ( 0.5 - Math.random() );
  4713. },
  4714. degToRad: function ( degrees ) {
  4715. return degrees * _Math.DEG2RAD;
  4716. },
  4717. radToDeg: function ( radians ) {
  4718. return radians * _Math.RAD2DEG;
  4719. },
  4720. isPowerOfTwo: function ( value ) {
  4721. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4722. },
  4723. nearestPowerOfTwo: function ( value ) {
  4724. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4725. },
  4726. nextPowerOfTwo: function ( value ) {
  4727. value --;
  4728. value |= value >> 1;
  4729. value |= value >> 2;
  4730. value |= value >> 4;
  4731. value |= value >> 8;
  4732. value |= value >> 16;
  4733. value ++;
  4734. return value;
  4735. }
  4736. };
  4737. /**
  4738. * @author mrdoob / http://mrdoob.com/
  4739. * @author philogb / http://blog.thejit.org/
  4740. * @author egraether / http://egraether.com/
  4741. * @author zz85 / http://www.lab4games.net/zz85/blog
  4742. */
  4743. function Vector2( x, y ) {
  4744. this.x = x || 0;
  4745. this.y = y || 0;
  4746. }
  4747. Object.defineProperties( Vector2.prototype, {
  4748. "width" : {
  4749. get: function () {
  4750. return this.x;
  4751. },
  4752. set: function ( value ) {
  4753. this.x = value;
  4754. }
  4755. },
  4756. "height" : {
  4757. get: function () {
  4758. return this.y;
  4759. },
  4760. set: function ( value ) {
  4761. this.y = value;
  4762. }
  4763. }
  4764. } );
  4765. Object.assign( Vector2.prototype, {
  4766. isVector2: true,
  4767. set: function ( x, y ) {
  4768. this.x = x;
  4769. this.y = y;
  4770. return this;
  4771. },
  4772. setScalar: function ( scalar ) {
  4773. this.x = scalar;
  4774. this.y = scalar;
  4775. return this;
  4776. },
  4777. setX: function ( x ) {
  4778. this.x = x;
  4779. return this;
  4780. },
  4781. setY: function ( y ) {
  4782. this.y = y;
  4783. return this;
  4784. },
  4785. setComponent: function ( index, value ) {
  4786. switch ( index ) {
  4787. case 0: this.x = value; break;
  4788. case 1: this.y = value; break;
  4789. default: throw new Error( 'index is out of range: ' + index );
  4790. }
  4791. return this;
  4792. },
  4793. getComponent: function ( index ) {
  4794. switch ( index ) {
  4795. case 0: return this.x;
  4796. case 1: return this.y;
  4797. default: throw new Error( 'index is out of range: ' + index );
  4798. }
  4799. },
  4800. clone: function () {
  4801. return new this.constructor( this.x, this.y );
  4802. },
  4803. copy: function ( v ) {
  4804. this.x = v.x;
  4805. this.y = v.y;
  4806. return this;
  4807. },
  4808. add: function ( v, w ) {
  4809. if ( w !== undefined ) {
  4810. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4811. return this.addVectors( v, w );
  4812. }
  4813. this.x += v.x;
  4814. this.y += v.y;
  4815. return this;
  4816. },
  4817. addScalar: function ( s ) {
  4818. this.x += s;
  4819. this.y += s;
  4820. return this;
  4821. },
  4822. addVectors: function ( a, b ) {
  4823. this.x = a.x + b.x;
  4824. this.y = a.y + b.y;
  4825. return this;
  4826. },
  4827. addScaledVector: function ( v, s ) {
  4828. this.x += v.x * s;
  4829. this.y += v.y * s;
  4830. return this;
  4831. },
  4832. sub: function ( v, w ) {
  4833. if ( w !== undefined ) {
  4834. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4835. return this.subVectors( v, w );
  4836. }
  4837. this.x -= v.x;
  4838. this.y -= v.y;
  4839. return this;
  4840. },
  4841. subScalar: function ( s ) {
  4842. this.x -= s;
  4843. this.y -= s;
  4844. return this;
  4845. },
  4846. subVectors: function ( a, b ) {
  4847. this.x = a.x - b.x;
  4848. this.y = a.y - b.y;
  4849. return this;
  4850. },
  4851. multiply: function ( v ) {
  4852. this.x *= v.x;
  4853. this.y *= v.y;
  4854. return this;
  4855. },
  4856. multiplyScalar: function ( scalar ) {
  4857. this.x *= scalar;
  4858. this.y *= scalar;
  4859. return this;
  4860. },
  4861. divide: function ( v ) {
  4862. this.x /= v.x;
  4863. this.y /= v.y;
  4864. return this;
  4865. },
  4866. divideScalar: function ( scalar ) {
  4867. return this.multiplyScalar( 1 / scalar );
  4868. },
  4869. min: function ( v ) {
  4870. this.x = Math.min( this.x, v.x );
  4871. this.y = Math.min( this.y, v.y );
  4872. return this;
  4873. },
  4874. max: function ( v ) {
  4875. this.x = Math.max( this.x, v.x );
  4876. this.y = Math.max( this.y, v.y );
  4877. return this;
  4878. },
  4879. clamp: function ( min, max ) {
  4880. // assumes min < max, componentwise
  4881. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4882. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4883. return this;
  4884. },
  4885. clampScalar: function () {
  4886. var min = new Vector2();
  4887. var max = new Vector2();
  4888. return function clampScalar( minVal, maxVal ) {
  4889. min.set( minVal, minVal );
  4890. max.set( maxVal, maxVal );
  4891. return this.clamp( min, max );
  4892. };
  4893. }(),
  4894. clampLength: function ( min, max ) {
  4895. var length = this.length();
  4896. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  4897. },
  4898. floor: function () {
  4899. this.x = Math.floor( this.x );
  4900. this.y = Math.floor( this.y );
  4901. return this;
  4902. },
  4903. ceil: function () {
  4904. this.x = Math.ceil( this.x );
  4905. this.y = Math.ceil( this.y );
  4906. return this;
  4907. },
  4908. round: function () {
  4909. this.x = Math.round( this.x );
  4910. this.y = Math.round( this.y );
  4911. return this;
  4912. },
  4913. roundToZero: function () {
  4914. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4915. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4916. return this;
  4917. },
  4918. negate: function () {
  4919. this.x = - this.x;
  4920. this.y = - this.y;
  4921. return this;
  4922. },
  4923. dot: function ( v ) {
  4924. return this.x * v.x + this.y * v.y;
  4925. },
  4926. lengthSq: function () {
  4927. return this.x * this.x + this.y * this.y;
  4928. },
  4929. length: function () {
  4930. return Math.sqrt( this.x * this.x + this.y * this.y );
  4931. },
  4932. lengthManhattan: function() {
  4933. return Math.abs( this.x ) + Math.abs( this.y );
  4934. },
  4935. normalize: function () {
  4936. return this.divideScalar( this.length() || 1 );
  4937. },
  4938. angle: function () {
  4939. // computes the angle in radians with respect to the positive x-axis
  4940. var angle = Math.atan2( this.y, this.x );
  4941. if ( angle < 0 ) angle += 2 * Math.PI;
  4942. return angle;
  4943. },
  4944. distanceTo: function ( v ) {
  4945. return Math.sqrt( this.distanceToSquared( v ) );
  4946. },
  4947. distanceToSquared: function ( v ) {
  4948. var dx = this.x - v.x, dy = this.y - v.y;
  4949. return dx * dx + dy * dy;
  4950. },
  4951. distanceToManhattan: function ( v ) {
  4952. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  4953. },
  4954. setLength: function ( length ) {
  4955. return this.normalize().multiplyScalar( length );
  4956. },
  4957. lerp: function ( v, alpha ) {
  4958. this.x += ( v.x - this.x ) * alpha;
  4959. this.y += ( v.y - this.y ) * alpha;
  4960. return this;
  4961. },
  4962. lerpVectors: function ( v1, v2, alpha ) {
  4963. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  4964. },
  4965. equals: function ( v ) {
  4966. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  4967. },
  4968. fromArray: function ( array, offset ) {
  4969. if ( offset === undefined ) offset = 0;
  4970. this.x = array[ offset ];
  4971. this.y = array[ offset + 1 ];
  4972. return this;
  4973. },
  4974. toArray: function ( array, offset ) {
  4975. if ( array === undefined ) array = [];
  4976. if ( offset === undefined ) offset = 0;
  4977. array[ offset ] = this.x;
  4978. array[ offset + 1 ] = this.y;
  4979. return array;
  4980. },
  4981. fromBufferAttribute: function ( attribute, index, offset ) {
  4982. if ( offset !== undefined ) {
  4983. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  4984. }
  4985. this.x = attribute.getX( index );
  4986. this.y = attribute.getY( index );
  4987. return this;
  4988. },
  4989. rotateAround: function ( center, angle ) {
  4990. var c = Math.cos( angle ), s = Math.sin( angle );
  4991. var x = this.x - center.x;
  4992. var y = this.y - center.y;
  4993. this.x = x * c - y * s + center.x;
  4994. this.y = x * s + y * c + center.y;
  4995. return this;
  4996. }
  4997. } );
  4998. /**
  4999. * @author mrdoob / http://mrdoob.com/
  5000. * @author alteredq / http://alteredqualia.com/
  5001. * @author szimek / https://github.com/szimek/
  5002. */
  5003. var textureId = 0;
  5004. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  5005. Object.defineProperty( this, 'id', { value: textureId ++ } );
  5006. this.uuid = _Math.generateUUID();
  5007. this.name = '';
  5008. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  5009. this.mipmaps = [];
  5010. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  5011. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  5012. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  5013. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  5014. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  5015. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  5016. this.format = format !== undefined ? format : RGBAFormat;
  5017. this.type = type !== undefined ? type : UnsignedByteType;
  5018. this.offset = new Vector2( 0, 0 );
  5019. this.repeat = new Vector2( 1, 1 );
  5020. this.generateMipmaps = true;
  5021. this.premultiplyAlpha = false;
  5022. this.flipY = true;
  5023. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5024. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  5025. //
  5026. // Also changing the encoding after already used by a Material will not automatically make the Material
  5027. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  5028. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  5029. this.version = 0;
  5030. this.onUpdate = null;
  5031. }
  5032. Texture.DEFAULT_IMAGE = undefined;
  5033. Texture.DEFAULT_MAPPING = UVMapping;
  5034. Object.defineProperty( Texture.prototype, "needsUpdate", {
  5035. set: function ( value ) {
  5036. if ( value === true ) this.version ++;
  5037. }
  5038. } );
  5039. Object.assign( Texture.prototype, EventDispatcher.prototype, {
  5040. constructor: Texture,
  5041. isTexture: true,
  5042. clone: function () {
  5043. return new this.constructor().copy( this );
  5044. },
  5045. copy: function ( source ) {
  5046. this.name = source.name;
  5047. this.image = source.image;
  5048. this.mipmaps = source.mipmaps.slice( 0 );
  5049. this.mapping = source.mapping;
  5050. this.wrapS = source.wrapS;
  5051. this.wrapT = source.wrapT;
  5052. this.magFilter = source.magFilter;
  5053. this.minFilter = source.minFilter;
  5054. this.anisotropy = source.anisotropy;
  5055. this.format = source.format;
  5056. this.type = source.type;
  5057. this.offset.copy( source.offset );
  5058. this.repeat.copy( source.repeat );
  5059. this.generateMipmaps = source.generateMipmaps;
  5060. this.premultiplyAlpha = source.premultiplyAlpha;
  5061. this.flipY = source.flipY;
  5062. this.unpackAlignment = source.unpackAlignment;
  5063. this.encoding = source.encoding;
  5064. return this;
  5065. },
  5066. toJSON: function ( meta ) {
  5067. if ( meta.textures[ this.uuid ] !== undefined ) {
  5068. return meta.textures[ this.uuid ];
  5069. }
  5070. function getDataURL( image ) {
  5071. var canvas;
  5072. if ( image instanceof HTMLCanvasElement ) {
  5073. canvas = image;
  5074. } else {
  5075. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  5076. canvas.width = image.width;
  5077. canvas.height = image.height;
  5078. var context = canvas.getContext( '2d' );
  5079. if ( image instanceof ImageData ) {
  5080. context.putImageData( image, 0, 0 );
  5081. } else {
  5082. context.drawImage( image, 0, 0, image.width, image.height );
  5083. }
  5084. }
  5085. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  5086. return canvas.toDataURL( 'image/jpeg', 0.6 );
  5087. } else {
  5088. return canvas.toDataURL( 'image/png' );
  5089. }
  5090. }
  5091. var output = {
  5092. metadata: {
  5093. version: 4.5,
  5094. type: 'Texture',
  5095. generator: 'Texture.toJSON'
  5096. },
  5097. uuid: this.uuid,
  5098. name: this.name,
  5099. mapping: this.mapping,
  5100. repeat: [ this.repeat.x, this.repeat.y ],
  5101. offset: [ this.offset.x, this.offset.y ],
  5102. wrap: [ this.wrapS, this.wrapT ],
  5103. minFilter: this.minFilter,
  5104. magFilter: this.magFilter,
  5105. anisotropy: this.anisotropy,
  5106. flipY: this.flipY
  5107. };
  5108. if ( this.image !== undefined ) {
  5109. // TODO: Move to THREE.Image
  5110. var image = this.image;
  5111. if ( image.uuid === undefined ) {
  5112. image.uuid = _Math.generateUUID(); // UGH
  5113. }
  5114. if ( meta.images[ image.uuid ] === undefined ) {
  5115. meta.images[ image.uuid ] = {
  5116. uuid: image.uuid,
  5117. url: getDataURL( image )
  5118. };
  5119. }
  5120. output.image = image.uuid;
  5121. }
  5122. meta.textures[ this.uuid ] = output;
  5123. return output;
  5124. },
  5125. dispose: function () {
  5126. this.dispatchEvent( { type: 'dispose' } );
  5127. },
  5128. transformUv: function ( uv ) {
  5129. if ( this.mapping !== UVMapping ) return;
  5130. uv.multiply( this.repeat );
  5131. uv.add( this.offset );
  5132. if ( uv.x < 0 || uv.x > 1 ) {
  5133. switch ( this.wrapS ) {
  5134. case RepeatWrapping:
  5135. uv.x = uv.x - Math.floor( uv.x );
  5136. break;
  5137. case ClampToEdgeWrapping:
  5138. uv.x = uv.x < 0 ? 0 : 1;
  5139. break;
  5140. case MirroredRepeatWrapping:
  5141. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5142. uv.x = Math.ceil( uv.x ) - uv.x;
  5143. } else {
  5144. uv.x = uv.x - Math.floor( uv.x );
  5145. }
  5146. break;
  5147. }
  5148. }
  5149. if ( uv.y < 0 || uv.y > 1 ) {
  5150. switch ( this.wrapT ) {
  5151. case RepeatWrapping:
  5152. uv.y = uv.y - Math.floor( uv.y );
  5153. break;
  5154. case ClampToEdgeWrapping:
  5155. uv.y = uv.y < 0 ? 0 : 1;
  5156. break;
  5157. case MirroredRepeatWrapping:
  5158. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5159. uv.y = Math.ceil( uv.y ) - uv.y;
  5160. } else {
  5161. uv.y = uv.y - Math.floor( uv.y );
  5162. }
  5163. break;
  5164. }
  5165. }
  5166. if ( this.flipY ) {
  5167. uv.y = 1 - uv.y;
  5168. }
  5169. }
  5170. } );
  5171. /**
  5172. * @author supereggbert / http://www.paulbrunt.co.uk/
  5173. * @author philogb / http://blog.thejit.org/
  5174. * @author mikael emtinger / http://gomo.se/
  5175. * @author egraether / http://egraether.com/
  5176. * @author WestLangley / http://github.com/WestLangley
  5177. */
  5178. function Vector4( x, y, z, w ) {
  5179. this.x = x || 0;
  5180. this.y = y || 0;
  5181. this.z = z || 0;
  5182. this.w = ( w !== undefined ) ? w : 1;
  5183. }
  5184. Object.assign( Vector4.prototype, {
  5185. isVector4: true,
  5186. set: function ( x, y, z, w ) {
  5187. this.x = x;
  5188. this.y = y;
  5189. this.z = z;
  5190. this.w = w;
  5191. return this;
  5192. },
  5193. setScalar: function ( scalar ) {
  5194. this.x = scalar;
  5195. this.y = scalar;
  5196. this.z = scalar;
  5197. this.w = scalar;
  5198. return this;
  5199. },
  5200. setX: function ( x ) {
  5201. this.x = x;
  5202. return this;
  5203. },
  5204. setY: function ( y ) {
  5205. this.y = y;
  5206. return this;
  5207. },
  5208. setZ: function ( z ) {
  5209. this.z = z;
  5210. return this;
  5211. },
  5212. setW: function ( w ) {
  5213. this.w = w;
  5214. return this;
  5215. },
  5216. setComponent: function ( index, value ) {
  5217. switch ( index ) {
  5218. case 0: this.x = value; break;
  5219. case 1: this.y = value; break;
  5220. case 2: this.z = value; break;
  5221. case 3: this.w = value; break;
  5222. default: throw new Error( 'index is out of range: ' + index );
  5223. }
  5224. return this;
  5225. },
  5226. getComponent: function ( index ) {
  5227. switch ( index ) {
  5228. case 0: return this.x;
  5229. case 1: return this.y;
  5230. case 2: return this.z;
  5231. case 3: return this.w;
  5232. default: throw new Error( 'index is out of range: ' + index );
  5233. }
  5234. },
  5235. clone: function () {
  5236. return new this.constructor( this.x, this.y, this.z, this.w );
  5237. },
  5238. copy: function ( v ) {
  5239. this.x = v.x;
  5240. this.y = v.y;
  5241. this.z = v.z;
  5242. this.w = ( v.w !== undefined ) ? v.w : 1;
  5243. return this;
  5244. },
  5245. add: function ( v, w ) {
  5246. if ( w !== undefined ) {
  5247. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5248. return this.addVectors( v, w );
  5249. }
  5250. this.x += v.x;
  5251. this.y += v.y;
  5252. this.z += v.z;
  5253. this.w += v.w;
  5254. return this;
  5255. },
  5256. addScalar: function ( s ) {
  5257. this.x += s;
  5258. this.y += s;
  5259. this.z += s;
  5260. this.w += s;
  5261. return this;
  5262. },
  5263. addVectors: function ( a, b ) {
  5264. this.x = a.x + b.x;
  5265. this.y = a.y + b.y;
  5266. this.z = a.z + b.z;
  5267. this.w = a.w + b.w;
  5268. return this;
  5269. },
  5270. addScaledVector: function ( v, s ) {
  5271. this.x += v.x * s;
  5272. this.y += v.y * s;
  5273. this.z += v.z * s;
  5274. this.w += v.w * s;
  5275. return this;
  5276. },
  5277. sub: function ( v, w ) {
  5278. if ( w !== undefined ) {
  5279. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5280. return this.subVectors( v, w );
  5281. }
  5282. this.x -= v.x;
  5283. this.y -= v.y;
  5284. this.z -= v.z;
  5285. this.w -= v.w;
  5286. return this;
  5287. },
  5288. subScalar: function ( s ) {
  5289. this.x -= s;
  5290. this.y -= s;
  5291. this.z -= s;
  5292. this.w -= s;
  5293. return this;
  5294. },
  5295. subVectors: function ( a, b ) {
  5296. this.x = a.x - b.x;
  5297. this.y = a.y - b.y;
  5298. this.z = a.z - b.z;
  5299. this.w = a.w - b.w;
  5300. return this;
  5301. },
  5302. multiplyScalar: function ( scalar ) {
  5303. this.x *= scalar;
  5304. this.y *= scalar;
  5305. this.z *= scalar;
  5306. this.w *= scalar;
  5307. return this;
  5308. },
  5309. applyMatrix4: function ( m ) {
  5310. var x = this.x, y = this.y, z = this.z, w = this.w;
  5311. var e = m.elements;
  5312. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  5313. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  5314. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  5315. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  5316. return this;
  5317. },
  5318. divideScalar: function ( scalar ) {
  5319. return this.multiplyScalar( 1 / scalar );
  5320. },
  5321. setAxisAngleFromQuaternion: function ( q ) {
  5322. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  5323. // q is assumed to be normalized
  5324. this.w = 2 * Math.acos( q.w );
  5325. var s = Math.sqrt( 1 - q.w * q.w );
  5326. if ( s < 0.0001 ) {
  5327. this.x = 1;
  5328. this.y = 0;
  5329. this.z = 0;
  5330. } else {
  5331. this.x = q.x / s;
  5332. this.y = q.y / s;
  5333. this.z = q.z / s;
  5334. }
  5335. return this;
  5336. },
  5337. setAxisAngleFromRotationMatrix: function ( m ) {
  5338. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  5339. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5340. var angle, x, y, z, // variables for result
  5341. epsilon = 0.01, // margin to allow for rounding errors
  5342. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  5343. te = m.elements,
  5344. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5345. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5346. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  5347. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  5348. ( Math.abs( m13 - m31 ) < epsilon ) &&
  5349. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  5350. // singularity found
  5351. // first check for identity matrix which must have +1 for all terms
  5352. // in leading diagonal and zero in other terms
  5353. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  5354. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  5355. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  5356. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  5357. // this singularity is identity matrix so angle = 0
  5358. this.set( 1, 0, 0, 0 );
  5359. return this; // zero angle, arbitrary axis
  5360. }
  5361. // otherwise this singularity is angle = 180
  5362. angle = Math.PI;
  5363. var xx = ( m11 + 1 ) / 2;
  5364. var yy = ( m22 + 1 ) / 2;
  5365. var zz = ( m33 + 1 ) / 2;
  5366. var xy = ( m12 + m21 ) / 4;
  5367. var xz = ( m13 + m31 ) / 4;
  5368. var yz = ( m23 + m32 ) / 4;
  5369. if ( ( xx > yy ) && ( xx > zz ) ) {
  5370. // m11 is the largest diagonal term
  5371. if ( xx < epsilon ) {
  5372. x = 0;
  5373. y = 0.707106781;
  5374. z = 0.707106781;
  5375. } else {
  5376. x = Math.sqrt( xx );
  5377. y = xy / x;
  5378. z = xz / x;
  5379. }
  5380. } else if ( yy > zz ) {
  5381. // m22 is the largest diagonal term
  5382. if ( yy < epsilon ) {
  5383. x = 0.707106781;
  5384. y = 0;
  5385. z = 0.707106781;
  5386. } else {
  5387. y = Math.sqrt( yy );
  5388. x = xy / y;
  5389. z = yz / y;
  5390. }
  5391. } else {
  5392. // m33 is the largest diagonal term so base result on this
  5393. if ( zz < epsilon ) {
  5394. x = 0.707106781;
  5395. y = 0.707106781;
  5396. z = 0;
  5397. } else {
  5398. z = Math.sqrt( zz );
  5399. x = xz / z;
  5400. y = yz / z;
  5401. }
  5402. }
  5403. this.set( x, y, z, angle );
  5404. return this; // return 180 deg rotation
  5405. }
  5406. // as we have reached here there are no singularities so we can handle normally
  5407. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  5408. ( m13 - m31 ) * ( m13 - m31 ) +
  5409. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  5410. if ( Math.abs( s ) < 0.001 ) s = 1;
  5411. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  5412. // caught by singularity test above, but I've left it in just in case
  5413. this.x = ( m32 - m23 ) / s;
  5414. this.y = ( m13 - m31 ) / s;
  5415. this.z = ( m21 - m12 ) / s;
  5416. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  5417. return this;
  5418. },
  5419. min: function ( v ) {
  5420. this.x = Math.min( this.x, v.x );
  5421. this.y = Math.min( this.y, v.y );
  5422. this.z = Math.min( this.z, v.z );
  5423. this.w = Math.min( this.w, v.w );
  5424. return this;
  5425. },
  5426. max: function ( v ) {
  5427. this.x = Math.max( this.x, v.x );
  5428. this.y = Math.max( this.y, v.y );
  5429. this.z = Math.max( this.z, v.z );
  5430. this.w = Math.max( this.w, v.w );
  5431. return this;
  5432. },
  5433. clamp: function ( min, max ) {
  5434. // assumes min < max, componentwise
  5435. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5436. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5437. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5438. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  5439. return this;
  5440. },
  5441. clampScalar: function () {
  5442. var min, max;
  5443. return function clampScalar( minVal, maxVal ) {
  5444. if ( min === undefined ) {
  5445. min = new Vector4();
  5446. max = new Vector4();
  5447. }
  5448. min.set( minVal, minVal, minVal, minVal );
  5449. max.set( maxVal, maxVal, maxVal, maxVal );
  5450. return this.clamp( min, max );
  5451. };
  5452. }(),
  5453. clampLength: function ( min, max ) {
  5454. var length = this.length();
  5455. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  5456. },
  5457. floor: function () {
  5458. this.x = Math.floor( this.x );
  5459. this.y = Math.floor( this.y );
  5460. this.z = Math.floor( this.z );
  5461. this.w = Math.floor( this.w );
  5462. return this;
  5463. },
  5464. ceil: function () {
  5465. this.x = Math.ceil( this.x );
  5466. this.y = Math.ceil( this.y );
  5467. this.z = Math.ceil( this.z );
  5468. this.w = Math.ceil( this.w );
  5469. return this;
  5470. },
  5471. round: function () {
  5472. this.x = Math.round( this.x );
  5473. this.y = Math.round( this.y );
  5474. this.z = Math.round( this.z );
  5475. this.w = Math.round( this.w );
  5476. return this;
  5477. },
  5478. roundToZero: function () {
  5479. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5480. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5481. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5482. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  5483. return this;
  5484. },
  5485. negate: function () {
  5486. this.x = - this.x;
  5487. this.y = - this.y;
  5488. this.z = - this.z;
  5489. this.w = - this.w;
  5490. return this;
  5491. },
  5492. dot: function ( v ) {
  5493. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  5494. },
  5495. lengthSq: function () {
  5496. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  5497. },
  5498. length: function () {
  5499. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  5500. },
  5501. lengthManhattan: function () {
  5502. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  5503. },
  5504. normalize: function () {
  5505. return this.divideScalar( this.length() || 1 );
  5506. },
  5507. setLength: function ( length ) {
  5508. return this.normalize().multiplyScalar( length );
  5509. },
  5510. lerp: function ( v, alpha ) {
  5511. this.x += ( v.x - this.x ) * alpha;
  5512. this.y += ( v.y - this.y ) * alpha;
  5513. this.z += ( v.z - this.z ) * alpha;
  5514. this.w += ( v.w - this.w ) * alpha;
  5515. return this;
  5516. },
  5517. lerpVectors: function ( v1, v2, alpha ) {
  5518. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5519. },
  5520. equals: function ( v ) {
  5521. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  5522. },
  5523. fromArray: function ( array, offset ) {
  5524. if ( offset === undefined ) offset = 0;
  5525. this.x = array[ offset ];
  5526. this.y = array[ offset + 1 ];
  5527. this.z = array[ offset + 2 ];
  5528. this.w = array[ offset + 3 ];
  5529. return this;
  5530. },
  5531. toArray: function ( array, offset ) {
  5532. if ( array === undefined ) array = [];
  5533. if ( offset === undefined ) offset = 0;
  5534. array[ offset ] = this.x;
  5535. array[ offset + 1 ] = this.y;
  5536. array[ offset + 2 ] = this.z;
  5537. array[ offset + 3 ] = this.w;
  5538. return array;
  5539. },
  5540. fromBufferAttribute: function ( attribute, index, offset ) {
  5541. if ( offset !== undefined ) {
  5542. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  5543. }
  5544. this.x = attribute.getX( index );
  5545. this.y = attribute.getY( index );
  5546. this.z = attribute.getZ( index );
  5547. this.w = attribute.getW( index );
  5548. return this;
  5549. }
  5550. } );
  5551. /**
  5552. * @author szimek / https://github.com/szimek/
  5553. * @author alteredq / http://alteredqualia.com/
  5554. * @author Marius Kintel / https://github.com/kintel
  5555. */
  5556. /*
  5557. In options, we can specify:
  5558. * Texture parameters for an auto-generated target texture
  5559. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  5560. */
  5561. function WebGLRenderTarget( width, height, options ) {
  5562. this.uuid = _Math.generateUUID();
  5563. this.width = width;
  5564. this.height = height;
  5565. this.scissor = new Vector4( 0, 0, width, height );
  5566. this.scissorTest = false;
  5567. this.viewport = new Vector4( 0, 0, width, height );
  5568. options = options || {};
  5569. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  5570. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  5571. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  5572. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  5573. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  5574. }
  5575. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  5576. isWebGLRenderTarget: true,
  5577. setSize: function ( width, height ) {
  5578. if ( this.width !== width || this.height !== height ) {
  5579. this.width = width;
  5580. this.height = height;
  5581. this.dispose();
  5582. }
  5583. this.viewport.set( 0, 0, width, height );
  5584. this.scissor.set( 0, 0, width, height );
  5585. },
  5586. clone: function () {
  5587. return new this.constructor().copy( this );
  5588. },
  5589. copy: function ( source ) {
  5590. this.width = source.width;
  5591. this.height = source.height;
  5592. this.viewport.copy( source.viewport );
  5593. this.texture = source.texture.clone();
  5594. this.depthBuffer = source.depthBuffer;
  5595. this.stencilBuffer = source.stencilBuffer;
  5596. this.depthTexture = source.depthTexture;
  5597. return this;
  5598. },
  5599. dispose: function () {
  5600. this.dispatchEvent( { type: 'dispose' } );
  5601. }
  5602. } );
  5603. /**
  5604. * @author alteredq / http://alteredqualia.com
  5605. */
  5606. function WebGLRenderTargetCube( width, height, options ) {
  5607. WebGLRenderTarget.call( this, width, height, options );
  5608. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  5609. this.activeMipMapLevel = 0;
  5610. }
  5611. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  5612. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  5613. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  5614. /**
  5615. * @author mikael emtinger / http://gomo.se/
  5616. * @author alteredq / http://alteredqualia.com/
  5617. * @author WestLangley / http://github.com/WestLangley
  5618. * @author bhouston / http://clara.io
  5619. */
  5620. function Quaternion( x, y, z, w ) {
  5621. this._x = x || 0;
  5622. this._y = y || 0;
  5623. this._z = z || 0;
  5624. this._w = ( w !== undefined ) ? w : 1;
  5625. }
  5626. Object.assign( Quaternion, {
  5627. slerp: function ( qa, qb, qm, t ) {
  5628. return qm.copy( qa ).slerp( qb, t );
  5629. },
  5630. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5631. // fuzz-free, array-based Quaternion SLERP operation
  5632. var x0 = src0[ srcOffset0 + 0 ],
  5633. y0 = src0[ srcOffset0 + 1 ],
  5634. z0 = src0[ srcOffset0 + 2 ],
  5635. w0 = src0[ srcOffset0 + 3 ],
  5636. x1 = src1[ srcOffset1 + 0 ],
  5637. y1 = src1[ srcOffset1 + 1 ],
  5638. z1 = src1[ srcOffset1 + 2 ],
  5639. w1 = src1[ srcOffset1 + 3 ];
  5640. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5641. var s = 1 - t,
  5642. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5643. dir = ( cos >= 0 ? 1 : - 1 ),
  5644. sqrSin = 1 - cos * cos;
  5645. // Skip the Slerp for tiny steps to avoid numeric problems:
  5646. if ( sqrSin > Number.EPSILON ) {
  5647. var sin = Math.sqrt( sqrSin ),
  5648. len = Math.atan2( sin, cos * dir );
  5649. s = Math.sin( s * len ) / sin;
  5650. t = Math.sin( t * len ) / sin;
  5651. }
  5652. var tDir = t * dir;
  5653. x0 = x0 * s + x1 * tDir;
  5654. y0 = y0 * s + y1 * tDir;
  5655. z0 = z0 * s + z1 * tDir;
  5656. w0 = w0 * s + w1 * tDir;
  5657. // Normalize in case we just did a lerp:
  5658. if ( s === 1 - t ) {
  5659. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5660. x0 *= f;
  5661. y0 *= f;
  5662. z0 *= f;
  5663. w0 *= f;
  5664. }
  5665. }
  5666. dst[ dstOffset ] = x0;
  5667. dst[ dstOffset + 1 ] = y0;
  5668. dst[ dstOffset + 2 ] = z0;
  5669. dst[ dstOffset + 3 ] = w0;
  5670. }
  5671. } );
  5672. Object.defineProperties( Quaternion.prototype, {
  5673. x: {
  5674. get: function () {
  5675. return this._x;
  5676. },
  5677. set: function ( value ) {
  5678. this._x = value;
  5679. this.onChangeCallback();
  5680. }
  5681. },
  5682. y: {
  5683. get: function () {
  5684. return this._y;
  5685. },
  5686. set: function ( value ) {
  5687. this._y = value;
  5688. this.onChangeCallback();
  5689. }
  5690. },
  5691. z: {
  5692. get: function () {
  5693. return this._z;
  5694. },
  5695. set: function ( value ) {
  5696. this._z = value;
  5697. this.onChangeCallback();
  5698. }
  5699. },
  5700. w: {
  5701. get: function () {
  5702. return this._w;
  5703. },
  5704. set: function ( value ) {
  5705. this._w = value;
  5706. this.onChangeCallback();
  5707. }
  5708. }
  5709. } );
  5710. Object.assign( Quaternion.prototype, {
  5711. set: function ( x, y, z, w ) {
  5712. this._x = x;
  5713. this._y = y;
  5714. this._z = z;
  5715. this._w = w;
  5716. this.onChangeCallback();
  5717. return this;
  5718. },
  5719. clone: function () {
  5720. return new this.constructor( this._x, this._y, this._z, this._w );
  5721. },
  5722. copy: function ( quaternion ) {
  5723. this._x = quaternion.x;
  5724. this._y = quaternion.y;
  5725. this._z = quaternion.z;
  5726. this._w = quaternion.w;
  5727. this.onChangeCallback();
  5728. return this;
  5729. },
  5730. setFromEuler: function ( euler, update ) {
  5731. if ( ! ( euler && euler.isEuler ) ) {
  5732. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5733. }
  5734. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  5735. // http://www.mathworks.com/matlabcentral/fileexchange/
  5736. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5737. // content/SpinCalc.m
  5738. var cos = Math.cos;
  5739. var sin = Math.sin;
  5740. var c1 = cos( x / 2 );
  5741. var c2 = cos( y / 2 );
  5742. var c3 = cos( z / 2 );
  5743. var s1 = sin( x / 2 );
  5744. var s2 = sin( y / 2 );
  5745. var s3 = sin( z / 2 );
  5746. if ( order === 'XYZ' ) {
  5747. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5748. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5749. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5750. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5751. } else if ( order === 'YXZ' ) {
  5752. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5753. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5754. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5755. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5756. } else if ( order === 'ZXY' ) {
  5757. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5758. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5759. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5760. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5761. } else if ( order === 'ZYX' ) {
  5762. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5763. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5764. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5765. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5766. } else if ( order === 'YZX' ) {
  5767. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5768. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5769. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5770. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5771. } else if ( order === 'XZY' ) {
  5772. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5773. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5774. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5775. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5776. }
  5777. if ( update !== false ) this.onChangeCallback();
  5778. return this;
  5779. },
  5780. setFromAxisAngle: function ( axis, angle ) {
  5781. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5782. // assumes axis is normalized
  5783. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5784. this._x = axis.x * s;
  5785. this._y = axis.y * s;
  5786. this._z = axis.z * s;
  5787. this._w = Math.cos( halfAngle );
  5788. this.onChangeCallback();
  5789. return this;
  5790. },
  5791. setFromRotationMatrix: function ( m ) {
  5792. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5793. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5794. var te = m.elements,
  5795. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5796. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5797. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5798. trace = m11 + m22 + m33,
  5799. s;
  5800. if ( trace > 0 ) {
  5801. s = 0.5 / Math.sqrt( trace + 1.0 );
  5802. this._w = 0.25 / s;
  5803. this._x = ( m32 - m23 ) * s;
  5804. this._y = ( m13 - m31 ) * s;
  5805. this._z = ( m21 - m12 ) * s;
  5806. } else if ( m11 > m22 && m11 > m33 ) {
  5807. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5808. this._w = ( m32 - m23 ) / s;
  5809. this._x = 0.25 * s;
  5810. this._y = ( m12 + m21 ) / s;
  5811. this._z = ( m13 + m31 ) / s;
  5812. } else if ( m22 > m33 ) {
  5813. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5814. this._w = ( m13 - m31 ) / s;
  5815. this._x = ( m12 + m21 ) / s;
  5816. this._y = 0.25 * s;
  5817. this._z = ( m23 + m32 ) / s;
  5818. } else {
  5819. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5820. this._w = ( m21 - m12 ) / s;
  5821. this._x = ( m13 + m31 ) / s;
  5822. this._y = ( m23 + m32 ) / s;
  5823. this._z = 0.25 * s;
  5824. }
  5825. this.onChangeCallback();
  5826. return this;
  5827. },
  5828. setFromUnitVectors: function () {
  5829. // assumes direction vectors vFrom and vTo are normalized
  5830. var v1 = new Vector3();
  5831. var r;
  5832. var EPS = 0.000001;
  5833. return function setFromUnitVectors( vFrom, vTo ) {
  5834. if ( v1 === undefined ) v1 = new Vector3();
  5835. r = vFrom.dot( vTo ) + 1;
  5836. if ( r < EPS ) {
  5837. r = 0;
  5838. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5839. v1.set( - vFrom.y, vFrom.x, 0 );
  5840. } else {
  5841. v1.set( 0, - vFrom.z, vFrom.y );
  5842. }
  5843. } else {
  5844. v1.crossVectors( vFrom, vTo );
  5845. }
  5846. this._x = v1.x;
  5847. this._y = v1.y;
  5848. this._z = v1.z;
  5849. this._w = r;
  5850. return this.normalize();
  5851. };
  5852. }(),
  5853. inverse: function () {
  5854. return this.conjugate().normalize();
  5855. },
  5856. conjugate: function () {
  5857. this._x *= - 1;
  5858. this._y *= - 1;
  5859. this._z *= - 1;
  5860. this.onChangeCallback();
  5861. return this;
  5862. },
  5863. dot: function ( v ) {
  5864. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5865. },
  5866. lengthSq: function () {
  5867. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5868. },
  5869. length: function () {
  5870. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5871. },
  5872. normalize: function () {
  5873. var l = this.length();
  5874. if ( l === 0 ) {
  5875. this._x = 0;
  5876. this._y = 0;
  5877. this._z = 0;
  5878. this._w = 1;
  5879. } else {
  5880. l = 1 / l;
  5881. this._x = this._x * l;
  5882. this._y = this._y * l;
  5883. this._z = this._z * l;
  5884. this._w = this._w * l;
  5885. }
  5886. this.onChangeCallback();
  5887. return this;
  5888. },
  5889. multiply: function ( q, p ) {
  5890. if ( p !== undefined ) {
  5891. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5892. return this.multiplyQuaternions( q, p );
  5893. }
  5894. return this.multiplyQuaternions( this, q );
  5895. },
  5896. premultiply: function ( q ) {
  5897. return this.multiplyQuaternions( q, this );
  5898. },
  5899. multiplyQuaternions: function ( a, b ) {
  5900. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5901. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5902. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5903. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5904. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5905. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5906. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5907. this.onChangeCallback();
  5908. return this;
  5909. },
  5910. slerp: function ( qb, t ) {
  5911. if ( t === 0 ) return this;
  5912. if ( t === 1 ) return this.copy( qb );
  5913. var x = this._x, y = this._y, z = this._z, w = this._w;
  5914. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5915. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5916. if ( cosHalfTheta < 0 ) {
  5917. this._w = - qb._w;
  5918. this._x = - qb._x;
  5919. this._y = - qb._y;
  5920. this._z = - qb._z;
  5921. cosHalfTheta = - cosHalfTheta;
  5922. } else {
  5923. this.copy( qb );
  5924. }
  5925. if ( cosHalfTheta >= 1.0 ) {
  5926. this._w = w;
  5927. this._x = x;
  5928. this._y = y;
  5929. this._z = z;
  5930. return this;
  5931. }
  5932. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  5933. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  5934. this._w = 0.5 * ( w + this._w );
  5935. this._x = 0.5 * ( x + this._x );
  5936. this._y = 0.5 * ( y + this._y );
  5937. this._z = 0.5 * ( z + this._z );
  5938. return this;
  5939. }
  5940. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5941. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5942. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5943. this._w = ( w * ratioA + this._w * ratioB );
  5944. this._x = ( x * ratioA + this._x * ratioB );
  5945. this._y = ( y * ratioA + this._y * ratioB );
  5946. this._z = ( z * ratioA + this._z * ratioB );
  5947. this.onChangeCallback();
  5948. return this;
  5949. },
  5950. equals: function ( quaternion ) {
  5951. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  5952. },
  5953. fromArray: function ( array, offset ) {
  5954. if ( offset === undefined ) offset = 0;
  5955. this._x = array[ offset ];
  5956. this._y = array[ offset + 1 ];
  5957. this._z = array[ offset + 2 ];
  5958. this._w = array[ offset + 3 ];
  5959. this.onChangeCallback();
  5960. return this;
  5961. },
  5962. toArray: function ( array, offset ) {
  5963. if ( array === undefined ) array = [];
  5964. if ( offset === undefined ) offset = 0;
  5965. array[ offset ] = this._x;
  5966. array[ offset + 1 ] = this._y;
  5967. array[ offset + 2 ] = this._z;
  5968. array[ offset + 3 ] = this._w;
  5969. return array;
  5970. },
  5971. onChange: function ( callback ) {
  5972. this.onChangeCallback = callback;
  5973. return this;
  5974. },
  5975. onChangeCallback: function () {}
  5976. } );
  5977. /**
  5978. * @author mrdoob / http://mrdoob.com/
  5979. * @author kile / http://kile.stravaganza.org/
  5980. * @author philogb / http://blog.thejit.org/
  5981. * @author mikael emtinger / http://gomo.se/
  5982. * @author egraether / http://egraether.com/
  5983. * @author WestLangley / http://github.com/WestLangley
  5984. */
  5985. function Vector3( x, y, z ) {
  5986. this.x = x || 0;
  5987. this.y = y || 0;
  5988. this.z = z || 0;
  5989. }
  5990. Object.assign( Vector3.prototype, {
  5991. isVector3: true,
  5992. set: function ( x, y, z ) {
  5993. this.x = x;
  5994. this.y = y;
  5995. this.z = z;
  5996. return this;
  5997. },
  5998. setScalar: function ( scalar ) {
  5999. this.x = scalar;
  6000. this.y = scalar;
  6001. this.z = scalar;
  6002. return this;
  6003. },
  6004. setX: function ( x ) {
  6005. this.x = x;
  6006. return this;
  6007. },
  6008. setY: function ( y ) {
  6009. this.y = y;
  6010. return this;
  6011. },
  6012. setZ: function ( z ) {
  6013. this.z = z;
  6014. return this;
  6015. },
  6016. setComponent: function ( index, value ) {
  6017. switch ( index ) {
  6018. case 0: this.x = value; break;
  6019. case 1: this.y = value; break;
  6020. case 2: this.z = value; break;
  6021. default: throw new Error( 'index is out of range: ' + index );
  6022. }
  6023. return this;
  6024. },
  6025. getComponent: function ( index ) {
  6026. switch ( index ) {
  6027. case 0: return this.x;
  6028. case 1: return this.y;
  6029. case 2: return this.z;
  6030. default: throw new Error( 'index is out of range: ' + index );
  6031. }
  6032. },
  6033. clone: function () {
  6034. return new this.constructor( this.x, this.y, this.z );
  6035. },
  6036. copy: function ( v ) {
  6037. this.x = v.x;
  6038. this.y = v.y;
  6039. this.z = v.z;
  6040. return this;
  6041. },
  6042. add: function ( v, w ) {
  6043. if ( w !== undefined ) {
  6044. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6045. return this.addVectors( v, w );
  6046. }
  6047. this.x += v.x;
  6048. this.y += v.y;
  6049. this.z += v.z;
  6050. return this;
  6051. },
  6052. addScalar: function ( s ) {
  6053. this.x += s;
  6054. this.y += s;
  6055. this.z += s;
  6056. return this;
  6057. },
  6058. addVectors: function ( a, b ) {
  6059. this.x = a.x + b.x;
  6060. this.y = a.y + b.y;
  6061. this.z = a.z + b.z;
  6062. return this;
  6063. },
  6064. addScaledVector: function ( v, s ) {
  6065. this.x += v.x * s;
  6066. this.y += v.y * s;
  6067. this.z += v.z * s;
  6068. return this;
  6069. },
  6070. sub: function ( v, w ) {
  6071. if ( w !== undefined ) {
  6072. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6073. return this.subVectors( v, w );
  6074. }
  6075. this.x -= v.x;
  6076. this.y -= v.y;
  6077. this.z -= v.z;
  6078. return this;
  6079. },
  6080. subScalar: function ( s ) {
  6081. this.x -= s;
  6082. this.y -= s;
  6083. this.z -= s;
  6084. return this;
  6085. },
  6086. subVectors: function ( a, b ) {
  6087. this.x = a.x - b.x;
  6088. this.y = a.y - b.y;
  6089. this.z = a.z - b.z;
  6090. return this;
  6091. },
  6092. multiply: function ( v, w ) {
  6093. if ( w !== undefined ) {
  6094. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6095. return this.multiplyVectors( v, w );
  6096. }
  6097. this.x *= v.x;
  6098. this.y *= v.y;
  6099. this.z *= v.z;
  6100. return this;
  6101. },
  6102. multiplyScalar: function ( scalar ) {
  6103. this.x *= scalar;
  6104. this.y *= scalar;
  6105. this.z *= scalar;
  6106. return this;
  6107. },
  6108. multiplyVectors: function ( a, b ) {
  6109. this.x = a.x * b.x;
  6110. this.y = a.y * b.y;
  6111. this.z = a.z * b.z;
  6112. return this;
  6113. },
  6114. applyEuler: function () {
  6115. var quaternion = new Quaternion();
  6116. return function applyEuler( euler ) {
  6117. if ( ! ( euler && euler.isEuler ) ) {
  6118. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6119. }
  6120. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  6121. };
  6122. }(),
  6123. applyAxisAngle: function () {
  6124. var quaternion = new Quaternion();
  6125. return function applyAxisAngle( axis, angle ) {
  6126. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  6127. };
  6128. }(),
  6129. applyMatrix3: function ( m ) {
  6130. var x = this.x, y = this.y, z = this.z;
  6131. var e = m.elements;
  6132. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6133. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6134. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6135. return this;
  6136. },
  6137. applyMatrix4: function ( m ) {
  6138. var x = this.x, y = this.y, z = this.z;
  6139. var e = m.elements;
  6140. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6141. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6142. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6143. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6144. return this;
  6145. },
  6146. applyQuaternion: function ( q ) {
  6147. var x = this.x, y = this.y, z = this.z;
  6148. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6149. // calculate quat * vector
  6150. var ix = qw * x + qy * z - qz * y;
  6151. var iy = qw * y + qz * x - qx * z;
  6152. var iz = qw * z + qx * y - qy * x;
  6153. var iw = - qx * x - qy * y - qz * z;
  6154. // calculate result * inverse quat
  6155. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6156. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6157. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6158. return this;
  6159. },
  6160. project: function () {
  6161. var matrix = new Matrix4();
  6162. return function project( camera ) {
  6163. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  6164. return this.applyMatrix4( matrix );
  6165. };
  6166. }(),
  6167. unproject: function () {
  6168. var matrix = new Matrix4();
  6169. return function unproject( camera ) {
  6170. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  6171. return this.applyMatrix4( matrix );
  6172. };
  6173. }(),
  6174. transformDirection: function ( m ) {
  6175. // input: THREE.Matrix4 affine matrix
  6176. // vector interpreted as a direction
  6177. var x = this.x, y = this.y, z = this.z;
  6178. var e = m.elements;
  6179. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6180. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6181. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6182. return this.normalize();
  6183. },
  6184. divide: function ( v ) {
  6185. this.x /= v.x;
  6186. this.y /= v.y;
  6187. this.z /= v.z;
  6188. return this;
  6189. },
  6190. divideScalar: function ( scalar ) {
  6191. return this.multiplyScalar( 1 / scalar );
  6192. },
  6193. min: function ( v ) {
  6194. this.x = Math.min( this.x, v.x );
  6195. this.y = Math.min( this.y, v.y );
  6196. this.z = Math.min( this.z, v.z );
  6197. return this;
  6198. },
  6199. max: function ( v ) {
  6200. this.x = Math.max( this.x, v.x );
  6201. this.y = Math.max( this.y, v.y );
  6202. this.z = Math.max( this.z, v.z );
  6203. return this;
  6204. },
  6205. clamp: function ( min, max ) {
  6206. // assumes min < max, componentwise
  6207. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6208. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6209. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6210. return this;
  6211. },
  6212. clampScalar: function () {
  6213. var min = new Vector3();
  6214. var max = new Vector3();
  6215. return function clampScalar( minVal, maxVal ) {
  6216. min.set( minVal, minVal, minVal );
  6217. max.set( maxVal, maxVal, maxVal );
  6218. return this.clamp( min, max );
  6219. };
  6220. }(),
  6221. clampLength: function ( min, max ) {
  6222. var length = this.length();
  6223. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6224. },
  6225. floor: function () {
  6226. this.x = Math.floor( this.x );
  6227. this.y = Math.floor( this.y );
  6228. this.z = Math.floor( this.z );
  6229. return this;
  6230. },
  6231. ceil: function () {
  6232. this.x = Math.ceil( this.x );
  6233. this.y = Math.ceil( this.y );
  6234. this.z = Math.ceil( this.z );
  6235. return this;
  6236. },
  6237. round: function () {
  6238. this.x = Math.round( this.x );
  6239. this.y = Math.round( this.y );
  6240. this.z = Math.round( this.z );
  6241. return this;
  6242. },
  6243. roundToZero: function () {
  6244. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6245. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6246. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6247. return this;
  6248. },
  6249. negate: function () {
  6250. this.x = - this.x;
  6251. this.y = - this.y;
  6252. this.z = - this.z;
  6253. return this;
  6254. },
  6255. dot: function ( v ) {
  6256. return this.x * v.x + this.y * v.y + this.z * v.z;
  6257. },
  6258. // TODO lengthSquared?
  6259. lengthSq: function () {
  6260. return this.x * this.x + this.y * this.y + this.z * this.z;
  6261. },
  6262. length: function () {
  6263. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6264. },
  6265. lengthManhattan: function () {
  6266. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6267. },
  6268. normalize: function () {
  6269. return this.divideScalar( this.length() || 1 );
  6270. },
  6271. setLength: function ( length ) {
  6272. return this.normalize().multiplyScalar( length );
  6273. },
  6274. lerp: function ( v, alpha ) {
  6275. this.x += ( v.x - this.x ) * alpha;
  6276. this.y += ( v.y - this.y ) * alpha;
  6277. this.z += ( v.z - this.z ) * alpha;
  6278. return this;
  6279. },
  6280. lerpVectors: function ( v1, v2, alpha ) {
  6281. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6282. },
  6283. cross: function ( v, w ) {
  6284. if ( w !== undefined ) {
  6285. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6286. return this.crossVectors( v, w );
  6287. }
  6288. var x = this.x, y = this.y, z = this.z;
  6289. this.x = y * v.z - z * v.y;
  6290. this.y = z * v.x - x * v.z;
  6291. this.z = x * v.y - y * v.x;
  6292. return this;
  6293. },
  6294. crossVectors: function ( a, b ) {
  6295. var ax = a.x, ay = a.y, az = a.z;
  6296. var bx = b.x, by = b.y, bz = b.z;
  6297. this.x = ay * bz - az * by;
  6298. this.y = az * bx - ax * bz;
  6299. this.z = ax * by - ay * bx;
  6300. return this;
  6301. },
  6302. projectOnVector: function ( vector ) {
  6303. var scalar = vector.dot( this ) / vector.lengthSq();
  6304. return this.copy( vector ).multiplyScalar( scalar );
  6305. },
  6306. projectOnPlane: function () {
  6307. var v1 = new Vector3();
  6308. return function projectOnPlane( planeNormal ) {
  6309. v1.copy( this ).projectOnVector( planeNormal );
  6310. return this.sub( v1 );
  6311. };
  6312. }(),
  6313. reflect: function () {
  6314. // reflect incident vector off plane orthogonal to normal
  6315. // normal is assumed to have unit length
  6316. var v1 = new Vector3();
  6317. return function reflect( normal ) {
  6318. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6319. };
  6320. }(),
  6321. angleTo: function ( v ) {
  6322. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6323. // clamp, to handle numerical problems
  6324. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6325. },
  6326. distanceTo: function ( v ) {
  6327. return Math.sqrt( this.distanceToSquared( v ) );
  6328. },
  6329. distanceToSquared: function ( v ) {
  6330. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6331. return dx * dx + dy * dy + dz * dz;
  6332. },
  6333. distanceToManhattan: function ( v ) {
  6334. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6335. },
  6336. setFromSpherical: function ( s ) {
  6337. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  6338. this.x = sinPhiRadius * Math.sin( s.theta );
  6339. this.y = Math.cos( s.phi ) * s.radius;
  6340. this.z = sinPhiRadius * Math.cos( s.theta );
  6341. return this;
  6342. },
  6343. setFromCylindrical: function ( c ) {
  6344. this.x = c.radius * Math.sin( c.theta );
  6345. this.y = c.y;
  6346. this.z = c.radius * Math.cos( c.theta );
  6347. return this;
  6348. },
  6349. setFromMatrixPosition: function ( m ) {
  6350. var e = m.elements;
  6351. this.x = e[ 12 ];
  6352. this.y = e[ 13 ];
  6353. this.z = e[ 14 ];
  6354. return this;
  6355. },
  6356. setFromMatrixScale: function ( m ) {
  6357. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6358. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6359. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6360. this.x = sx;
  6361. this.y = sy;
  6362. this.z = sz;
  6363. return this;
  6364. },
  6365. setFromMatrixColumn: function ( m, index ) {
  6366. return this.fromArray( m.elements, index * 4 );
  6367. },
  6368. equals: function ( v ) {
  6369. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6370. },
  6371. fromArray: function ( array, offset ) {
  6372. if ( offset === undefined ) offset = 0;
  6373. this.x = array[ offset ];
  6374. this.y = array[ offset + 1 ];
  6375. this.z = array[ offset + 2 ];
  6376. return this;
  6377. },
  6378. toArray: function ( array, offset ) {
  6379. if ( array === undefined ) array = [];
  6380. if ( offset === undefined ) offset = 0;
  6381. array[ offset ] = this.x;
  6382. array[ offset + 1 ] = this.y;
  6383. array[ offset + 2 ] = this.z;
  6384. return array;
  6385. },
  6386. fromBufferAttribute: function ( attribute, index, offset ) {
  6387. if ( offset !== undefined ) {
  6388. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6389. }
  6390. this.x = attribute.getX( index );
  6391. this.y = attribute.getY( index );
  6392. this.z = attribute.getZ( index );
  6393. return this;
  6394. }
  6395. } );
  6396. /**
  6397. * @author mrdoob / http://mrdoob.com/
  6398. * @author supereggbert / http://www.paulbrunt.co.uk/
  6399. * @author philogb / http://blog.thejit.org/
  6400. * @author jordi_ros / http://plattsoft.com
  6401. * @author D1plo1d / http://github.com/D1plo1d
  6402. * @author alteredq / http://alteredqualia.com/
  6403. * @author mikael emtinger / http://gomo.se/
  6404. * @author timknip / http://www.floorplanner.com/
  6405. * @author bhouston / http://clara.io
  6406. * @author WestLangley / http://github.com/WestLangley
  6407. */
  6408. function Matrix4() {
  6409. this.elements = [
  6410. 1, 0, 0, 0,
  6411. 0, 1, 0, 0,
  6412. 0, 0, 1, 0,
  6413. 0, 0, 0, 1
  6414. ];
  6415. if ( arguments.length > 0 ) {
  6416. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  6417. }
  6418. }
  6419. Object.assign( Matrix4.prototype, {
  6420. isMatrix4: true,
  6421. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6422. var te = this.elements;
  6423. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6424. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6425. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6426. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6427. return this;
  6428. },
  6429. identity: function () {
  6430. this.set(
  6431. 1, 0, 0, 0,
  6432. 0, 1, 0, 0,
  6433. 0, 0, 1, 0,
  6434. 0, 0, 0, 1
  6435. );
  6436. return this;
  6437. },
  6438. clone: function () {
  6439. return new Matrix4().fromArray( this.elements );
  6440. },
  6441. copy: function ( m ) {
  6442. var te = this.elements;
  6443. var me = m.elements;
  6444. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  6445. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  6446. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  6447. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  6448. return this;
  6449. },
  6450. copyPosition: function ( m ) {
  6451. var te = this.elements, me = m.elements;
  6452. te[ 12 ] = me[ 12 ];
  6453. te[ 13 ] = me[ 13 ];
  6454. te[ 14 ] = me[ 14 ];
  6455. return this;
  6456. },
  6457. extractBasis: function ( xAxis, yAxis, zAxis ) {
  6458. xAxis.setFromMatrixColumn( this, 0 );
  6459. yAxis.setFromMatrixColumn( this, 1 );
  6460. zAxis.setFromMatrixColumn( this, 2 );
  6461. return this;
  6462. },
  6463. makeBasis: function ( xAxis, yAxis, zAxis ) {
  6464. this.set(
  6465. xAxis.x, yAxis.x, zAxis.x, 0,
  6466. xAxis.y, yAxis.y, zAxis.y, 0,
  6467. xAxis.z, yAxis.z, zAxis.z, 0,
  6468. 0, 0, 0, 1
  6469. );
  6470. return this;
  6471. },
  6472. extractRotation: function () {
  6473. var v1 = new Vector3();
  6474. return function extractRotation( m ) {
  6475. var te = this.elements;
  6476. var me = m.elements;
  6477. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  6478. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  6479. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  6480. te[ 0 ] = me[ 0 ] * scaleX;
  6481. te[ 1 ] = me[ 1 ] * scaleX;
  6482. te[ 2 ] = me[ 2 ] * scaleX;
  6483. te[ 4 ] = me[ 4 ] * scaleY;
  6484. te[ 5 ] = me[ 5 ] * scaleY;
  6485. te[ 6 ] = me[ 6 ] * scaleY;
  6486. te[ 8 ] = me[ 8 ] * scaleZ;
  6487. te[ 9 ] = me[ 9 ] * scaleZ;
  6488. te[ 10 ] = me[ 10 ] * scaleZ;
  6489. return this;
  6490. };
  6491. }(),
  6492. makeRotationFromEuler: function ( euler ) {
  6493. if ( ! ( euler && euler.isEuler ) ) {
  6494. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  6495. }
  6496. var te = this.elements;
  6497. var x = euler.x, y = euler.y, z = euler.z;
  6498. var a = Math.cos( x ), b = Math.sin( x );
  6499. var c = Math.cos( y ), d = Math.sin( y );
  6500. var e = Math.cos( z ), f = Math.sin( z );
  6501. if ( euler.order === 'XYZ' ) {
  6502. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6503. te[ 0 ] = c * e;
  6504. te[ 4 ] = - c * f;
  6505. te[ 8 ] = d;
  6506. te[ 1 ] = af + be * d;
  6507. te[ 5 ] = ae - bf * d;
  6508. te[ 9 ] = - b * c;
  6509. te[ 2 ] = bf - ae * d;
  6510. te[ 6 ] = be + af * d;
  6511. te[ 10 ] = a * c;
  6512. } else if ( euler.order === 'YXZ' ) {
  6513. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6514. te[ 0 ] = ce + df * b;
  6515. te[ 4 ] = de * b - cf;
  6516. te[ 8 ] = a * d;
  6517. te[ 1 ] = a * f;
  6518. te[ 5 ] = a * e;
  6519. te[ 9 ] = - b;
  6520. te[ 2 ] = cf * b - de;
  6521. te[ 6 ] = df + ce * b;
  6522. te[ 10 ] = a * c;
  6523. } else if ( euler.order === 'ZXY' ) {
  6524. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6525. te[ 0 ] = ce - df * b;
  6526. te[ 4 ] = - a * f;
  6527. te[ 8 ] = de + cf * b;
  6528. te[ 1 ] = cf + de * b;
  6529. te[ 5 ] = a * e;
  6530. te[ 9 ] = df - ce * b;
  6531. te[ 2 ] = - a * d;
  6532. te[ 6 ] = b;
  6533. te[ 10 ] = a * c;
  6534. } else if ( euler.order === 'ZYX' ) {
  6535. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6536. te[ 0 ] = c * e;
  6537. te[ 4 ] = be * d - af;
  6538. te[ 8 ] = ae * d + bf;
  6539. te[ 1 ] = c * f;
  6540. te[ 5 ] = bf * d + ae;
  6541. te[ 9 ] = af * d - be;
  6542. te[ 2 ] = - d;
  6543. te[ 6 ] = b * c;
  6544. te[ 10 ] = a * c;
  6545. } else if ( euler.order === 'YZX' ) {
  6546. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6547. te[ 0 ] = c * e;
  6548. te[ 4 ] = bd - ac * f;
  6549. te[ 8 ] = bc * f + ad;
  6550. te[ 1 ] = f;
  6551. te[ 5 ] = a * e;
  6552. te[ 9 ] = - b * e;
  6553. te[ 2 ] = - d * e;
  6554. te[ 6 ] = ad * f + bc;
  6555. te[ 10 ] = ac - bd * f;
  6556. } else if ( euler.order === 'XZY' ) {
  6557. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6558. te[ 0 ] = c * e;
  6559. te[ 4 ] = - f;
  6560. te[ 8 ] = d * e;
  6561. te[ 1 ] = ac * f + bd;
  6562. te[ 5 ] = a * e;
  6563. te[ 9 ] = ad * f - bc;
  6564. te[ 2 ] = bc * f - ad;
  6565. te[ 6 ] = b * e;
  6566. te[ 10 ] = bd * f + ac;
  6567. }
  6568. // last column
  6569. te[ 3 ] = 0;
  6570. te[ 7 ] = 0;
  6571. te[ 11 ] = 0;
  6572. // bottom row
  6573. te[ 12 ] = 0;
  6574. te[ 13 ] = 0;
  6575. te[ 14 ] = 0;
  6576. te[ 15 ] = 1;
  6577. return this;
  6578. },
  6579. makeRotationFromQuaternion: function ( q ) {
  6580. var te = this.elements;
  6581. var x = q._x, y = q._y, z = q._z, w = q._w;
  6582. var x2 = x + x, y2 = y + y, z2 = z + z;
  6583. var xx = x * x2, xy = x * y2, xz = x * z2;
  6584. var yy = y * y2, yz = y * z2, zz = z * z2;
  6585. var wx = w * x2, wy = w * y2, wz = w * z2;
  6586. te[ 0 ] = 1 - ( yy + zz );
  6587. te[ 4 ] = xy - wz;
  6588. te[ 8 ] = xz + wy;
  6589. te[ 1 ] = xy + wz;
  6590. te[ 5 ] = 1 - ( xx + zz );
  6591. te[ 9 ] = yz - wx;
  6592. te[ 2 ] = xz - wy;
  6593. te[ 6 ] = yz + wx;
  6594. te[ 10 ] = 1 - ( xx + yy );
  6595. // last column
  6596. te[ 3 ] = 0;
  6597. te[ 7 ] = 0;
  6598. te[ 11 ] = 0;
  6599. // bottom row
  6600. te[ 12 ] = 0;
  6601. te[ 13 ] = 0;
  6602. te[ 14 ] = 0;
  6603. te[ 15 ] = 1;
  6604. return this;
  6605. },
  6606. lookAt: function () {
  6607. var x = new Vector3();
  6608. var y = new Vector3();
  6609. var z = new Vector3();
  6610. return function lookAt( eye, target, up ) {
  6611. var te = this.elements;
  6612. z.subVectors( eye, target );
  6613. if ( z.lengthSq() === 0 ) {
  6614. // eye and target are in the same position
  6615. z.z = 1;
  6616. }
  6617. z.normalize();
  6618. x.crossVectors( up, z );
  6619. if ( x.lengthSq() === 0 ) {
  6620. // up and z are parallel
  6621. if ( Math.abs( up.z ) === 1 ) {
  6622. z.x += 0.0001;
  6623. } else {
  6624. z.z += 0.0001;
  6625. }
  6626. z.normalize();
  6627. x.crossVectors( up, z );
  6628. }
  6629. x.normalize();
  6630. y.crossVectors( z, x );
  6631. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  6632. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  6633. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  6634. return this;
  6635. };
  6636. }(),
  6637. multiply: function ( m, n ) {
  6638. if ( n !== undefined ) {
  6639. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  6640. return this.multiplyMatrices( m, n );
  6641. }
  6642. return this.multiplyMatrices( this, m );
  6643. },
  6644. premultiply: function ( m ) {
  6645. return this.multiplyMatrices( m, this );
  6646. },
  6647. multiplyMatrices: function ( a, b ) {
  6648. var ae = a.elements;
  6649. var be = b.elements;
  6650. var te = this.elements;
  6651. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6652. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6653. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6654. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6655. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6656. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6657. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6658. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6659. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6660. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6661. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6662. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6663. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6664. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6665. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6666. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6667. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6668. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6669. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6670. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6671. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6672. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6673. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6674. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6675. return this;
  6676. },
  6677. multiplyScalar: function ( s ) {
  6678. var te = this.elements;
  6679. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6680. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6681. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6682. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6683. return this;
  6684. },
  6685. applyToBufferAttribute: function () {
  6686. var v1 = new Vector3();
  6687. return function applyToBufferAttribute( attribute ) {
  6688. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6689. v1.x = attribute.getX( i );
  6690. v1.y = attribute.getY( i );
  6691. v1.z = attribute.getZ( i );
  6692. v1.applyMatrix4( this );
  6693. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6694. }
  6695. return attribute;
  6696. };
  6697. }(),
  6698. determinant: function () {
  6699. var te = this.elements;
  6700. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6701. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6702. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6703. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6704. //TODO: make this more efficient
  6705. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  6706. return (
  6707. n41 * (
  6708. + n14 * n23 * n32
  6709. - n13 * n24 * n32
  6710. - n14 * n22 * n33
  6711. + n12 * n24 * n33
  6712. + n13 * n22 * n34
  6713. - n12 * n23 * n34
  6714. ) +
  6715. n42 * (
  6716. + n11 * n23 * n34
  6717. - n11 * n24 * n33
  6718. + n14 * n21 * n33
  6719. - n13 * n21 * n34
  6720. + n13 * n24 * n31
  6721. - n14 * n23 * n31
  6722. ) +
  6723. n43 * (
  6724. + n11 * n24 * n32
  6725. - n11 * n22 * n34
  6726. - n14 * n21 * n32
  6727. + n12 * n21 * n34
  6728. + n14 * n22 * n31
  6729. - n12 * n24 * n31
  6730. ) +
  6731. n44 * (
  6732. - n13 * n22 * n31
  6733. - n11 * n23 * n32
  6734. + n11 * n22 * n33
  6735. + n13 * n21 * n32
  6736. - n12 * n21 * n33
  6737. + n12 * n23 * n31
  6738. )
  6739. );
  6740. },
  6741. transpose: function () {
  6742. var te = this.elements;
  6743. var tmp;
  6744. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  6745. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  6746. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  6747. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  6748. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  6749. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  6750. return this;
  6751. },
  6752. setPosition: function ( v ) {
  6753. var te = this.elements;
  6754. te[ 12 ] = v.x;
  6755. te[ 13 ] = v.y;
  6756. te[ 14 ] = v.z;
  6757. return this;
  6758. },
  6759. getInverse: function ( m, throwOnDegenerate ) {
  6760. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  6761. var te = this.elements,
  6762. me = m.elements,
  6763. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  6764. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  6765. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  6766. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  6767. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  6768. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  6769. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  6770. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  6771. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  6772. if ( det === 0 ) {
  6773. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  6774. if ( throwOnDegenerate === true ) {
  6775. throw new Error( msg );
  6776. } else {
  6777. console.warn( msg );
  6778. }
  6779. return this.identity();
  6780. }
  6781. var detInv = 1 / det;
  6782. te[ 0 ] = t11 * detInv;
  6783. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  6784. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  6785. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  6786. te[ 4 ] = t12 * detInv;
  6787. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  6788. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  6789. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  6790. te[ 8 ] = t13 * detInv;
  6791. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  6792. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  6793. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  6794. te[ 12 ] = t14 * detInv;
  6795. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  6796. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  6797. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  6798. return this;
  6799. },
  6800. scale: function ( v ) {
  6801. var te = this.elements;
  6802. var x = v.x, y = v.y, z = v.z;
  6803. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  6804. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  6805. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  6806. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  6807. return this;
  6808. },
  6809. getMaxScaleOnAxis: function () {
  6810. var te = this.elements;
  6811. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  6812. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  6813. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  6814. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  6815. },
  6816. makeTranslation: function ( x, y, z ) {
  6817. this.set(
  6818. 1, 0, 0, x,
  6819. 0, 1, 0, y,
  6820. 0, 0, 1, z,
  6821. 0, 0, 0, 1
  6822. );
  6823. return this;
  6824. },
  6825. makeRotationX: function ( theta ) {
  6826. var c = Math.cos( theta ), s = Math.sin( theta );
  6827. this.set(
  6828. 1, 0, 0, 0,
  6829. 0, c, - s, 0,
  6830. 0, s, c, 0,
  6831. 0, 0, 0, 1
  6832. );
  6833. return this;
  6834. },
  6835. makeRotationY: function ( theta ) {
  6836. var c = Math.cos( theta ), s = Math.sin( theta );
  6837. this.set(
  6838. c, 0, s, 0,
  6839. 0, 1, 0, 0,
  6840. - s, 0, c, 0,
  6841. 0, 0, 0, 1
  6842. );
  6843. return this;
  6844. },
  6845. makeRotationZ: function ( theta ) {
  6846. var c = Math.cos( theta ), s = Math.sin( theta );
  6847. this.set(
  6848. c, - s, 0, 0,
  6849. s, c, 0, 0,
  6850. 0, 0, 1, 0,
  6851. 0, 0, 0, 1
  6852. );
  6853. return this;
  6854. },
  6855. makeRotationAxis: function ( axis, angle ) {
  6856. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  6857. var c = Math.cos( angle );
  6858. var s = Math.sin( angle );
  6859. var t = 1 - c;
  6860. var x = axis.x, y = axis.y, z = axis.z;
  6861. var tx = t * x, ty = t * y;
  6862. this.set(
  6863. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  6864. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  6865. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  6866. 0, 0, 0, 1
  6867. );
  6868. return this;
  6869. },
  6870. makeScale: function ( x, y, z ) {
  6871. this.set(
  6872. x, 0, 0, 0,
  6873. 0, y, 0, 0,
  6874. 0, 0, z, 0,
  6875. 0, 0, 0, 1
  6876. );
  6877. return this;
  6878. },
  6879. makeShear: function ( x, y, z ) {
  6880. this.set(
  6881. 1, y, z, 0,
  6882. x, 1, z, 0,
  6883. x, y, 1, 0,
  6884. 0, 0, 0, 1
  6885. );
  6886. return this;
  6887. },
  6888. compose: function ( position, quaternion, scale ) {
  6889. this.makeRotationFromQuaternion( quaternion );
  6890. this.scale( scale );
  6891. this.setPosition( position );
  6892. return this;
  6893. },
  6894. decompose: function () {
  6895. var vector = new Vector3();
  6896. var matrix = new Matrix4();
  6897. return function decompose( position, quaternion, scale ) {
  6898. var te = this.elements;
  6899. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  6900. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  6901. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  6902. // if determine is negative, we need to invert one scale
  6903. var det = this.determinant();
  6904. if ( det < 0 ) sx = - sx;
  6905. position.x = te[ 12 ];
  6906. position.y = te[ 13 ];
  6907. position.z = te[ 14 ];
  6908. // scale the rotation part
  6909. matrix.copy( this );
  6910. var invSX = 1 / sx;
  6911. var invSY = 1 / sy;
  6912. var invSZ = 1 / sz;
  6913. matrix.elements[ 0 ] *= invSX;
  6914. matrix.elements[ 1 ] *= invSX;
  6915. matrix.elements[ 2 ] *= invSX;
  6916. matrix.elements[ 4 ] *= invSY;
  6917. matrix.elements[ 5 ] *= invSY;
  6918. matrix.elements[ 6 ] *= invSY;
  6919. matrix.elements[ 8 ] *= invSZ;
  6920. matrix.elements[ 9 ] *= invSZ;
  6921. matrix.elements[ 10 ] *= invSZ;
  6922. quaternion.setFromRotationMatrix( matrix );
  6923. scale.x = sx;
  6924. scale.y = sy;
  6925. scale.z = sz;
  6926. return this;
  6927. };
  6928. }(),
  6929. makePerspective: function ( left, right, top, bottom, near, far ) {
  6930. if ( far === undefined ) {
  6931. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  6932. }
  6933. var te = this.elements;
  6934. var x = 2 * near / ( right - left );
  6935. var y = 2 * near / ( top - bottom );
  6936. var a = ( right + left ) / ( right - left );
  6937. var b = ( top + bottom ) / ( top - bottom );
  6938. var c = - ( far + near ) / ( far - near );
  6939. var d = - 2 * far * near / ( far - near );
  6940. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  6941. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  6942. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  6943. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  6944. return this;
  6945. },
  6946. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  6947. var te = this.elements;
  6948. var w = 1.0 / ( right - left );
  6949. var h = 1.0 / ( top - bottom );
  6950. var p = 1.0 / ( far - near );
  6951. var x = ( right + left ) * w;
  6952. var y = ( top + bottom ) * h;
  6953. var z = ( far + near ) * p;
  6954. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  6955. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  6956. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  6957. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  6958. return this;
  6959. },
  6960. equals: function ( matrix ) {
  6961. var te = this.elements;
  6962. var me = matrix.elements;
  6963. for ( var i = 0; i < 16; i ++ ) {
  6964. if ( te[ i ] !== me[ i ] ) return false;
  6965. }
  6966. return true;
  6967. },
  6968. fromArray: function ( array, offset ) {
  6969. if ( offset === undefined ) offset = 0;
  6970. for ( var i = 0; i < 16; i ++ ) {
  6971. this.elements[ i ] = array[ i + offset ];
  6972. }
  6973. return this;
  6974. },
  6975. toArray: function ( array, offset ) {
  6976. if ( array === undefined ) array = [];
  6977. if ( offset === undefined ) offset = 0;
  6978. var te = this.elements;
  6979. array[ offset ] = te[ 0 ];
  6980. array[ offset + 1 ] = te[ 1 ];
  6981. array[ offset + 2 ] = te[ 2 ];
  6982. array[ offset + 3 ] = te[ 3 ];
  6983. array[ offset + 4 ] = te[ 4 ];
  6984. array[ offset + 5 ] = te[ 5 ];
  6985. array[ offset + 6 ] = te[ 6 ];
  6986. array[ offset + 7 ] = te[ 7 ];
  6987. array[ offset + 8 ] = te[ 8 ];
  6988. array[ offset + 9 ] = te[ 9 ];
  6989. array[ offset + 10 ] = te[ 10 ];
  6990. array[ offset + 11 ] = te[ 11 ];
  6991. array[ offset + 12 ] = te[ 12 ];
  6992. array[ offset + 13 ] = te[ 13 ];
  6993. array[ offset + 14 ] = te[ 14 ];
  6994. array[ offset + 15 ] = te[ 15 ];
  6995. return array;
  6996. }
  6997. } );
  6998. /**
  6999. * @author alteredq / http://alteredqualia.com/
  7000. */
  7001. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7002. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7003. this.image = { data: data, width: width, height: height };
  7004. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7005. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7006. this.generateMipmaps = false;
  7007. this.flipY = false;
  7008. this.unpackAlignment = 1;
  7009. }
  7010. DataTexture.prototype = Object.create( Texture.prototype );
  7011. DataTexture.prototype.constructor = DataTexture;
  7012. DataTexture.prototype.isDataTexture = true;
  7013. /**
  7014. * @author mrdoob / http://mrdoob.com/
  7015. */
  7016. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7017. images = images !== undefined ? images : [];
  7018. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7019. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7020. this.flipY = false;
  7021. }
  7022. CubeTexture.prototype = Object.create( Texture.prototype );
  7023. CubeTexture.prototype.constructor = CubeTexture;
  7024. CubeTexture.prototype.isCubeTexture = true;
  7025. Object.defineProperty( CubeTexture.prototype, 'images', {
  7026. get: function () {
  7027. return this.image;
  7028. },
  7029. set: function ( value ) {
  7030. this.image = value;
  7031. }
  7032. } );
  7033. /**
  7034. * @author tschw
  7035. *
  7036. * Uniforms of a program.
  7037. * Those form a tree structure with a special top-level container for the root,
  7038. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  7039. *
  7040. *
  7041. * Properties of inner nodes including the top-level container:
  7042. *
  7043. * .seq - array of nested uniforms
  7044. * .map - nested uniforms by name
  7045. *
  7046. *
  7047. * Methods of all nodes except the top-level container:
  7048. *
  7049. * .setValue( gl, value, [renderer] )
  7050. *
  7051. * uploads a uniform value(s)
  7052. * the 'renderer' parameter is needed for sampler uniforms
  7053. *
  7054. *
  7055. * Static methods of the top-level container (renderer factorizations):
  7056. *
  7057. * .upload( gl, seq, values, renderer )
  7058. *
  7059. * sets uniforms in 'seq' to 'values[id].value'
  7060. *
  7061. * .seqWithValue( seq, values ) : filteredSeq
  7062. *
  7063. * filters 'seq' entries with corresponding entry in values
  7064. *
  7065. *
  7066. * Methods of the top-level container (renderer factorizations):
  7067. *
  7068. * .setValue( gl, name, value )
  7069. *
  7070. * sets uniform with name 'name' to 'value'
  7071. *
  7072. * .set( gl, obj, prop )
  7073. *
  7074. * sets uniform from object and property with same name than uniform
  7075. *
  7076. * .setOptional( gl, obj, prop )
  7077. *
  7078. * like .set for an optional property of the object
  7079. *
  7080. */
  7081. var emptyTexture = new Texture();
  7082. var emptyCubeTexture = new CubeTexture();
  7083. // --- Base for inner nodes (including the root) ---
  7084. function UniformContainer() {
  7085. this.seq = [];
  7086. this.map = {};
  7087. }
  7088. // --- Utilities ---
  7089. // Array Caches (provide typed arrays for temporary by size)
  7090. var arrayCacheF32 = [];
  7091. var arrayCacheI32 = [];
  7092. // Float32Array caches used for uploading Matrix uniforms
  7093. var mat4array = new Float32Array( 16 );
  7094. var mat3array = new Float32Array( 9 );
  7095. // Flattening for arrays of vectors and matrices
  7096. function flatten( array, nBlocks, blockSize ) {
  7097. var firstElem = array[ 0 ];
  7098. if ( firstElem <= 0 || firstElem > 0 ) return array;
  7099. // unoptimized: ! isNaN( firstElem )
  7100. // see http://jacksondunstan.com/articles/983
  7101. var n = nBlocks * blockSize,
  7102. r = arrayCacheF32[ n ];
  7103. if ( r === undefined ) {
  7104. r = new Float32Array( n );
  7105. arrayCacheF32[ n ] = r;
  7106. }
  7107. if ( nBlocks !== 0 ) {
  7108. firstElem.toArray( r, 0 );
  7109. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  7110. offset += blockSize;
  7111. array[ i ].toArray( r, offset );
  7112. }
  7113. }
  7114. return r;
  7115. }
  7116. // Texture unit allocation
  7117. function allocTexUnits( renderer, n ) {
  7118. var r = arrayCacheI32[ n ];
  7119. if ( r === undefined ) {
  7120. r = new Int32Array( n );
  7121. arrayCacheI32[ n ] = r;
  7122. }
  7123. for ( var i = 0; i !== n; ++ i )
  7124. r[ i ] = renderer.allocTextureUnit();
  7125. return r;
  7126. }
  7127. // --- Setters ---
  7128. // Note: Defining these methods externally, because they come in a bunch
  7129. // and this way their names minify.
  7130. // Single scalar
  7131. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  7132. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  7133. // Single float vector (from flat array or THREE.VectorN)
  7134. function setValue2fv( gl, v ) {
  7135. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  7136. else gl.uniform2f( this.addr, v.x, v.y );
  7137. }
  7138. function setValue3fv( gl, v ) {
  7139. if ( v.x !== undefined )
  7140. gl.uniform3f( this.addr, v.x, v.y, v.z );
  7141. else if ( v.r !== undefined )
  7142. gl.uniform3f( this.addr, v.r, v.g, v.b );
  7143. else
  7144. gl.uniform3fv( this.addr, v );
  7145. }
  7146. function setValue4fv( gl, v ) {
  7147. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  7148. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  7149. }
  7150. // Single matrix (from flat array or MatrixN)
  7151. function setValue2fm( gl, v ) {
  7152. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  7153. }
  7154. function setValue3fm( gl, v ) {
  7155. if ( v.elements === undefined ) {
  7156. gl.uniformMatrix3fv( this.addr, false, v );
  7157. } else {
  7158. mat3array.set( v.elements );
  7159. gl.uniformMatrix3fv( this.addr, false, mat3array );
  7160. }
  7161. }
  7162. function setValue4fm( gl, v ) {
  7163. if ( v.elements === undefined ) {
  7164. gl.uniformMatrix4fv( this.addr, false, v );
  7165. } else {
  7166. mat4array.set( v.elements );
  7167. gl.uniformMatrix4fv( this.addr, false, mat4array );
  7168. }
  7169. }
  7170. // Single texture (2D / Cube)
  7171. function setValueT1( gl, v, renderer ) {
  7172. var unit = renderer.allocTextureUnit();
  7173. gl.uniform1i( this.addr, unit );
  7174. renderer.setTexture2D( v || emptyTexture, unit );
  7175. }
  7176. function setValueT6( gl, v, renderer ) {
  7177. var unit = renderer.allocTextureUnit();
  7178. gl.uniform1i( this.addr, unit );
  7179. renderer.setTextureCube( v || emptyCubeTexture, unit );
  7180. }
  7181. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  7182. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  7183. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  7184. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  7185. // Helper to pick the right setter for the singular case
  7186. function getSingularSetter( type ) {
  7187. switch ( type ) {
  7188. case 0x1406: return setValue1f; // FLOAT
  7189. case 0x8b50: return setValue2fv; // _VEC2
  7190. case 0x8b51: return setValue3fv; // _VEC3
  7191. case 0x8b52: return setValue4fv; // _VEC4
  7192. case 0x8b5a: return setValue2fm; // _MAT2
  7193. case 0x8b5b: return setValue3fm; // _MAT3
  7194. case 0x8b5c: return setValue4fm; // _MAT4
  7195. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  7196. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  7197. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  7198. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7199. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7200. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7201. }
  7202. }
  7203. // Array of scalars
  7204. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  7205. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  7206. // Array of vectors (flat or from THREE classes)
  7207. function setValueV2a( gl, v ) {
  7208. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  7209. }
  7210. function setValueV3a( gl, v ) {
  7211. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  7212. }
  7213. function setValueV4a( gl, v ) {
  7214. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  7215. }
  7216. // Array of matrices (flat or from THREE clases)
  7217. function setValueM2a( gl, v ) {
  7218. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  7219. }
  7220. function setValueM3a( gl, v ) {
  7221. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  7222. }
  7223. function setValueM4a( gl, v ) {
  7224. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  7225. }
  7226. // Array of textures (2D / Cube)
  7227. function setValueT1a( gl, v, renderer ) {
  7228. var n = v.length,
  7229. units = allocTexUnits( renderer, n );
  7230. gl.uniform1iv( this.addr, units );
  7231. for ( var i = 0; i !== n; ++ i ) {
  7232. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  7233. }
  7234. }
  7235. function setValueT6a( gl, v, renderer ) {
  7236. var n = v.length,
  7237. units = allocTexUnits( renderer, n );
  7238. gl.uniform1iv( this.addr, units );
  7239. for ( var i = 0; i !== n; ++ i ) {
  7240. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  7241. }
  7242. }
  7243. // Helper to pick the right setter for a pure (bottom-level) array
  7244. function getPureArraySetter( type ) {
  7245. switch ( type ) {
  7246. case 0x1406: return setValue1fv; // FLOAT
  7247. case 0x8b50: return setValueV2a; // _VEC2
  7248. case 0x8b51: return setValueV3a; // _VEC3
  7249. case 0x8b52: return setValueV4a; // _VEC4
  7250. case 0x8b5a: return setValueM2a; // _MAT2
  7251. case 0x8b5b: return setValueM3a; // _MAT3
  7252. case 0x8b5c: return setValueM4a; // _MAT4
  7253. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  7254. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  7255. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  7256. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7257. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7258. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7259. }
  7260. }
  7261. // --- Uniform Classes ---
  7262. function SingleUniform( id, activeInfo, addr ) {
  7263. this.id = id;
  7264. this.addr = addr;
  7265. this.setValue = getSingularSetter( activeInfo.type );
  7266. // this.path = activeInfo.name; // DEBUG
  7267. }
  7268. function PureArrayUniform( id, activeInfo, addr ) {
  7269. this.id = id;
  7270. this.addr = addr;
  7271. this.size = activeInfo.size;
  7272. this.setValue = getPureArraySetter( activeInfo.type );
  7273. // this.path = activeInfo.name; // DEBUG
  7274. }
  7275. function StructuredUniform( id ) {
  7276. this.id = id;
  7277. UniformContainer.call( this ); // mix-in
  7278. }
  7279. StructuredUniform.prototype.setValue = function ( gl, value ) {
  7280. // Note: Don't need an extra 'renderer' parameter, since samplers
  7281. // are not allowed in structured uniforms.
  7282. var seq = this.seq;
  7283. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7284. var u = seq[ i ];
  7285. u.setValue( gl, value[ u.id ] );
  7286. }
  7287. };
  7288. // --- Top-level ---
  7289. // Parser - builds up the property tree from the path strings
  7290. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  7291. // extracts
  7292. // - the identifier (member name or array index)
  7293. // - followed by an optional right bracket (found when array index)
  7294. // - followed by an optional left bracket or dot (type of subscript)
  7295. //
  7296. // Note: These portions can be read in a non-overlapping fashion and
  7297. // allow straightforward parsing of the hierarchy that WebGL encodes
  7298. // in the uniform names.
  7299. function addUniform( container, uniformObject ) {
  7300. container.seq.push( uniformObject );
  7301. container.map[ uniformObject.id ] = uniformObject;
  7302. }
  7303. function parseUniform( activeInfo, addr, container ) {
  7304. var path = activeInfo.name,
  7305. pathLength = path.length;
  7306. // reset RegExp object, because of the early exit of a previous run
  7307. RePathPart.lastIndex = 0;
  7308. for ( ; ; ) {
  7309. var match = RePathPart.exec( path ),
  7310. matchEnd = RePathPart.lastIndex,
  7311. id = match[ 1 ],
  7312. idIsIndex = match[ 2 ] === ']',
  7313. subscript = match[ 3 ];
  7314. if ( idIsIndex ) id = id | 0; // convert to integer
  7315. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  7316. // bare name or "pure" bottom-level array "[0]" suffix
  7317. addUniform( container, subscript === undefined ?
  7318. new SingleUniform( id, activeInfo, addr ) :
  7319. new PureArrayUniform( id, activeInfo, addr ) );
  7320. break;
  7321. } else {
  7322. // step into inner node / create it in case it doesn't exist
  7323. var map = container.map, next = map[ id ];
  7324. if ( next === undefined ) {
  7325. next = new StructuredUniform( id );
  7326. addUniform( container, next );
  7327. }
  7328. container = next;
  7329. }
  7330. }
  7331. }
  7332. // Root Container
  7333. function WebGLUniforms( gl, program, renderer ) {
  7334. UniformContainer.call( this );
  7335. this.renderer = renderer;
  7336. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  7337. for ( var i = 0; i < n; ++ i ) {
  7338. var info = gl.getActiveUniform( program, i ),
  7339. path = info.name,
  7340. addr = gl.getUniformLocation( program, path );
  7341. parseUniform( info, addr, this );
  7342. }
  7343. }
  7344. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  7345. var u = this.map[ name ];
  7346. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  7347. };
  7348. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  7349. var v = object[ name ];
  7350. if ( v !== undefined ) this.setValue( gl, name, v );
  7351. };
  7352. // Static interface
  7353. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  7354. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7355. var u = seq[ i ],
  7356. v = values[ u.id ];
  7357. if ( v.needsUpdate !== false ) {
  7358. // note: always updating when .needsUpdate is undefined
  7359. u.setValue( gl, v.value, renderer );
  7360. }
  7361. }
  7362. };
  7363. WebGLUniforms.seqWithValue = function ( seq, values ) {
  7364. var r = [];
  7365. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7366. var u = seq[ i ];
  7367. if ( u.id in values ) r.push( u );
  7368. }
  7369. return r;
  7370. };
  7371. /**
  7372. * @author mrdoob / http://mrdoob.com/
  7373. */
  7374. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  7375. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  7376. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  7377. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  7378. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  7379. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  7380. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  7381. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  7382. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  7383. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  7384. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  7385. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  7386. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  7387. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  7388. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  7389. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  7390. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  7391. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  7392. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  7393. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  7394. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  7395. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  7396. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  7397. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  7398. function Color( r, g, b ) {
  7399. if ( g === undefined && b === undefined ) {
  7400. // r is THREE.Color, hex or string
  7401. return this.set( r );
  7402. }
  7403. return this.setRGB( r, g, b );
  7404. }
  7405. Object.assign( Color.prototype, {
  7406. isColor: true,
  7407. r: 1, g: 1, b: 1,
  7408. set: function ( value ) {
  7409. if ( value && value.isColor ) {
  7410. this.copy( value );
  7411. } else if ( typeof value === 'number' ) {
  7412. this.setHex( value );
  7413. } else if ( typeof value === 'string' ) {
  7414. this.setStyle( value );
  7415. }
  7416. return this;
  7417. },
  7418. setScalar: function ( scalar ) {
  7419. this.r = scalar;
  7420. this.g = scalar;
  7421. this.b = scalar;
  7422. return this;
  7423. },
  7424. setHex: function ( hex ) {
  7425. hex = Math.floor( hex );
  7426. this.r = ( hex >> 16 & 255 ) / 255;
  7427. this.g = ( hex >> 8 & 255 ) / 255;
  7428. this.b = ( hex & 255 ) / 255;
  7429. return this;
  7430. },
  7431. setRGB: function ( r, g, b ) {
  7432. this.r = r;
  7433. this.g = g;
  7434. this.b = b;
  7435. return this;
  7436. },
  7437. setHSL: function () {
  7438. function hue2rgb( p, q, t ) {
  7439. if ( t < 0 ) t += 1;
  7440. if ( t > 1 ) t -= 1;
  7441. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7442. if ( t < 1 / 2 ) return q;
  7443. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7444. return p;
  7445. }
  7446. return function setHSL( h, s, l ) {
  7447. // h,s,l ranges are in 0.0 - 1.0
  7448. h = _Math.euclideanModulo( h, 1 );
  7449. s = _Math.clamp( s, 0, 1 );
  7450. l = _Math.clamp( l, 0, 1 );
  7451. if ( s === 0 ) {
  7452. this.r = this.g = this.b = l;
  7453. } else {
  7454. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7455. var q = ( 2 * l ) - p;
  7456. this.r = hue2rgb( q, p, h + 1 / 3 );
  7457. this.g = hue2rgb( q, p, h );
  7458. this.b = hue2rgb( q, p, h - 1 / 3 );
  7459. }
  7460. return this;
  7461. };
  7462. }(),
  7463. setStyle: function ( style ) {
  7464. function handleAlpha( string ) {
  7465. if ( string === undefined ) return;
  7466. if ( parseFloat( string ) < 1 ) {
  7467. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7468. }
  7469. }
  7470. var m;
  7471. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7472. // rgb / hsl
  7473. var color;
  7474. var name = m[ 1 ];
  7475. var components = m[ 2 ];
  7476. switch ( name ) {
  7477. case 'rgb':
  7478. case 'rgba':
  7479. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7480. // rgb(255,0,0) rgba(255,0,0,0.5)
  7481. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7482. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7483. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7484. handleAlpha( color[ 5 ] );
  7485. return this;
  7486. }
  7487. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7488. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7489. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7490. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7491. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7492. handleAlpha( color[ 5 ] );
  7493. return this;
  7494. }
  7495. break;
  7496. case 'hsl':
  7497. case 'hsla':
  7498. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7499. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7500. var h = parseFloat( color[ 1 ] ) / 360;
  7501. var s = parseInt( color[ 2 ], 10 ) / 100;
  7502. var l = parseInt( color[ 3 ], 10 ) / 100;
  7503. handleAlpha( color[ 5 ] );
  7504. return this.setHSL( h, s, l );
  7505. }
  7506. break;
  7507. }
  7508. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7509. // hex color
  7510. var hex = m[ 1 ];
  7511. var size = hex.length;
  7512. if ( size === 3 ) {
  7513. // #ff0
  7514. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7515. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7516. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7517. return this;
  7518. } else if ( size === 6 ) {
  7519. // #ff0000
  7520. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7521. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7522. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7523. return this;
  7524. }
  7525. }
  7526. if ( style && style.length > 0 ) {
  7527. // color keywords
  7528. var hex = ColorKeywords[ style ];
  7529. if ( hex !== undefined ) {
  7530. // red
  7531. this.setHex( hex );
  7532. } else {
  7533. // unknown color
  7534. console.warn( 'THREE.Color: Unknown color ' + style );
  7535. }
  7536. }
  7537. return this;
  7538. },
  7539. clone: function () {
  7540. return new this.constructor( this.r, this.g, this.b );
  7541. },
  7542. copy: function ( color ) {
  7543. this.r = color.r;
  7544. this.g = color.g;
  7545. this.b = color.b;
  7546. return this;
  7547. },
  7548. copyGammaToLinear: function ( color, gammaFactor ) {
  7549. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7550. this.r = Math.pow( color.r, gammaFactor );
  7551. this.g = Math.pow( color.g, gammaFactor );
  7552. this.b = Math.pow( color.b, gammaFactor );
  7553. return this;
  7554. },
  7555. copyLinearToGamma: function ( color, gammaFactor ) {
  7556. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7557. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7558. this.r = Math.pow( color.r, safeInverse );
  7559. this.g = Math.pow( color.g, safeInverse );
  7560. this.b = Math.pow( color.b, safeInverse );
  7561. return this;
  7562. },
  7563. convertGammaToLinear: function () {
  7564. var r = this.r, g = this.g, b = this.b;
  7565. this.r = r * r;
  7566. this.g = g * g;
  7567. this.b = b * b;
  7568. return this;
  7569. },
  7570. convertLinearToGamma: function () {
  7571. this.r = Math.sqrt( this.r );
  7572. this.g = Math.sqrt( this.g );
  7573. this.b = Math.sqrt( this.b );
  7574. return this;
  7575. },
  7576. getHex: function () {
  7577. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  7578. },
  7579. getHexString: function () {
  7580. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  7581. },
  7582. getHSL: function ( optionalTarget ) {
  7583. // h,s,l ranges are in 0.0 - 1.0
  7584. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  7585. var r = this.r, g = this.g, b = this.b;
  7586. var max = Math.max( r, g, b );
  7587. var min = Math.min( r, g, b );
  7588. var hue, saturation;
  7589. var lightness = ( min + max ) / 2.0;
  7590. if ( min === max ) {
  7591. hue = 0;
  7592. saturation = 0;
  7593. } else {
  7594. var delta = max - min;
  7595. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  7596. switch ( max ) {
  7597. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  7598. case g: hue = ( b - r ) / delta + 2; break;
  7599. case b: hue = ( r - g ) / delta + 4; break;
  7600. }
  7601. hue /= 6;
  7602. }
  7603. hsl.h = hue;
  7604. hsl.s = saturation;
  7605. hsl.l = lightness;
  7606. return hsl;
  7607. },
  7608. getStyle: function () {
  7609. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  7610. },
  7611. offsetHSL: function ( h, s, l ) {
  7612. var hsl = this.getHSL();
  7613. hsl.h += h; hsl.s += s; hsl.l += l;
  7614. this.setHSL( hsl.h, hsl.s, hsl.l );
  7615. return this;
  7616. },
  7617. add: function ( color ) {
  7618. this.r += color.r;
  7619. this.g += color.g;
  7620. this.b += color.b;
  7621. return this;
  7622. },
  7623. addColors: function ( color1, color2 ) {
  7624. this.r = color1.r + color2.r;
  7625. this.g = color1.g + color2.g;
  7626. this.b = color1.b + color2.b;
  7627. return this;
  7628. },
  7629. addScalar: function ( s ) {
  7630. this.r += s;
  7631. this.g += s;
  7632. this.b += s;
  7633. return this;
  7634. },
  7635. sub: function( color ) {
  7636. this.r = Math.max( 0, this.r - color.r );
  7637. this.g = Math.max( 0, this.g - color.g );
  7638. this.b = Math.max( 0, this.b - color.b );
  7639. return this;
  7640. },
  7641. multiply: function ( color ) {
  7642. this.r *= color.r;
  7643. this.g *= color.g;
  7644. this.b *= color.b;
  7645. return this;
  7646. },
  7647. multiplyScalar: function ( s ) {
  7648. this.r *= s;
  7649. this.g *= s;
  7650. this.b *= s;
  7651. return this;
  7652. },
  7653. lerp: function ( color, alpha ) {
  7654. this.r += ( color.r - this.r ) * alpha;
  7655. this.g += ( color.g - this.g ) * alpha;
  7656. this.b += ( color.b - this.b ) * alpha;
  7657. return this;
  7658. },
  7659. equals: function ( c ) {
  7660. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  7661. },
  7662. fromArray: function ( array, offset ) {
  7663. if ( offset === undefined ) offset = 0;
  7664. this.r = array[ offset ];
  7665. this.g = array[ offset + 1 ];
  7666. this.b = array[ offset + 2 ];
  7667. return this;
  7668. },
  7669. toArray: function ( array, offset ) {
  7670. if ( array === undefined ) array = [];
  7671. if ( offset === undefined ) offset = 0;
  7672. array[ offset ] = this.r;
  7673. array[ offset + 1 ] = this.g;
  7674. array[ offset + 2 ] = this.b;
  7675. return array;
  7676. },
  7677. toJSON: function () {
  7678. return this.getHex();
  7679. }
  7680. } );
  7681. /**
  7682. * Uniforms library for shared webgl shaders
  7683. */
  7684. var UniformsLib = {
  7685. common: {
  7686. diffuse: { value: new Color( 0xeeeeee ) },
  7687. opacity: { value: 1.0 },
  7688. map: { value: null },
  7689. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  7690. alphaMap: { value: null },
  7691. },
  7692. specularmap: {
  7693. specularMap: { value: null },
  7694. },
  7695. envmap: {
  7696. envMap: { value: null },
  7697. flipEnvMap: { value: - 1 },
  7698. reflectivity: { value: 1.0 },
  7699. refractionRatio: { value: 0.98 }
  7700. },
  7701. aomap: {
  7702. aoMap: { value: null },
  7703. aoMapIntensity: { value: 1 }
  7704. },
  7705. lightmap: {
  7706. lightMap: { value: null },
  7707. lightMapIntensity: { value: 1 }
  7708. },
  7709. emissivemap: {
  7710. emissiveMap: { value: null }
  7711. },
  7712. bumpmap: {
  7713. bumpMap: { value: null },
  7714. bumpScale: { value: 1 }
  7715. },
  7716. normalmap: {
  7717. normalMap: { value: null },
  7718. normalScale: { value: new Vector2( 1, 1 ) }
  7719. },
  7720. displacementmap: {
  7721. displacementMap: { value: null },
  7722. displacementScale: { value: 1 },
  7723. displacementBias: { value: 0 }
  7724. },
  7725. roughnessmap: {
  7726. roughnessMap: { value: null }
  7727. },
  7728. metalnessmap: {
  7729. metalnessMap: { value: null }
  7730. },
  7731. gradientmap: {
  7732. gradientMap: { value: null }
  7733. },
  7734. fog: {
  7735. fogDensity: { value: 0.00025 },
  7736. fogNear: { value: 1 },
  7737. fogFar: { value: 2000 },
  7738. fogColor: { value: new Color( 0xffffff ) }
  7739. },
  7740. lights: {
  7741. ambientLightColor: { value: [] },
  7742. directionalLights: { value: [], properties: {
  7743. direction: {},
  7744. color: {},
  7745. shadow: {},
  7746. shadowBias: {},
  7747. shadowRadius: {},
  7748. shadowMapSize: {}
  7749. } },
  7750. directionalShadowMap: { value: [] },
  7751. directionalShadowMatrix: { value: [] },
  7752. spotLights: { value: [], properties: {
  7753. color: {},
  7754. position: {},
  7755. direction: {},
  7756. distance: {},
  7757. coneCos: {},
  7758. penumbraCos: {},
  7759. decay: {},
  7760. shadow: {},
  7761. shadowBias: {},
  7762. shadowRadius: {},
  7763. shadowMapSize: {}
  7764. } },
  7765. spotShadowMap: { value: [] },
  7766. spotShadowMatrix: { value: [] },
  7767. pointLights: { value: [], properties: {
  7768. color: {},
  7769. position: {},
  7770. decay: {},
  7771. distance: {},
  7772. shadow: {},
  7773. shadowBias: {},
  7774. shadowRadius: {},
  7775. shadowMapSize: {},
  7776. shadowCameraNear: {},
  7777. shadowCameraFar: {}
  7778. } },
  7779. pointShadowMap: { value: [] },
  7780. pointShadowMatrix: { value: [] },
  7781. hemisphereLights: { value: [], properties: {
  7782. direction: {},
  7783. skyColor: {},
  7784. groundColor: {}
  7785. } },
  7786. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7787. rectAreaLights: { value: [], properties: {
  7788. color: {},
  7789. position: {},
  7790. width: {},
  7791. height: {}
  7792. } }
  7793. },
  7794. points: {
  7795. diffuse: { value: new Color( 0xeeeeee ) },
  7796. opacity: { value: 1.0 },
  7797. size: { value: 1.0 },
  7798. scale: { value: 1.0 },
  7799. map: { value: null },
  7800. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  7801. }
  7802. };
  7803. /**
  7804. * Uniform Utilities
  7805. */
  7806. var UniformsUtils = {
  7807. merge: function ( uniforms ) {
  7808. var merged = {};
  7809. for ( var u = 0; u < uniforms.length; u ++ ) {
  7810. var tmp = this.clone( uniforms[ u ] );
  7811. for ( var p in tmp ) {
  7812. merged[ p ] = tmp[ p ];
  7813. }
  7814. }
  7815. return merged;
  7816. },
  7817. clone: function ( uniforms_src ) {
  7818. var uniforms_dst = {};
  7819. for ( var u in uniforms_src ) {
  7820. uniforms_dst[ u ] = {};
  7821. for ( var p in uniforms_src[ u ] ) {
  7822. var parameter_src = uniforms_src[ u ][ p ];
  7823. if ( parameter_src && ( parameter_src.isColor ||
  7824. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  7825. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  7826. parameter_src.isTexture ) ) {
  7827. uniforms_dst[ u ][ p ] = parameter_src.clone();
  7828. } else if ( Array.isArray( parameter_src ) ) {
  7829. uniforms_dst[ u ][ p ] = parameter_src.slice();
  7830. } else {
  7831. uniforms_dst[ u ][ p ] = parameter_src;
  7832. }
  7833. }
  7834. }
  7835. return uniforms_dst;
  7836. }
  7837. };
  7838. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  7839. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  7840. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  7841. 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\n";
  7842. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7843. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  7844. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  7845. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\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 theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\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.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - 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 * transpose( 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\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn 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\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  7846. 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\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  7847. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";
  7848. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  7849. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  7850. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  7851. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7852. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  7853. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7854. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  7855. 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 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";
  7856. 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(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\n";
  7857. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  7858. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  7859. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  7860. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  7861. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  7862. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  7863. 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.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\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.w );\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.w );\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.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, 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.x, 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 = value.rgb * cLogLuvM;\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 = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  7864. 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\n";
  7865. 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\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\n";
  7866. 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\n";
  7867. 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\n";
  7868. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  7869. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  7870. 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\n";
  7871. 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\n";
  7872. 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\n";
  7873. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  7874. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7875. 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 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\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\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\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\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  7876. var lights_pars = "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 ltcMat;\tuniform sampler2D ltcMag;\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\n#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( 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(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\n";
  7877. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  7878. 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)\n";
  7879. 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\n";
  7880. 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\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), 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\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, 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\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\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}\n";
  7881. var lights_template = "\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\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\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\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\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#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 ( NUM_HEMI_LIGHTS > 0 )\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\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  7882. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  7883. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  7884. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  7885. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  7886. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  7887. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  7888. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  7889. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  7890. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  7891. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7892. 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\n";
  7893. 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";
  7894. 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\n";
  7895. var normal_fragment = "#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#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  7896. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  7897. 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 1.0 - 2.0 * rgb.xyz;\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}\n";
  7898. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  7899. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  7900. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  7901. 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\n";
  7902. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  7903. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7904. 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\n";
  7905. 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\n";
  7906. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\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\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\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  7907. 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\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\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\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}\n";
  7908. 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";
  7909. 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\n";
  7910. 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\n";
  7911. 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#endif\n";
  7912. 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";
  7913. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7914. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  7915. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\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}\n";
  7916. 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";
  7917. 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 vec4 offsetRepeat;\n#endif\n";
  7918. 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 = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  7919. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7920. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  7921. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  7922. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  7923. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  7924. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  7925. 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( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  7926. 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}\n";
  7927. 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}\n";
  7928. 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}\n";
  7929. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\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\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  7930. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  7931. 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}\n";
  7932. 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}\n";
  7933. 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}\n";
  7934. 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}\n";
  7935. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\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>\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#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}\n";
  7936. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\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>\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}\n";
  7937. 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>\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>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\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}\n";
  7938. 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}\n";
  7939. 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#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 <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\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>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\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}\n";
  7940. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  7941. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\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>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  7942. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\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#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 )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  7943. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_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}\n";
  7944. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_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 <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  7945. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  7946. var shadow_vert = "#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}\n";
  7947. var ShaderChunk = {
  7948. alphamap_fragment: alphamap_fragment,
  7949. alphamap_pars_fragment: alphamap_pars_fragment,
  7950. alphatest_fragment: alphatest_fragment,
  7951. aomap_fragment: aomap_fragment,
  7952. aomap_pars_fragment: aomap_pars_fragment,
  7953. begin_vertex: begin_vertex,
  7954. beginnormal_vertex: beginnormal_vertex,
  7955. bsdfs: bsdfs,
  7956. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7957. clipping_planes_fragment: clipping_planes_fragment,
  7958. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7959. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7960. clipping_planes_vertex: clipping_planes_vertex,
  7961. color_fragment: color_fragment,
  7962. color_pars_fragment: color_pars_fragment,
  7963. color_pars_vertex: color_pars_vertex,
  7964. color_vertex: color_vertex,
  7965. common: common,
  7966. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7967. defaultnormal_vertex: defaultnormal_vertex,
  7968. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7969. displacementmap_vertex: displacementmap_vertex,
  7970. emissivemap_fragment: emissivemap_fragment,
  7971. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7972. encodings_fragment: encodings_fragment,
  7973. encodings_pars_fragment: encodings_pars_fragment,
  7974. envmap_fragment: envmap_fragment,
  7975. envmap_pars_fragment: envmap_pars_fragment,
  7976. envmap_pars_vertex: envmap_pars_vertex,
  7977. envmap_vertex: envmap_vertex,
  7978. fog_vertex: fog_vertex,
  7979. fog_pars_vertex: fog_pars_vertex,
  7980. fog_fragment: fog_fragment,
  7981. fog_pars_fragment: fog_pars_fragment,
  7982. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7983. lightmap_fragment: lightmap_fragment,
  7984. lightmap_pars_fragment: lightmap_pars_fragment,
  7985. lights_lambert_vertex: lights_lambert_vertex,
  7986. lights_pars: lights_pars,
  7987. lights_phong_fragment: lights_phong_fragment,
  7988. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7989. lights_physical_fragment: lights_physical_fragment,
  7990. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7991. lights_template: lights_template,
  7992. logdepthbuf_fragment: logdepthbuf_fragment,
  7993. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7994. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7995. logdepthbuf_vertex: logdepthbuf_vertex,
  7996. map_fragment: map_fragment,
  7997. map_pars_fragment: map_pars_fragment,
  7998. map_particle_fragment: map_particle_fragment,
  7999. map_particle_pars_fragment: map_particle_pars_fragment,
  8000. metalnessmap_fragment: metalnessmap_fragment,
  8001. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8002. morphnormal_vertex: morphnormal_vertex,
  8003. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8004. morphtarget_vertex: morphtarget_vertex,
  8005. normal_fragment: normal_fragment,
  8006. normalmap_pars_fragment: normalmap_pars_fragment,
  8007. packing: packing,
  8008. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8009. project_vertex: project_vertex,
  8010. dithering_fragment: dithering_fragment,
  8011. dithering_pars_fragment: dithering_pars_fragment,
  8012. roughnessmap_fragment: roughnessmap_fragment,
  8013. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8014. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8015. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8016. shadowmap_vertex: shadowmap_vertex,
  8017. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8018. skinbase_vertex: skinbase_vertex,
  8019. skinning_pars_vertex: skinning_pars_vertex,
  8020. skinning_vertex: skinning_vertex,
  8021. skinnormal_vertex: skinnormal_vertex,
  8022. specularmap_fragment: specularmap_fragment,
  8023. specularmap_pars_fragment: specularmap_pars_fragment,
  8024. tonemapping_fragment: tonemapping_fragment,
  8025. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8026. uv_pars_fragment: uv_pars_fragment,
  8027. uv_pars_vertex: uv_pars_vertex,
  8028. uv_vertex: uv_vertex,
  8029. uv2_pars_fragment: uv2_pars_fragment,
  8030. uv2_pars_vertex: uv2_pars_vertex,
  8031. uv2_vertex: uv2_vertex,
  8032. worldpos_vertex: worldpos_vertex,
  8033. cube_frag: cube_frag,
  8034. cube_vert: cube_vert,
  8035. depth_frag: depth_frag,
  8036. depth_vert: depth_vert,
  8037. distanceRGBA_frag: distanceRGBA_frag,
  8038. distanceRGBA_vert: distanceRGBA_vert,
  8039. equirect_frag: equirect_frag,
  8040. equirect_vert: equirect_vert,
  8041. linedashed_frag: linedashed_frag,
  8042. linedashed_vert: linedashed_vert,
  8043. meshbasic_frag: meshbasic_frag,
  8044. meshbasic_vert: meshbasic_vert,
  8045. meshlambert_frag: meshlambert_frag,
  8046. meshlambert_vert: meshlambert_vert,
  8047. meshphong_frag: meshphong_frag,
  8048. meshphong_vert: meshphong_vert,
  8049. meshphysical_frag: meshphysical_frag,
  8050. meshphysical_vert: meshphysical_vert,
  8051. normal_frag: normal_frag,
  8052. normal_vert: normal_vert,
  8053. points_frag: points_frag,
  8054. points_vert: points_vert,
  8055. shadow_frag: shadow_frag,
  8056. shadow_vert: shadow_vert
  8057. };
  8058. /**
  8059. * @author alteredq / http://alteredqualia.com/
  8060. * @author mrdoob / http://mrdoob.com/
  8061. * @author mikael emtinger / http://gomo.se/
  8062. */
  8063. var ShaderLib = {
  8064. basic: {
  8065. uniforms: UniformsUtils.merge( [
  8066. UniformsLib.common,
  8067. UniformsLib.specularmap,
  8068. UniformsLib.envmap,
  8069. UniformsLib.aomap,
  8070. UniformsLib.lightmap,
  8071. UniformsLib.fog
  8072. ] ),
  8073. vertexShader: ShaderChunk.meshbasic_vert,
  8074. fragmentShader: ShaderChunk.meshbasic_frag
  8075. },
  8076. lambert: {
  8077. uniforms: UniformsUtils.merge( [
  8078. UniformsLib.common,
  8079. UniformsLib.specularmap,
  8080. UniformsLib.envmap,
  8081. UniformsLib.aomap,
  8082. UniformsLib.lightmap,
  8083. UniformsLib.emissivemap,
  8084. UniformsLib.fog,
  8085. UniformsLib.lights,
  8086. {
  8087. emissive: { value: new Color( 0x000000 ) }
  8088. }
  8089. ] ),
  8090. vertexShader: ShaderChunk.meshlambert_vert,
  8091. fragmentShader: ShaderChunk.meshlambert_frag
  8092. },
  8093. phong: {
  8094. uniforms: UniformsUtils.merge( [
  8095. UniformsLib.common,
  8096. UniformsLib.specularmap,
  8097. UniformsLib.envmap,
  8098. UniformsLib.aomap,
  8099. UniformsLib.lightmap,
  8100. UniformsLib.emissivemap,
  8101. UniformsLib.bumpmap,
  8102. UniformsLib.normalmap,
  8103. UniformsLib.displacementmap,
  8104. UniformsLib.gradientmap,
  8105. UniformsLib.fog,
  8106. UniformsLib.lights,
  8107. {
  8108. emissive: { value: new Color( 0x000000 ) },
  8109. specular: { value: new Color( 0x111111 ) },
  8110. shininess: { value: 30 }
  8111. }
  8112. ] ),
  8113. vertexShader: ShaderChunk.meshphong_vert,
  8114. fragmentShader: ShaderChunk.meshphong_frag
  8115. },
  8116. standard: {
  8117. uniforms: UniformsUtils.merge( [
  8118. UniformsLib.common,
  8119. UniformsLib.envmap,
  8120. UniformsLib.aomap,
  8121. UniformsLib.lightmap,
  8122. UniformsLib.emissivemap,
  8123. UniformsLib.bumpmap,
  8124. UniformsLib.normalmap,
  8125. UniformsLib.displacementmap,
  8126. UniformsLib.roughnessmap,
  8127. UniformsLib.metalnessmap,
  8128. UniformsLib.fog,
  8129. UniformsLib.lights,
  8130. {
  8131. emissive: { value: new Color( 0x000000 ) },
  8132. roughness: { value: 0.5 },
  8133. metalness: { value: 0.5 },
  8134. envMapIntensity: { value: 1 } // temporary
  8135. }
  8136. ] ),
  8137. vertexShader: ShaderChunk.meshphysical_vert,
  8138. fragmentShader: ShaderChunk.meshphysical_frag
  8139. },
  8140. points: {
  8141. uniforms: UniformsUtils.merge( [
  8142. UniformsLib.points,
  8143. UniformsLib.fog
  8144. ] ),
  8145. vertexShader: ShaderChunk.points_vert,
  8146. fragmentShader: ShaderChunk.points_frag
  8147. },
  8148. dashed: {
  8149. uniforms: UniformsUtils.merge( [
  8150. UniformsLib.common,
  8151. UniformsLib.fog,
  8152. {
  8153. scale: { value: 1 },
  8154. dashSize: { value: 1 },
  8155. totalSize: { value: 2 }
  8156. }
  8157. ] ),
  8158. vertexShader: ShaderChunk.linedashed_vert,
  8159. fragmentShader: ShaderChunk.linedashed_frag
  8160. },
  8161. depth: {
  8162. uniforms: UniformsUtils.merge( [
  8163. UniformsLib.common,
  8164. UniformsLib.displacementmap
  8165. ] ),
  8166. vertexShader: ShaderChunk.depth_vert,
  8167. fragmentShader: ShaderChunk.depth_frag
  8168. },
  8169. normal: {
  8170. uniforms: UniformsUtils.merge( [
  8171. UniformsLib.common,
  8172. UniformsLib.bumpmap,
  8173. UniformsLib.normalmap,
  8174. UniformsLib.displacementmap,
  8175. {
  8176. opacity: { value: 1.0 }
  8177. }
  8178. ] ),
  8179. vertexShader: ShaderChunk.normal_vert,
  8180. fragmentShader: ShaderChunk.normal_frag
  8181. },
  8182. /* -------------------------------------------------------------------------
  8183. // Cube map shader
  8184. ------------------------------------------------------------------------- */
  8185. cube: {
  8186. uniforms: {
  8187. tCube: { value: null },
  8188. tFlip: { value: - 1 },
  8189. opacity: { value: 1.0 }
  8190. },
  8191. vertexShader: ShaderChunk.cube_vert,
  8192. fragmentShader: ShaderChunk.cube_frag
  8193. },
  8194. equirect: {
  8195. uniforms: {
  8196. tEquirect: { value: null },
  8197. },
  8198. vertexShader: ShaderChunk.equirect_vert,
  8199. fragmentShader: ShaderChunk.equirect_frag
  8200. },
  8201. distanceRGBA: {
  8202. uniforms: UniformsUtils.merge( [
  8203. UniformsLib.common,
  8204. UniformsLib.displacementmap,
  8205. {
  8206. referencePosition: { value: new Vector3() },
  8207. nearDistance: { value: 1 },
  8208. farDistance: { value: 1000 }
  8209. }
  8210. ] ),
  8211. vertexShader: ShaderChunk.distanceRGBA_vert,
  8212. fragmentShader: ShaderChunk.distanceRGBA_frag
  8213. },
  8214. shadow: {
  8215. uniforms: UniformsUtils.merge( [
  8216. UniformsLib.lights,
  8217. {
  8218. color: { value: new Color( 0x00000 ) },
  8219. opacity: { value: 1.0 }
  8220. },
  8221. ] ),
  8222. vertexShader: ShaderChunk.shadow_vert,
  8223. fragmentShader: ShaderChunk.shadow_frag
  8224. }
  8225. };
  8226. ShaderLib.physical = {
  8227. uniforms: UniformsUtils.merge( [
  8228. ShaderLib.standard.uniforms,
  8229. {
  8230. clearCoat: { value: 0 },
  8231. clearCoatRoughness: { value: 0 }
  8232. }
  8233. ] ),
  8234. vertexShader: ShaderChunk.meshphysical_vert,
  8235. fragmentShader: ShaderChunk.meshphysical_frag
  8236. };
  8237. /**
  8238. * @author bhouston / http://clara.io
  8239. */
  8240. function Box2( min, max ) {
  8241. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  8242. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  8243. }
  8244. Object.assign( Box2.prototype, {
  8245. set: function ( min, max ) {
  8246. this.min.copy( min );
  8247. this.max.copy( max );
  8248. return this;
  8249. },
  8250. setFromPoints: function ( points ) {
  8251. this.makeEmpty();
  8252. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8253. this.expandByPoint( points[ i ] );
  8254. }
  8255. return this;
  8256. },
  8257. setFromCenterAndSize: function () {
  8258. var v1 = new Vector2();
  8259. return function setFromCenterAndSize( center, size ) {
  8260. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  8261. this.min.copy( center ).sub( halfSize );
  8262. this.max.copy( center ).add( halfSize );
  8263. return this;
  8264. };
  8265. }(),
  8266. clone: function () {
  8267. return new this.constructor().copy( this );
  8268. },
  8269. copy: function ( box ) {
  8270. this.min.copy( box.min );
  8271. this.max.copy( box.max );
  8272. return this;
  8273. },
  8274. makeEmpty: function () {
  8275. this.min.x = this.min.y = + Infinity;
  8276. this.max.x = this.max.y = - Infinity;
  8277. return this;
  8278. },
  8279. isEmpty: function () {
  8280. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8281. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  8282. },
  8283. getCenter: function ( optionalTarget ) {
  8284. var result = optionalTarget || new Vector2();
  8285. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  8286. },
  8287. getSize: function ( optionalTarget ) {
  8288. var result = optionalTarget || new Vector2();
  8289. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  8290. },
  8291. expandByPoint: function ( point ) {
  8292. this.min.min( point );
  8293. this.max.max( point );
  8294. return this;
  8295. },
  8296. expandByVector: function ( vector ) {
  8297. this.min.sub( vector );
  8298. this.max.add( vector );
  8299. return this;
  8300. },
  8301. expandByScalar: function ( scalar ) {
  8302. this.min.addScalar( - scalar );
  8303. this.max.addScalar( scalar );
  8304. return this;
  8305. },
  8306. containsPoint: function ( point ) {
  8307. return point.x < this.min.x || point.x > this.max.x ||
  8308. point.y < this.min.y || point.y > this.max.y ? false : true;
  8309. },
  8310. containsBox: function ( box ) {
  8311. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  8312. this.min.y <= box.min.y && box.max.y <= this.max.y;
  8313. },
  8314. getParameter: function ( point, optionalTarget ) {
  8315. // This can potentially have a divide by zero if the box
  8316. // has a size dimension of 0.
  8317. var result = optionalTarget || new Vector2();
  8318. return result.set(
  8319. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  8320. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  8321. );
  8322. },
  8323. intersectsBox: function ( box ) {
  8324. // using 4 splitting planes to rule out intersections
  8325. return box.max.x < this.min.x || box.min.x > this.max.x ||
  8326. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  8327. },
  8328. clampPoint: function ( point, optionalTarget ) {
  8329. var result = optionalTarget || new Vector2();
  8330. return result.copy( point ).clamp( this.min, this.max );
  8331. },
  8332. distanceToPoint: function () {
  8333. var v1 = new Vector2();
  8334. return function distanceToPoint( point ) {
  8335. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  8336. return clampedPoint.sub( point ).length();
  8337. };
  8338. }(),
  8339. intersect: function ( box ) {
  8340. this.min.max( box.min );
  8341. this.max.min( box.max );
  8342. return this;
  8343. },
  8344. union: function ( box ) {
  8345. this.min.min( box.min );
  8346. this.max.max( box.max );
  8347. return this;
  8348. },
  8349. translate: function ( offset ) {
  8350. this.min.add( offset );
  8351. this.max.add( offset );
  8352. return this;
  8353. },
  8354. equals: function ( box ) {
  8355. return box.min.equals( this.min ) && box.max.equals( this.max );
  8356. }
  8357. } );
  8358. /**
  8359. * @author mikael emtinger / http://gomo.se/
  8360. * @author alteredq / http://alteredqualia.com/
  8361. */
  8362. function WebGLFlareRenderer( renderer, gl, state, textures, capabilities ) {
  8363. var vertexBuffer, elementBuffer;
  8364. var shader, program, attributes, uniforms;
  8365. var tempTexture, occlusionTexture;
  8366. function init() {
  8367. var vertices = new Float32Array( [
  8368. - 1, - 1, 0, 0,
  8369. 1, - 1, 1, 0,
  8370. 1, 1, 1, 1,
  8371. - 1, 1, 0, 1
  8372. ] );
  8373. var faces = new Uint16Array( [
  8374. 0, 1, 2,
  8375. 0, 2, 3
  8376. ] );
  8377. // buffers
  8378. vertexBuffer = gl.createBuffer();
  8379. elementBuffer = gl.createBuffer();
  8380. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8381. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8382. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8383. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8384. // textures
  8385. tempTexture = gl.createTexture();
  8386. occlusionTexture = gl.createTexture();
  8387. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8388. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  8389. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8390. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8391. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8392. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8393. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8394. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  8395. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8396. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8397. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8398. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8399. shader = {
  8400. vertexShader: [
  8401. "uniform lowp int renderType;",
  8402. "uniform vec3 screenPosition;",
  8403. "uniform vec2 scale;",
  8404. "uniform float rotation;",
  8405. "uniform sampler2D occlusionMap;",
  8406. "attribute vec2 position;",
  8407. "attribute vec2 uv;",
  8408. "varying vec2 vUV;",
  8409. "varying float vVisibility;",
  8410. "void main() {",
  8411. "vUV = uv;",
  8412. "vec2 pos = position;",
  8413. "if ( renderType == 2 ) {",
  8414. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  8415. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  8416. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  8417. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  8418. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  8419. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  8420. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  8421. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  8422. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  8423. "vVisibility = visibility.r / 9.0;",
  8424. "vVisibility *= 1.0 - visibility.g / 9.0;",
  8425. "vVisibility *= visibility.b / 9.0;",
  8426. "vVisibility *= 1.0 - visibility.a / 9.0;",
  8427. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  8428. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  8429. "}",
  8430. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  8431. "}"
  8432. ].join( "\n" ),
  8433. fragmentShader: [
  8434. "uniform lowp int renderType;",
  8435. "uniform sampler2D map;",
  8436. "uniform float opacity;",
  8437. "uniform vec3 color;",
  8438. "varying vec2 vUV;",
  8439. "varying float vVisibility;",
  8440. "void main() {",
  8441. // pink square
  8442. "if ( renderType == 0 ) {",
  8443. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  8444. // restore
  8445. "} else if ( renderType == 1 ) {",
  8446. "gl_FragColor = texture2D( map, vUV );",
  8447. // flare
  8448. "} else {",
  8449. "vec4 texture = texture2D( map, vUV );",
  8450. "texture.a *= opacity * vVisibility;",
  8451. "gl_FragColor = texture;",
  8452. "gl_FragColor.rgb *= color;",
  8453. "}",
  8454. "}"
  8455. ].join( "\n" )
  8456. };
  8457. program = createProgram( shader );
  8458. attributes = {
  8459. vertex: gl.getAttribLocation ( program, "position" ),
  8460. uv: gl.getAttribLocation ( program, "uv" )
  8461. };
  8462. uniforms = {
  8463. renderType: gl.getUniformLocation( program, "renderType" ),
  8464. map: gl.getUniformLocation( program, "map" ),
  8465. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  8466. opacity: gl.getUniformLocation( program, "opacity" ),
  8467. color: gl.getUniformLocation( program, "color" ),
  8468. scale: gl.getUniformLocation( program, "scale" ),
  8469. rotation: gl.getUniformLocation( program, "rotation" ),
  8470. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  8471. };
  8472. }
  8473. /*
  8474. * Render lens flares
  8475. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  8476. * reads these back and calculates occlusion.
  8477. */
  8478. this.render = function ( flares, scene, camera, viewport ) {
  8479. if ( flares.length === 0 ) return;
  8480. var tempPosition = new Vector3();
  8481. var invAspect = viewport.w / viewport.z,
  8482. halfViewportWidth = viewport.z * 0.5,
  8483. halfViewportHeight = viewport.w * 0.5;
  8484. var size = 16 / viewport.w,
  8485. scale = new Vector2( size * invAspect, size );
  8486. var screenPosition = new Vector3( 1, 1, 0 ),
  8487. screenPositionPixels = new Vector2( 1, 1 );
  8488. var validArea = new Box2();
  8489. validArea.min.set( viewport.x, viewport.y );
  8490. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  8491. if ( program === undefined ) {
  8492. init();
  8493. }
  8494. state.useProgram( program );
  8495. state.initAttributes();
  8496. state.enableAttribute( attributes.vertex );
  8497. state.enableAttribute( attributes.uv );
  8498. state.disableUnusedAttributes();
  8499. // loop through all lens flares to update their occlusion and positions
  8500. // setup gl and common used attribs/uniforms
  8501. gl.uniform1i( uniforms.occlusionMap, 0 );
  8502. gl.uniform1i( uniforms.map, 1 );
  8503. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8504. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  8505. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8506. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8507. state.disable( gl.CULL_FACE );
  8508. state.buffers.depth.setMask( false );
  8509. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  8510. size = 16 / viewport.w;
  8511. scale.set( size * invAspect, size );
  8512. // calc object screen position
  8513. var flare = flares[ i ];
  8514. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  8515. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  8516. tempPosition.applyMatrix4( camera.projectionMatrix );
  8517. // setup arrays for gl programs
  8518. screenPosition.copy( tempPosition );
  8519. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  8520. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  8521. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  8522. // screen cull
  8523. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  8524. // save current RGB to temp texture
  8525. state.activeTexture( gl.TEXTURE0 );
  8526. state.bindTexture( gl.TEXTURE_2D, null );
  8527. state.activeTexture( gl.TEXTURE1 );
  8528. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8529. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8530. // render pink quad
  8531. gl.uniform1i( uniforms.renderType, 0 );
  8532. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8533. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8534. state.disable( gl.BLEND );
  8535. state.enable( gl.DEPTH_TEST );
  8536. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8537. // copy result to occlusionMap
  8538. state.activeTexture( gl.TEXTURE0 );
  8539. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8540. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8541. // restore graphics
  8542. gl.uniform1i( uniforms.renderType, 1 );
  8543. state.disable( gl.DEPTH_TEST );
  8544. state.activeTexture( gl.TEXTURE1 );
  8545. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8546. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8547. // update object positions
  8548. flare.positionScreen.copy( screenPosition );
  8549. if ( flare.customUpdateCallback ) {
  8550. flare.customUpdateCallback( flare );
  8551. } else {
  8552. flare.updateLensFlares();
  8553. }
  8554. // render flares
  8555. gl.uniform1i( uniforms.renderType, 2 );
  8556. state.enable( gl.BLEND );
  8557. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  8558. var sprite = flare.lensFlares[ j ];
  8559. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  8560. screenPosition.x = sprite.x;
  8561. screenPosition.y = sprite.y;
  8562. screenPosition.z = sprite.z;
  8563. size = sprite.size * sprite.scale / viewport.w;
  8564. scale.x = size * invAspect;
  8565. scale.y = size;
  8566. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8567. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8568. gl.uniform1f( uniforms.rotation, sprite.rotation );
  8569. gl.uniform1f( uniforms.opacity, sprite.opacity );
  8570. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  8571. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  8572. textures.setTexture2D( sprite.texture, 1 );
  8573. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8574. }
  8575. }
  8576. }
  8577. }
  8578. // restore gl
  8579. state.enable( gl.CULL_FACE );
  8580. state.enable( gl.DEPTH_TEST );
  8581. state.buffers.depth.setMask( true );
  8582. state.reset();
  8583. };
  8584. function createProgram( shader ) {
  8585. var program = gl.createProgram();
  8586. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8587. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8588. var prefix = "precision " + capabilities.precision + " float;\n";
  8589. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  8590. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  8591. gl.compileShader( fragmentShader );
  8592. gl.compileShader( vertexShader );
  8593. gl.attachShader( program, fragmentShader );
  8594. gl.attachShader( program, vertexShader );
  8595. gl.linkProgram( program );
  8596. return program;
  8597. }
  8598. }
  8599. /**
  8600. * @author mrdoob / http://mrdoob.com/
  8601. */
  8602. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8603. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8604. this.needsUpdate = true;
  8605. }
  8606. CanvasTexture.prototype = Object.create( Texture.prototype );
  8607. CanvasTexture.prototype.constructor = CanvasTexture;
  8608. /**
  8609. * @author mikael emtinger / http://gomo.se/
  8610. * @author alteredq / http://alteredqualia.com/
  8611. */
  8612. function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) {
  8613. var vertexBuffer, elementBuffer;
  8614. var program, attributes, uniforms;
  8615. var texture;
  8616. // decompose matrixWorld
  8617. var spritePosition = new Vector3();
  8618. var spriteRotation = new Quaternion();
  8619. var spriteScale = new Vector3();
  8620. function init() {
  8621. var vertices = new Float32Array( [
  8622. - 0.5, - 0.5, 0, 0,
  8623. 0.5, - 0.5, 1, 0,
  8624. 0.5, 0.5, 1, 1,
  8625. - 0.5, 0.5, 0, 1
  8626. ] );
  8627. var faces = new Uint16Array( [
  8628. 0, 1, 2,
  8629. 0, 2, 3
  8630. ] );
  8631. vertexBuffer = gl.createBuffer();
  8632. elementBuffer = gl.createBuffer();
  8633. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8634. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8635. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8636. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8637. program = createProgram();
  8638. attributes = {
  8639. position: gl.getAttribLocation ( program, 'position' ),
  8640. uv: gl.getAttribLocation ( program, 'uv' )
  8641. };
  8642. uniforms = {
  8643. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  8644. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  8645. rotation: gl.getUniformLocation( program, 'rotation' ),
  8646. scale: gl.getUniformLocation( program, 'scale' ),
  8647. color: gl.getUniformLocation( program, 'color' ),
  8648. map: gl.getUniformLocation( program, 'map' ),
  8649. opacity: gl.getUniformLocation( program, 'opacity' ),
  8650. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  8651. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  8652. fogType: gl.getUniformLocation( program, 'fogType' ),
  8653. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  8654. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  8655. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  8656. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  8657. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  8658. };
  8659. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  8660. canvas.width = 8;
  8661. canvas.height = 8;
  8662. var context = canvas.getContext( '2d' );
  8663. context.fillStyle = 'white';
  8664. context.fillRect( 0, 0, 8, 8 );
  8665. texture = new CanvasTexture( canvas );
  8666. }
  8667. this.render = function ( sprites, scene, camera ) {
  8668. if ( sprites.length === 0 ) return;
  8669. // setup gl
  8670. if ( program === undefined ) {
  8671. init();
  8672. }
  8673. state.useProgram( program );
  8674. state.initAttributes();
  8675. state.enableAttribute( attributes.position );
  8676. state.enableAttribute( attributes.uv );
  8677. state.disableUnusedAttributes();
  8678. state.disable( gl.CULL_FACE );
  8679. state.enable( gl.BLEND );
  8680. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8681. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  8682. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8683. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8684. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  8685. state.activeTexture( gl.TEXTURE0 );
  8686. gl.uniform1i( uniforms.map, 0 );
  8687. var oldFogType = 0;
  8688. var sceneFogType = 0;
  8689. var fog = scene.fog;
  8690. if ( fog ) {
  8691. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  8692. if ( fog.isFog ) {
  8693. gl.uniform1f( uniforms.fogNear, fog.near );
  8694. gl.uniform1f( uniforms.fogFar, fog.far );
  8695. gl.uniform1i( uniforms.fogType, 1 );
  8696. oldFogType = 1;
  8697. sceneFogType = 1;
  8698. } else if ( fog.isFogExp2 ) {
  8699. gl.uniform1f( uniforms.fogDensity, fog.density );
  8700. gl.uniform1i( uniforms.fogType, 2 );
  8701. oldFogType = 2;
  8702. sceneFogType = 2;
  8703. }
  8704. } else {
  8705. gl.uniform1i( uniforms.fogType, 0 );
  8706. oldFogType = 0;
  8707. sceneFogType = 0;
  8708. }
  8709. // update positions and sort
  8710. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8711. var sprite = sprites[ i ];
  8712. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  8713. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  8714. }
  8715. sprites.sort( painterSortStable );
  8716. // render all sprites
  8717. var scale = [];
  8718. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8719. var sprite = sprites[ i ];
  8720. var material = sprite.material;
  8721. if ( material.visible === false ) continue;
  8722. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  8723. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  8724. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  8725. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  8726. scale[ 0 ] = spriteScale.x;
  8727. scale[ 1 ] = spriteScale.y;
  8728. var fogType = 0;
  8729. if ( scene.fog && material.fog ) {
  8730. fogType = sceneFogType;
  8731. }
  8732. if ( oldFogType !== fogType ) {
  8733. gl.uniform1i( uniforms.fogType, fogType );
  8734. oldFogType = fogType;
  8735. }
  8736. if ( material.map !== null ) {
  8737. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  8738. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  8739. } else {
  8740. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  8741. gl.uniform2f( uniforms.uvScale, 1, 1 );
  8742. }
  8743. gl.uniform1f( uniforms.opacity, material.opacity );
  8744. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  8745. gl.uniform1f( uniforms.rotation, material.rotation );
  8746. gl.uniform2fv( uniforms.scale, scale );
  8747. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  8748. state.buffers.depth.setTest( material.depthTest );
  8749. state.buffers.depth.setMask( material.depthWrite );
  8750. textures.setTexture2D( material.map || texture, 0 );
  8751. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8752. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  8753. }
  8754. // restore gl
  8755. state.enable( gl.CULL_FACE );
  8756. state.reset();
  8757. };
  8758. function createProgram() {
  8759. var program = gl.createProgram();
  8760. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8761. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8762. gl.shaderSource( vertexShader, [
  8763. 'precision ' + capabilities.precision + ' float;',
  8764. '#define SHADER_NAME ' + 'SpriteMaterial',
  8765. 'uniform mat4 modelViewMatrix;',
  8766. 'uniform mat4 projectionMatrix;',
  8767. 'uniform float rotation;',
  8768. 'uniform vec2 scale;',
  8769. 'uniform vec2 uvOffset;',
  8770. 'uniform vec2 uvScale;',
  8771. 'attribute vec2 position;',
  8772. 'attribute vec2 uv;',
  8773. 'varying vec2 vUV;',
  8774. 'void main() {',
  8775. 'vUV = uvOffset + uv * uvScale;',
  8776. 'vec2 alignedPosition = position * scale;',
  8777. 'vec2 rotatedPosition;',
  8778. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  8779. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  8780. 'vec4 finalPosition;',
  8781. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  8782. 'finalPosition.xy += rotatedPosition;',
  8783. 'finalPosition = projectionMatrix * finalPosition;',
  8784. 'gl_Position = finalPosition;',
  8785. '}'
  8786. ].join( '\n' ) );
  8787. gl.shaderSource( fragmentShader, [
  8788. 'precision ' + capabilities.precision + ' float;',
  8789. '#define SHADER_NAME ' + 'SpriteMaterial',
  8790. 'uniform vec3 color;',
  8791. 'uniform sampler2D map;',
  8792. 'uniform float opacity;',
  8793. 'uniform int fogType;',
  8794. 'uniform vec3 fogColor;',
  8795. 'uniform float fogDensity;',
  8796. 'uniform float fogNear;',
  8797. 'uniform float fogFar;',
  8798. 'uniform float alphaTest;',
  8799. 'varying vec2 vUV;',
  8800. 'void main() {',
  8801. 'vec4 texture = texture2D( map, vUV );',
  8802. 'if ( texture.a < alphaTest ) discard;',
  8803. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  8804. 'if ( fogType > 0 ) {',
  8805. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  8806. 'float fogFactor = 0.0;',
  8807. 'if ( fogType == 1 ) {',
  8808. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  8809. '} else {',
  8810. 'const float LOG2 = 1.442695;',
  8811. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  8812. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  8813. '}',
  8814. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  8815. '}',
  8816. '}'
  8817. ].join( '\n' ) );
  8818. gl.compileShader( vertexShader );
  8819. gl.compileShader( fragmentShader );
  8820. gl.attachShader( program, vertexShader );
  8821. gl.attachShader( program, fragmentShader );
  8822. gl.linkProgram( program );
  8823. return program;
  8824. }
  8825. function painterSortStable( a, b ) {
  8826. if ( a.renderOrder !== b.renderOrder ) {
  8827. return a.renderOrder - b.renderOrder;
  8828. } else if ( a.z !== b.z ) {
  8829. return b.z - a.z;
  8830. } else {
  8831. return b.id - a.id;
  8832. }
  8833. }
  8834. }
  8835. /**
  8836. * @author mrdoob / http://mrdoob.com/
  8837. * @author alteredq / http://alteredqualia.com/
  8838. */
  8839. var materialId = 0;
  8840. function Material() {
  8841. Object.defineProperty( this, 'id', { value: materialId ++ } );
  8842. this.uuid = _Math.generateUUID();
  8843. this.name = '';
  8844. this.type = 'Material';
  8845. this.fog = true;
  8846. this.lights = true;
  8847. this.blending = NormalBlending;
  8848. this.side = FrontSide;
  8849. this.flatShading = false;
  8850. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  8851. this.opacity = 1;
  8852. this.transparent = false;
  8853. this.blendSrc = SrcAlphaFactor;
  8854. this.blendDst = OneMinusSrcAlphaFactor;
  8855. this.blendEquation = AddEquation;
  8856. this.blendSrcAlpha = null;
  8857. this.blendDstAlpha = null;
  8858. this.blendEquationAlpha = null;
  8859. this.depthFunc = LessEqualDepth;
  8860. this.depthTest = true;
  8861. this.depthWrite = true;
  8862. this.clippingPlanes = null;
  8863. this.clipIntersection = false;
  8864. this.clipShadows = false;
  8865. this.colorWrite = true;
  8866. this.precision = null; // override the renderer's default precision for this material
  8867. this.polygonOffset = false;
  8868. this.polygonOffsetFactor = 0;
  8869. this.polygonOffsetUnits = 0;
  8870. this.dithering = false;
  8871. this.alphaTest = 0;
  8872. this.premultipliedAlpha = false;
  8873. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8874. this.visible = true;
  8875. this.userData = {};
  8876. this.needsUpdate = true;
  8877. }
  8878. Object.assign( Material.prototype, EventDispatcher.prototype, {
  8879. isMaterial: true,
  8880. onBeforeCompile: function () {},
  8881. setValues: function ( values ) {
  8882. if ( values === undefined ) return;
  8883. for ( var key in values ) {
  8884. var newValue = values[ key ];
  8885. if ( newValue === undefined ) {
  8886. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  8887. continue;
  8888. }
  8889. // for backward compatability if shading is set in the constructor
  8890. if ( key === 'shading' ) {
  8891. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  8892. this.flatShading = ( newValue === FlatShading ) ? true : false;
  8893. continue;
  8894. }
  8895. var currentValue = this[ key ];
  8896. if ( currentValue === undefined ) {
  8897. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  8898. continue;
  8899. }
  8900. if ( currentValue && currentValue.isColor ) {
  8901. currentValue.set( newValue );
  8902. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  8903. currentValue.copy( newValue );
  8904. } else if ( key === 'overdraw' ) {
  8905. // ensure overdraw is backwards-compatible with legacy boolean type
  8906. this[ key ] = Number( newValue );
  8907. } else {
  8908. this[ key ] = newValue;
  8909. }
  8910. }
  8911. },
  8912. toJSON: function ( meta ) {
  8913. var isRoot = meta === undefined;
  8914. if ( isRoot ) {
  8915. meta = {
  8916. textures: {},
  8917. images: {}
  8918. };
  8919. }
  8920. var data = {
  8921. metadata: {
  8922. version: 4.5,
  8923. type: 'Material',
  8924. generator: 'Material.toJSON'
  8925. }
  8926. };
  8927. // standard Material serialization
  8928. data.uuid = this.uuid;
  8929. data.type = this.type;
  8930. if ( this.name !== '' ) data.name = this.name;
  8931. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  8932. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  8933. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  8934. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  8935. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  8936. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  8937. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  8938. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  8939. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  8940. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  8941. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  8942. if ( this.bumpMap && this.bumpMap.isTexture ) {
  8943. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  8944. data.bumpScale = this.bumpScale;
  8945. }
  8946. if ( this.normalMap && this.normalMap.isTexture ) {
  8947. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  8948. data.normalScale = this.normalScale.toArray();
  8949. }
  8950. if ( this.displacementMap && this.displacementMap.isTexture ) {
  8951. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  8952. data.displacementScale = this.displacementScale;
  8953. data.displacementBias = this.displacementBias;
  8954. }
  8955. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  8956. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  8957. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  8958. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  8959. if ( this.envMap && this.envMap.isTexture ) {
  8960. data.envMap = this.envMap.toJSON( meta ).uuid;
  8961. data.reflectivity = this.reflectivity; // Scale behind envMap
  8962. }
  8963. if ( this.gradientMap && this.gradientMap.isTexture ) {
  8964. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  8965. }
  8966. if ( this.size !== undefined ) data.size = this.size;
  8967. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  8968. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  8969. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  8970. if ( this.side !== FrontSide ) data.side = this.side;
  8971. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  8972. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8973. if ( this.transparent === true ) data.transparent = this.transparent;
  8974. data.depthFunc = this.depthFunc;
  8975. data.depthTest = this.depthTest;
  8976. data.depthWrite = this.depthWrite;
  8977. if ( this.dithering === true ) data.dithering = true;
  8978. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  8979. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  8980. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  8981. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  8982. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  8983. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  8984. if ( this.morphTargets === true ) data.morphTargets = true;
  8985. if ( this.skinning === true ) data.skinning = true;
  8986. if ( this.visible === false ) data.visible = false;
  8987. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  8988. // TODO: Copied from Object3D.toJSON
  8989. function extractFromCache( cache ) {
  8990. var values = [];
  8991. for ( var key in cache ) {
  8992. var data = cache[ key ];
  8993. delete data.metadata;
  8994. values.push( data );
  8995. }
  8996. return values;
  8997. }
  8998. if ( isRoot ) {
  8999. var textures = extractFromCache( meta.textures );
  9000. var images = extractFromCache( meta.images );
  9001. if ( textures.length > 0 ) data.textures = textures;
  9002. if ( images.length > 0 ) data.images = images;
  9003. }
  9004. return data;
  9005. },
  9006. clone: function () {
  9007. return new this.constructor().copy( this );
  9008. },
  9009. copy: function ( source ) {
  9010. this.name = source.name;
  9011. this.fog = source.fog;
  9012. this.lights = source.lights;
  9013. this.blending = source.blending;
  9014. this.side = source.side;
  9015. this.flatShading = source.flatShading;
  9016. this.vertexColors = source.vertexColors;
  9017. this.opacity = source.opacity;
  9018. this.transparent = source.transparent;
  9019. this.blendSrc = source.blendSrc;
  9020. this.blendDst = source.blendDst;
  9021. this.blendEquation = source.blendEquation;
  9022. this.blendSrcAlpha = source.blendSrcAlpha;
  9023. this.blendDstAlpha = source.blendDstAlpha;
  9024. this.blendEquationAlpha = source.blendEquationAlpha;
  9025. this.depthFunc = source.depthFunc;
  9026. this.depthTest = source.depthTest;
  9027. this.depthWrite = source.depthWrite;
  9028. this.colorWrite = source.colorWrite;
  9029. this.precision = source.precision;
  9030. this.polygonOffset = source.polygonOffset;
  9031. this.polygonOffsetFactor = source.polygonOffsetFactor;
  9032. this.polygonOffsetUnits = source.polygonOffsetUnits;
  9033. this.dithering = source.dithering;
  9034. this.alphaTest = source.alphaTest;
  9035. this.premultipliedAlpha = source.premultipliedAlpha;
  9036. this.overdraw = source.overdraw;
  9037. this.visible = source.visible;
  9038. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9039. this.clipShadows = source.clipShadows;
  9040. this.clipIntersection = source.clipIntersection;
  9041. var srcPlanes = source.clippingPlanes,
  9042. dstPlanes = null;
  9043. if ( srcPlanes !== null ) {
  9044. var n = srcPlanes.length;
  9045. dstPlanes = new Array( n );
  9046. for ( var i = 0; i !== n; ++ i )
  9047. dstPlanes[ i ] = srcPlanes[ i ].clone();
  9048. }
  9049. this.clippingPlanes = dstPlanes;
  9050. return this;
  9051. },
  9052. dispose: function () {
  9053. this.dispatchEvent( { type: 'dispose' } );
  9054. }
  9055. } );
  9056. /**
  9057. * @author alteredq / http://alteredqualia.com/
  9058. *
  9059. * parameters = {
  9060. * defines: { "label" : "value" },
  9061. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  9062. *
  9063. * fragmentShader: <string>,
  9064. * vertexShader: <string>,
  9065. *
  9066. * wireframe: <boolean>,
  9067. * wireframeLinewidth: <float>,
  9068. *
  9069. * lights: <bool>,
  9070. *
  9071. * skinning: <bool>,
  9072. * morphTargets: <bool>,
  9073. * morphNormals: <bool>
  9074. * }
  9075. */
  9076. function ShaderMaterial( parameters ) {
  9077. Material.call( this );
  9078. this.type = 'ShaderMaterial';
  9079. this.defines = {};
  9080. this.uniforms = {};
  9081. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  9082. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  9083. this.linewidth = 1;
  9084. this.wireframe = false;
  9085. this.wireframeLinewidth = 1;
  9086. this.fog = false; // set to use scene fog
  9087. this.lights = false; // set to use scene lights
  9088. this.clipping = false; // set to use user-defined clipping planes
  9089. this.skinning = false; // set to use skinning attribute streams
  9090. this.morphTargets = false; // set to use morph targets
  9091. this.morphNormals = false; // set to use morph normals
  9092. this.extensions = {
  9093. derivatives: false, // set to use derivatives
  9094. fragDepth: false, // set to use fragment depth values
  9095. drawBuffers: false, // set to use draw buffers
  9096. shaderTextureLOD: false // set to use shader texture LOD
  9097. };
  9098. // When rendered geometry doesn't include these attributes but the material does,
  9099. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9100. this.defaultAttributeValues = {
  9101. 'color': [ 1, 1, 1 ],
  9102. 'uv': [ 0, 0 ],
  9103. 'uv2': [ 0, 0 ]
  9104. };
  9105. this.index0AttributeName = undefined;
  9106. if ( parameters !== undefined ) {
  9107. if ( parameters.attributes !== undefined ) {
  9108. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  9109. }
  9110. this.setValues( parameters );
  9111. }
  9112. }
  9113. ShaderMaterial.prototype = Object.create( Material.prototype );
  9114. ShaderMaterial.prototype.constructor = ShaderMaterial;
  9115. ShaderMaterial.prototype.isShaderMaterial = true;
  9116. ShaderMaterial.prototype.copy = function ( source ) {
  9117. Material.prototype.copy.call( this, source );
  9118. this.fragmentShader = source.fragmentShader;
  9119. this.vertexShader = source.vertexShader;
  9120. this.uniforms = UniformsUtils.clone( source.uniforms );
  9121. this.defines = source.defines;
  9122. this.wireframe = source.wireframe;
  9123. this.wireframeLinewidth = source.wireframeLinewidth;
  9124. this.lights = source.lights;
  9125. this.clipping = source.clipping;
  9126. this.skinning = source.skinning;
  9127. this.morphTargets = source.morphTargets;
  9128. this.morphNormals = source.morphNormals;
  9129. this.extensions = source.extensions;
  9130. return this;
  9131. };
  9132. ShaderMaterial.prototype.toJSON = function ( meta ) {
  9133. var data = Material.prototype.toJSON.call( this, meta );
  9134. data.uniforms = this.uniforms;
  9135. data.vertexShader = this.vertexShader;
  9136. data.fragmentShader = this.fragmentShader;
  9137. return data;
  9138. };
  9139. /**
  9140. * @author mrdoob / http://mrdoob.com/
  9141. * @author alteredq / http://alteredqualia.com/
  9142. * @author bhouston / https://clara.io
  9143. * @author WestLangley / http://github.com/WestLangley
  9144. *
  9145. * parameters = {
  9146. *
  9147. * opacity: <float>,
  9148. *
  9149. * map: new THREE.Texture( <Image> ),
  9150. *
  9151. * alphaMap: new THREE.Texture( <Image> ),
  9152. *
  9153. * displacementMap: new THREE.Texture( <Image> ),
  9154. * displacementScale: <float>,
  9155. * displacementBias: <float>,
  9156. *
  9157. * wireframe: <boolean>,
  9158. * wireframeLinewidth: <float>
  9159. * }
  9160. */
  9161. function MeshDepthMaterial( parameters ) {
  9162. Material.call( this );
  9163. this.type = 'MeshDepthMaterial';
  9164. this.depthPacking = BasicDepthPacking;
  9165. this.skinning = false;
  9166. this.morphTargets = false;
  9167. this.map = null;
  9168. this.alphaMap = null;
  9169. this.displacementMap = null;
  9170. this.displacementScale = 1;
  9171. this.displacementBias = 0;
  9172. this.wireframe = false;
  9173. this.wireframeLinewidth = 1;
  9174. this.fog = false;
  9175. this.lights = false;
  9176. this.setValues( parameters );
  9177. }
  9178. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  9179. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  9180. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  9181. MeshDepthMaterial.prototype.copy = function ( source ) {
  9182. Material.prototype.copy.call( this, source );
  9183. this.depthPacking = source.depthPacking;
  9184. this.skinning = source.skinning;
  9185. this.morphTargets = source.morphTargets;
  9186. this.map = source.map;
  9187. this.alphaMap = source.alphaMap;
  9188. this.displacementMap = source.displacementMap;
  9189. this.displacementScale = source.displacementScale;
  9190. this.displacementBias = source.displacementBias;
  9191. this.wireframe = source.wireframe;
  9192. this.wireframeLinewidth = source.wireframeLinewidth;
  9193. return this;
  9194. };
  9195. /**
  9196. * @author WestLangley / http://github.com/WestLangley
  9197. *
  9198. * parameters = {
  9199. *
  9200. * referencePosition: <float>,
  9201. * nearDistance: <float>,
  9202. * farDistance: <float>,
  9203. *
  9204. * skinning: <bool>,
  9205. * morphTargets: <bool>,
  9206. *
  9207. * map: new THREE.Texture( <Image> ),
  9208. *
  9209. * alphaMap: new THREE.Texture( <Image> ),
  9210. *
  9211. * displacementMap: new THREE.Texture( <Image> ),
  9212. * displacementScale: <float>,
  9213. * displacementBias: <float>
  9214. *
  9215. * }
  9216. */
  9217. function MeshDistanceMaterial( parameters ) {
  9218. Material.call( this );
  9219. this.type = 'MeshDistanceMaterial';
  9220. this.referencePosition = new Vector3();
  9221. this.nearDistance = 1;
  9222. this.farDistance = 1000;
  9223. this.skinning = false;
  9224. this.morphTargets = false;
  9225. this.map = null;
  9226. this.alphaMap = null;
  9227. this.displacementMap = null;
  9228. this.displacementScale = 1;
  9229. this.displacementBias = 0;
  9230. this.fog = false;
  9231. this.lights = false;
  9232. this.setValues( parameters );
  9233. }
  9234. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  9235. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  9236. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  9237. MeshDistanceMaterial.prototype.copy = function ( source ) {
  9238. Material.prototype.copy.call( this, source );
  9239. this.referencePosition.copy( source.referencePosition );
  9240. this.nearDistance = source.nearDistance;
  9241. this.farDistance = source.farDistance;
  9242. this.skinning = source.skinning;
  9243. this.morphTargets = source.morphTargets;
  9244. this.map = source.map;
  9245. this.alphaMap = source.alphaMap;
  9246. this.displacementMap = source.displacementMap;
  9247. this.displacementScale = source.displacementScale;
  9248. this.displacementBias = source.displacementBias;
  9249. return this;
  9250. };
  9251. /**
  9252. * @author bhouston / http://clara.io
  9253. * @author WestLangley / http://github.com/WestLangley
  9254. */
  9255. function Box3( min, max ) {
  9256. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9257. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9258. }
  9259. Object.assign( Box3.prototype, {
  9260. isBox3: true,
  9261. set: function ( min, max ) {
  9262. this.min.copy( min );
  9263. this.max.copy( max );
  9264. return this;
  9265. },
  9266. setFromArray: function ( array ) {
  9267. var minX = + Infinity;
  9268. var minY = + Infinity;
  9269. var minZ = + Infinity;
  9270. var maxX = - Infinity;
  9271. var maxY = - Infinity;
  9272. var maxZ = - Infinity;
  9273. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9274. var x = array[ i ];
  9275. var y = array[ i + 1 ];
  9276. var z = array[ i + 2 ];
  9277. if ( x < minX ) minX = x;
  9278. if ( y < minY ) minY = y;
  9279. if ( z < minZ ) minZ = z;
  9280. if ( x > maxX ) maxX = x;
  9281. if ( y > maxY ) maxY = y;
  9282. if ( z > maxZ ) maxZ = z;
  9283. }
  9284. this.min.set( minX, minY, minZ );
  9285. this.max.set( maxX, maxY, maxZ );
  9286. return this;
  9287. },
  9288. setFromBufferAttribute: function ( attribute ) {
  9289. var minX = + Infinity;
  9290. var minY = + Infinity;
  9291. var minZ = + Infinity;
  9292. var maxX = - Infinity;
  9293. var maxY = - Infinity;
  9294. var maxZ = - Infinity;
  9295. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9296. var x = attribute.getX( i );
  9297. var y = attribute.getY( i );
  9298. var z = attribute.getZ( i );
  9299. if ( x < minX ) minX = x;
  9300. if ( y < minY ) minY = y;
  9301. if ( z < minZ ) minZ = z;
  9302. if ( x > maxX ) maxX = x;
  9303. if ( y > maxY ) maxY = y;
  9304. if ( z > maxZ ) maxZ = z;
  9305. }
  9306. this.min.set( minX, minY, minZ );
  9307. this.max.set( maxX, maxY, maxZ );
  9308. return this;
  9309. },
  9310. setFromPoints: function ( points ) {
  9311. this.makeEmpty();
  9312. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9313. this.expandByPoint( points[ i ] );
  9314. }
  9315. return this;
  9316. },
  9317. setFromCenterAndSize: function () {
  9318. var v1 = new Vector3();
  9319. return function setFromCenterAndSize( center, size ) {
  9320. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  9321. this.min.copy( center ).sub( halfSize );
  9322. this.max.copy( center ).add( halfSize );
  9323. return this;
  9324. };
  9325. }(),
  9326. setFromObject: function ( object ) {
  9327. this.makeEmpty();
  9328. return this.expandByObject( object );
  9329. },
  9330. clone: function () {
  9331. return new this.constructor().copy( this );
  9332. },
  9333. copy: function ( box ) {
  9334. this.min.copy( box.min );
  9335. this.max.copy( box.max );
  9336. return this;
  9337. },
  9338. makeEmpty: function () {
  9339. this.min.x = this.min.y = this.min.z = + Infinity;
  9340. this.max.x = this.max.y = this.max.z = - Infinity;
  9341. return this;
  9342. },
  9343. isEmpty: function () {
  9344. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9345. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9346. },
  9347. getCenter: function ( optionalTarget ) {
  9348. var result = optionalTarget || new Vector3();
  9349. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9350. },
  9351. getSize: function ( optionalTarget ) {
  9352. var result = optionalTarget || new Vector3();
  9353. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  9354. },
  9355. expandByPoint: function ( point ) {
  9356. this.min.min( point );
  9357. this.max.max( point );
  9358. return this;
  9359. },
  9360. expandByVector: function ( vector ) {
  9361. this.min.sub( vector );
  9362. this.max.add( vector );
  9363. return this;
  9364. },
  9365. expandByScalar: function ( scalar ) {
  9366. this.min.addScalar( - scalar );
  9367. this.max.addScalar( scalar );
  9368. return this;
  9369. },
  9370. expandByObject: function () {
  9371. // Computes the world-axis-aligned bounding box of an object (including its children),
  9372. // accounting for both the object's, and children's, world transforms
  9373. var v1 = new Vector3();
  9374. return function expandByObject( object ) {
  9375. var scope = this;
  9376. object.updateMatrixWorld( true );
  9377. object.traverse( function ( node ) {
  9378. var i, l;
  9379. var geometry = node.geometry;
  9380. if ( geometry !== undefined ) {
  9381. if ( geometry.isGeometry ) {
  9382. var vertices = geometry.vertices;
  9383. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  9384. v1.copy( vertices[ i ] );
  9385. v1.applyMatrix4( node.matrixWorld );
  9386. scope.expandByPoint( v1 );
  9387. }
  9388. } else if ( geometry.isBufferGeometry ) {
  9389. var attribute = geometry.attributes.position;
  9390. if ( attribute !== undefined ) {
  9391. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  9392. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  9393. scope.expandByPoint( v1 );
  9394. }
  9395. }
  9396. }
  9397. }
  9398. } );
  9399. return this;
  9400. };
  9401. }(),
  9402. containsPoint: function ( point ) {
  9403. return point.x < this.min.x || point.x > this.max.x ||
  9404. point.y < this.min.y || point.y > this.max.y ||
  9405. point.z < this.min.z || point.z > this.max.z ? false : true;
  9406. },
  9407. containsBox: function ( box ) {
  9408. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9409. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9410. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9411. },
  9412. getParameter: function ( point, optionalTarget ) {
  9413. // This can potentially have a divide by zero if the box
  9414. // has a size dimension of 0.
  9415. var result = optionalTarget || new Vector3();
  9416. return result.set(
  9417. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9418. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9419. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9420. );
  9421. },
  9422. intersectsBox: function ( box ) {
  9423. // using 6 splitting planes to rule out intersections.
  9424. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9425. box.max.y < this.min.y || box.min.y > this.max.y ||
  9426. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9427. },
  9428. intersectsSphere: ( function () {
  9429. var closestPoint = new Vector3();
  9430. return function intersectsSphere( sphere ) {
  9431. // Find the point on the AABB closest to the sphere center.
  9432. this.clampPoint( sphere.center, closestPoint );
  9433. // If that point is inside the sphere, the AABB and sphere intersect.
  9434. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9435. };
  9436. } )(),
  9437. intersectsPlane: function ( plane ) {
  9438. // We compute the minimum and maximum dot product values. If those values
  9439. // are on the same side (back or front) of the plane, then there is no intersection.
  9440. var min, max;
  9441. if ( plane.normal.x > 0 ) {
  9442. min = plane.normal.x * this.min.x;
  9443. max = plane.normal.x * this.max.x;
  9444. } else {
  9445. min = plane.normal.x * this.max.x;
  9446. max = plane.normal.x * this.min.x;
  9447. }
  9448. if ( plane.normal.y > 0 ) {
  9449. min += plane.normal.y * this.min.y;
  9450. max += plane.normal.y * this.max.y;
  9451. } else {
  9452. min += plane.normal.y * this.max.y;
  9453. max += plane.normal.y * this.min.y;
  9454. }
  9455. if ( plane.normal.z > 0 ) {
  9456. min += plane.normal.z * this.min.z;
  9457. max += plane.normal.z * this.max.z;
  9458. } else {
  9459. min += plane.normal.z * this.max.z;
  9460. max += plane.normal.z * this.min.z;
  9461. }
  9462. return ( min <= plane.constant && max >= plane.constant );
  9463. },
  9464. clampPoint: function ( point, optionalTarget ) {
  9465. var result = optionalTarget || new Vector3();
  9466. return result.copy( point ).clamp( this.min, this.max );
  9467. },
  9468. distanceToPoint: function () {
  9469. var v1 = new Vector3();
  9470. return function distanceToPoint( point ) {
  9471. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  9472. return clampedPoint.sub( point ).length();
  9473. };
  9474. }(),
  9475. getBoundingSphere: function () {
  9476. var v1 = new Vector3();
  9477. return function getBoundingSphere( optionalTarget ) {
  9478. var result = optionalTarget || new Sphere();
  9479. this.getCenter( result.center );
  9480. result.radius = this.getSize( v1 ).length() * 0.5;
  9481. return result;
  9482. };
  9483. }(),
  9484. intersect: function ( box ) {
  9485. this.min.max( box.min );
  9486. this.max.min( box.max );
  9487. // 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.
  9488. if( this.isEmpty() ) this.makeEmpty();
  9489. return this;
  9490. },
  9491. union: function ( box ) {
  9492. this.min.min( box.min );
  9493. this.max.max( box.max );
  9494. return this;
  9495. },
  9496. applyMatrix4: function () {
  9497. var points = [
  9498. new Vector3(),
  9499. new Vector3(),
  9500. new Vector3(),
  9501. new Vector3(),
  9502. new Vector3(),
  9503. new Vector3(),
  9504. new Vector3(),
  9505. new Vector3()
  9506. ];
  9507. return function applyMatrix4( matrix ) {
  9508. // transform of empty box is an empty box.
  9509. if( this.isEmpty() ) return this;
  9510. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9511. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9512. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9513. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9514. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9515. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9516. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9517. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9518. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9519. this.setFromPoints( points );
  9520. return this;
  9521. };
  9522. }(),
  9523. translate: function ( offset ) {
  9524. this.min.add( offset );
  9525. this.max.add( offset );
  9526. return this;
  9527. },
  9528. equals: function ( box ) {
  9529. return box.min.equals( this.min ) && box.max.equals( this.max );
  9530. }
  9531. } );
  9532. /**
  9533. * @author bhouston / http://clara.io
  9534. * @author mrdoob / http://mrdoob.com/
  9535. */
  9536. function Sphere( center, radius ) {
  9537. this.center = ( center !== undefined ) ? center : new Vector3();
  9538. this.radius = ( radius !== undefined ) ? radius : 0;
  9539. }
  9540. Object.assign( Sphere.prototype, {
  9541. set: function ( center, radius ) {
  9542. this.center.copy( center );
  9543. this.radius = radius;
  9544. return this;
  9545. },
  9546. setFromPoints: function () {
  9547. var box = new Box3();
  9548. return function setFromPoints( points, optionalCenter ) {
  9549. var center = this.center;
  9550. if ( optionalCenter !== undefined ) {
  9551. center.copy( optionalCenter );
  9552. } else {
  9553. box.setFromPoints( points ).getCenter( center );
  9554. }
  9555. var maxRadiusSq = 0;
  9556. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9557. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9558. }
  9559. this.radius = Math.sqrt( maxRadiusSq );
  9560. return this;
  9561. };
  9562. }(),
  9563. clone: function () {
  9564. return new this.constructor().copy( this );
  9565. },
  9566. copy: function ( sphere ) {
  9567. this.center.copy( sphere.center );
  9568. this.radius = sphere.radius;
  9569. return this;
  9570. },
  9571. empty: function () {
  9572. return ( this.radius <= 0 );
  9573. },
  9574. containsPoint: function ( point ) {
  9575. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9576. },
  9577. distanceToPoint: function ( point ) {
  9578. return ( point.distanceTo( this.center ) - this.radius );
  9579. },
  9580. intersectsSphere: function ( sphere ) {
  9581. var radiusSum = this.radius + sphere.radius;
  9582. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9583. },
  9584. intersectsBox: function ( box ) {
  9585. return box.intersectsSphere( this );
  9586. },
  9587. intersectsPlane: function ( plane ) {
  9588. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  9589. },
  9590. clampPoint: function ( point, optionalTarget ) {
  9591. var deltaLengthSq = this.center.distanceToSquared( point );
  9592. var result = optionalTarget || new Vector3();
  9593. result.copy( point );
  9594. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9595. result.sub( this.center ).normalize();
  9596. result.multiplyScalar( this.radius ).add( this.center );
  9597. }
  9598. return result;
  9599. },
  9600. getBoundingBox: function ( optionalTarget ) {
  9601. var box = optionalTarget || new Box3();
  9602. box.set( this.center, this.center );
  9603. box.expandByScalar( this.radius );
  9604. return box;
  9605. },
  9606. applyMatrix4: function ( matrix ) {
  9607. this.center.applyMatrix4( matrix );
  9608. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9609. return this;
  9610. },
  9611. translate: function ( offset ) {
  9612. this.center.add( offset );
  9613. return this;
  9614. },
  9615. equals: function ( sphere ) {
  9616. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9617. }
  9618. } );
  9619. /**
  9620. * @author alteredq / http://alteredqualia.com/
  9621. * @author WestLangley / http://github.com/WestLangley
  9622. * @author bhouston / http://clara.io
  9623. * @author tschw
  9624. */
  9625. function Matrix3() {
  9626. this.elements = [
  9627. 1, 0, 0,
  9628. 0, 1, 0,
  9629. 0, 0, 1
  9630. ];
  9631. if ( arguments.length > 0 ) {
  9632. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  9633. }
  9634. }
  9635. Object.assign( Matrix3.prototype, {
  9636. isMatrix3: true,
  9637. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  9638. var te = this.elements;
  9639. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  9640. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  9641. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  9642. return this;
  9643. },
  9644. identity: function () {
  9645. this.set(
  9646. 1, 0, 0,
  9647. 0, 1, 0,
  9648. 0, 0, 1
  9649. );
  9650. return this;
  9651. },
  9652. clone: function () {
  9653. return new this.constructor().fromArray( this.elements );
  9654. },
  9655. copy: function ( m ) {
  9656. var te = this.elements;
  9657. var me = m.elements;
  9658. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  9659. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  9660. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  9661. return this;
  9662. },
  9663. setFromMatrix4: function ( m ) {
  9664. var me = m.elements;
  9665. this.set(
  9666. me[ 0 ], me[ 4 ], me[ 8 ],
  9667. me[ 1 ], me[ 5 ], me[ 9 ],
  9668. me[ 2 ], me[ 6 ], me[ 10 ]
  9669. );
  9670. return this;
  9671. },
  9672. applyToBufferAttribute: function () {
  9673. var v1 = new Vector3();
  9674. return function applyToBufferAttribute( attribute ) {
  9675. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9676. v1.x = attribute.getX( i );
  9677. v1.y = attribute.getY( i );
  9678. v1.z = attribute.getZ( i );
  9679. v1.applyMatrix3( this );
  9680. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  9681. }
  9682. return attribute;
  9683. };
  9684. }(),
  9685. multiply: function ( m ) {
  9686. return this.multiplyMatrices( this, m );
  9687. },
  9688. premultiply: function ( m ) {
  9689. return this.multiplyMatrices( m, this );
  9690. },
  9691. multiplyMatrices: function ( a, b ) {
  9692. var ae = a.elements;
  9693. var be = b.elements;
  9694. var te = this.elements;
  9695. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  9696. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  9697. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  9698. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  9699. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  9700. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  9701. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  9702. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  9703. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  9704. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  9705. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  9706. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  9707. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  9708. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  9709. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  9710. return this;
  9711. },
  9712. multiplyScalar: function ( s ) {
  9713. var te = this.elements;
  9714. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  9715. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  9716. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  9717. return this;
  9718. },
  9719. determinant: function () {
  9720. var te = this.elements;
  9721. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  9722. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  9723. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  9724. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  9725. },
  9726. getInverse: function ( matrix, throwOnDegenerate ) {
  9727. if ( matrix && matrix.isMatrix4 ) {
  9728. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  9729. }
  9730. var me = matrix.elements,
  9731. te = this.elements,
  9732. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  9733. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  9734. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  9735. t11 = n33 * n22 - n32 * n23,
  9736. t12 = n32 * n13 - n33 * n12,
  9737. t13 = n23 * n12 - n22 * n13,
  9738. det = n11 * t11 + n21 * t12 + n31 * t13;
  9739. if ( det === 0 ) {
  9740. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  9741. if ( throwOnDegenerate === true ) {
  9742. throw new Error( msg );
  9743. } else {
  9744. console.warn( msg );
  9745. }
  9746. return this.identity();
  9747. }
  9748. var detInv = 1 / det;
  9749. te[ 0 ] = t11 * detInv;
  9750. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  9751. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  9752. te[ 3 ] = t12 * detInv;
  9753. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  9754. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  9755. te[ 6 ] = t13 * detInv;
  9756. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  9757. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  9758. return this;
  9759. },
  9760. transpose: function () {
  9761. var tmp, m = this.elements;
  9762. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  9763. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  9764. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  9765. return this;
  9766. },
  9767. getNormalMatrix: function ( matrix4 ) {
  9768. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  9769. },
  9770. transposeIntoArray: function ( r ) {
  9771. var m = this.elements;
  9772. r[ 0 ] = m[ 0 ];
  9773. r[ 1 ] = m[ 3 ];
  9774. r[ 2 ] = m[ 6 ];
  9775. r[ 3 ] = m[ 1 ];
  9776. r[ 4 ] = m[ 4 ];
  9777. r[ 5 ] = m[ 7 ];
  9778. r[ 6 ] = m[ 2 ];
  9779. r[ 7 ] = m[ 5 ];
  9780. r[ 8 ] = m[ 8 ];
  9781. return this;
  9782. },
  9783. equals: function ( matrix ) {
  9784. var te = this.elements;
  9785. var me = matrix.elements;
  9786. for ( var i = 0; i < 9; i ++ ) {
  9787. if ( te[ i ] !== me[ i ] ) return false;
  9788. }
  9789. return true;
  9790. },
  9791. fromArray: function ( array, offset ) {
  9792. if ( offset === undefined ) offset = 0;
  9793. for ( var i = 0; i < 9; i ++ ) {
  9794. this.elements[ i ] = array[ i + offset ];
  9795. }
  9796. return this;
  9797. },
  9798. toArray: function ( array, offset ) {
  9799. if ( array === undefined ) array = [];
  9800. if ( offset === undefined ) offset = 0;
  9801. var te = this.elements;
  9802. array[ offset ] = te[ 0 ];
  9803. array[ offset + 1 ] = te[ 1 ];
  9804. array[ offset + 2 ] = te[ 2 ];
  9805. array[ offset + 3 ] = te[ 3 ];
  9806. array[ offset + 4 ] = te[ 4 ];
  9807. array[ offset + 5 ] = te[ 5 ];
  9808. array[ offset + 6 ] = te[ 6 ];
  9809. array[ offset + 7 ] = te[ 7 ];
  9810. array[ offset + 8 ] = te[ 8 ];
  9811. return array;
  9812. }
  9813. } );
  9814. /**
  9815. * @author bhouston / http://clara.io
  9816. */
  9817. function Plane( normal, constant ) {
  9818. // normal is assumed to be normalized
  9819. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  9820. this.constant = ( constant !== undefined ) ? constant : 0;
  9821. }
  9822. Object.assign( Plane.prototype, {
  9823. set: function ( normal, constant ) {
  9824. this.normal.copy( normal );
  9825. this.constant = constant;
  9826. return this;
  9827. },
  9828. setComponents: function ( x, y, z, w ) {
  9829. this.normal.set( x, y, z );
  9830. this.constant = w;
  9831. return this;
  9832. },
  9833. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  9834. this.normal.copy( normal );
  9835. this.constant = - point.dot( this.normal );
  9836. return this;
  9837. },
  9838. setFromCoplanarPoints: function () {
  9839. var v1 = new Vector3();
  9840. var v2 = new Vector3();
  9841. return function setFromCoplanarPoints( a, b, c ) {
  9842. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  9843. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9844. this.setFromNormalAndCoplanarPoint( normal, a );
  9845. return this;
  9846. };
  9847. }(),
  9848. clone: function () {
  9849. return new this.constructor().copy( this );
  9850. },
  9851. copy: function ( plane ) {
  9852. this.normal.copy( plane.normal );
  9853. this.constant = plane.constant;
  9854. return this;
  9855. },
  9856. normalize: function () {
  9857. // Note: will lead to a divide by zero if the plane is invalid.
  9858. var inverseNormalLength = 1.0 / this.normal.length();
  9859. this.normal.multiplyScalar( inverseNormalLength );
  9860. this.constant *= inverseNormalLength;
  9861. return this;
  9862. },
  9863. negate: function () {
  9864. this.constant *= - 1;
  9865. this.normal.negate();
  9866. return this;
  9867. },
  9868. distanceToPoint: function ( point ) {
  9869. return this.normal.dot( point ) + this.constant;
  9870. },
  9871. distanceToSphere: function ( sphere ) {
  9872. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9873. },
  9874. projectPoint: function ( point, optionalTarget ) {
  9875. var result = optionalTarget || new Vector3();
  9876. return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  9877. },
  9878. intersectLine: function () {
  9879. var v1 = new Vector3();
  9880. return function intersectLine( line, optionalTarget ) {
  9881. var result = optionalTarget || new Vector3();
  9882. var direction = line.delta( v1 );
  9883. var denominator = this.normal.dot( direction );
  9884. if ( denominator === 0 ) {
  9885. // line is coplanar, return origin
  9886. if ( this.distanceToPoint( line.start ) === 0 ) {
  9887. return result.copy( line.start );
  9888. }
  9889. // Unsure if this is the correct method to handle this case.
  9890. return undefined;
  9891. }
  9892. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9893. if ( t < 0 || t > 1 ) {
  9894. return undefined;
  9895. }
  9896. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  9897. };
  9898. }(),
  9899. intersectsLine: function ( line ) {
  9900. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9901. var startSign = this.distanceToPoint( line.start );
  9902. var endSign = this.distanceToPoint( line.end );
  9903. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9904. },
  9905. intersectsBox: function ( box ) {
  9906. return box.intersectsPlane( this );
  9907. },
  9908. intersectsSphere: function ( sphere ) {
  9909. return sphere.intersectsPlane( this );
  9910. },
  9911. coplanarPoint: function ( optionalTarget ) {
  9912. var result = optionalTarget || new Vector3();
  9913. return result.copy( this.normal ).multiplyScalar( - this.constant );
  9914. },
  9915. applyMatrix4: function () {
  9916. var v1 = new Vector3();
  9917. var m1 = new Matrix3();
  9918. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  9919. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  9920. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  9921. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  9922. this.constant = - referencePoint.dot( normal );
  9923. return this;
  9924. };
  9925. }(),
  9926. translate: function ( offset ) {
  9927. this.constant -= offset.dot( this.normal );
  9928. return this;
  9929. },
  9930. equals: function ( plane ) {
  9931. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  9932. }
  9933. } );
  9934. /**
  9935. * @author mrdoob / http://mrdoob.com/
  9936. * @author alteredq / http://alteredqualia.com/
  9937. * @author bhouston / http://clara.io
  9938. */
  9939. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  9940. this.planes = [
  9941. ( p0 !== undefined ) ? p0 : new Plane(),
  9942. ( p1 !== undefined ) ? p1 : new Plane(),
  9943. ( p2 !== undefined ) ? p2 : new Plane(),
  9944. ( p3 !== undefined ) ? p3 : new Plane(),
  9945. ( p4 !== undefined ) ? p4 : new Plane(),
  9946. ( p5 !== undefined ) ? p5 : new Plane()
  9947. ];
  9948. }
  9949. Object.assign( Frustum.prototype, {
  9950. set: function ( p0, p1, p2, p3, p4, p5 ) {
  9951. var planes = this.planes;
  9952. planes[ 0 ].copy( p0 );
  9953. planes[ 1 ].copy( p1 );
  9954. planes[ 2 ].copy( p2 );
  9955. planes[ 3 ].copy( p3 );
  9956. planes[ 4 ].copy( p4 );
  9957. planes[ 5 ].copy( p5 );
  9958. return this;
  9959. },
  9960. clone: function () {
  9961. return new this.constructor().copy( this );
  9962. },
  9963. copy: function ( frustum ) {
  9964. var planes = this.planes;
  9965. for ( var i = 0; i < 6; i ++ ) {
  9966. planes[ i ].copy( frustum.planes[ i ] );
  9967. }
  9968. return this;
  9969. },
  9970. setFromMatrix: function ( m ) {
  9971. var planes = this.planes;
  9972. var me = m.elements;
  9973. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9974. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9975. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9976. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9977. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9978. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9979. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9980. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9981. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9982. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9983. return this;
  9984. },
  9985. intersectsObject: function () {
  9986. var sphere = new Sphere();
  9987. return function intersectsObject( object ) {
  9988. var geometry = object.geometry;
  9989. if ( geometry.boundingSphere === null )
  9990. geometry.computeBoundingSphere();
  9991. sphere.copy( geometry.boundingSphere )
  9992. .applyMatrix4( object.matrixWorld );
  9993. return this.intersectsSphere( sphere );
  9994. };
  9995. }(),
  9996. intersectsSprite: function () {
  9997. var sphere = new Sphere();
  9998. return function intersectsSprite( sprite ) {
  9999. sphere.center.set( 0, 0, 0 );
  10000. sphere.radius = 0.7071067811865476;
  10001. sphere.applyMatrix4( sprite.matrixWorld );
  10002. return this.intersectsSphere( sphere );
  10003. };
  10004. }(),
  10005. intersectsSphere: function ( sphere ) {
  10006. var planes = this.planes;
  10007. var center = sphere.center;
  10008. var negRadius = - sphere.radius;
  10009. for ( var i = 0; i < 6; i ++ ) {
  10010. var distance = planes[ i ].distanceToPoint( center );
  10011. if ( distance < negRadius ) {
  10012. return false;
  10013. }
  10014. }
  10015. return true;
  10016. },
  10017. intersectsBox: function () {
  10018. var p1 = new Vector3(),
  10019. p2 = new Vector3();
  10020. return function intersectsBox( box ) {
  10021. var planes = this.planes;
  10022. for ( var i = 0; i < 6; i ++ ) {
  10023. var plane = planes[ i ];
  10024. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  10025. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10026. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  10027. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10028. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  10029. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10030. var d1 = plane.distanceToPoint( p1 );
  10031. var d2 = plane.distanceToPoint( p2 );
  10032. // if both outside plane, no intersection
  10033. if ( d1 < 0 && d2 < 0 ) {
  10034. return false;
  10035. }
  10036. }
  10037. return true;
  10038. };
  10039. }(),
  10040. containsPoint: function ( point ) {
  10041. var planes = this.planes;
  10042. for ( var i = 0; i < 6; i ++ ) {
  10043. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  10044. return false;
  10045. }
  10046. }
  10047. return true;
  10048. }
  10049. } );
  10050. /**
  10051. * @author alteredq / http://alteredqualia.com/
  10052. * @author mrdoob / http://mrdoob.com/
  10053. */
  10054. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  10055. var _frustum = new Frustum(),
  10056. _projScreenMatrix = new Matrix4(),
  10057. _shadowMapSize = new Vector2(),
  10058. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  10059. _lookTarget = new Vector3(),
  10060. _lightPositionWorld = new Vector3(),
  10061. _MorphingFlag = 1,
  10062. _SkinningFlag = 2,
  10063. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  10064. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  10065. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  10066. _materialCache = {};
  10067. var cubeDirections = [
  10068. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  10069. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  10070. ];
  10071. var cubeUps = [
  10072. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  10073. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  10074. ];
  10075. var cube2DViewPorts = [
  10076. new Vector4(), new Vector4(), new Vector4(),
  10077. new Vector4(), new Vector4(), new Vector4()
  10078. ];
  10079. // init
  10080. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  10081. var useMorphing = ( i & _MorphingFlag ) !== 0;
  10082. var useSkinning = ( i & _SkinningFlag ) !== 0;
  10083. var depthMaterial = new MeshDepthMaterial( {
  10084. depthPacking: RGBADepthPacking,
  10085. morphTargets: useMorphing,
  10086. skinning: useSkinning
  10087. } );
  10088. _depthMaterials[ i ] = depthMaterial;
  10089. //
  10090. var distanceMaterial = new MeshDistanceMaterial( {
  10091. morphTargets: useMorphing,
  10092. skinning: useSkinning
  10093. } );
  10094. _distanceMaterials[ i ] = distanceMaterial;
  10095. }
  10096. //
  10097. var scope = this;
  10098. this.enabled = false;
  10099. this.autoUpdate = true;
  10100. this.needsUpdate = false;
  10101. this.type = PCFShadowMap;
  10102. this.renderReverseSided = true;
  10103. this.renderSingleSided = true;
  10104. this.render = function ( lights, scene, camera ) {
  10105. if ( scope.enabled === false ) return;
  10106. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  10107. if ( lights.length === 0 ) return;
  10108. // TODO Clean up (needed in case of contextlost)
  10109. var _gl = _renderer.context;
  10110. var _state = _renderer.state;
  10111. // Set GL state for depth map.
  10112. _state.disable( _gl.BLEND );
  10113. _state.buffers.color.setClear( 1, 1, 1, 1 );
  10114. _state.buffers.depth.setTest( true );
  10115. _state.setScissorTest( false );
  10116. // render depth map
  10117. var faceCount;
  10118. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  10119. var light = lights[ i ];
  10120. var shadow = light.shadow;
  10121. var isPointLight = light && light.isPointLight;
  10122. if ( shadow === undefined ) {
  10123. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  10124. continue;
  10125. }
  10126. var shadowCamera = shadow.camera;
  10127. _shadowMapSize.copy( shadow.mapSize );
  10128. _shadowMapSize.min( _maxShadowMapSize );
  10129. if ( isPointLight ) {
  10130. var vpWidth = _shadowMapSize.x;
  10131. var vpHeight = _shadowMapSize.y;
  10132. // These viewports map a cube-map onto a 2D texture with the
  10133. // following orientation:
  10134. //
  10135. // xzXZ
  10136. // y Y
  10137. //
  10138. // X - Positive x direction
  10139. // x - Negative x direction
  10140. // Y - Positive y direction
  10141. // y - Negative y direction
  10142. // Z - Positive z direction
  10143. // z - Negative z direction
  10144. // positive X
  10145. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  10146. // negative X
  10147. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  10148. // positive Z
  10149. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  10150. // negative Z
  10151. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  10152. // positive Y
  10153. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  10154. // negative Y
  10155. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  10156. _shadowMapSize.x *= 4.0;
  10157. _shadowMapSize.y *= 2.0;
  10158. }
  10159. if ( shadow.map === null ) {
  10160. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  10161. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  10162. shadow.map.texture.name = light.name + ".shadowMap";
  10163. shadowCamera.updateProjectionMatrix();
  10164. }
  10165. if ( shadow.isSpotLightShadow ) {
  10166. shadow.update( light );
  10167. }
  10168. var shadowMap = shadow.map;
  10169. var shadowMatrix = shadow.matrix;
  10170. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  10171. shadowCamera.position.copy( _lightPositionWorld );
  10172. if ( isPointLight ) {
  10173. faceCount = 6;
  10174. // for point lights we set the shadow matrix to be a translation-only matrix
  10175. // equal to inverse of the light's position
  10176. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  10177. } else {
  10178. faceCount = 1;
  10179. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  10180. shadowCamera.lookAt( _lookTarget );
  10181. shadowCamera.updateMatrixWorld();
  10182. // compute shadow matrix
  10183. shadowMatrix.set(
  10184. 0.5, 0.0, 0.0, 0.5,
  10185. 0.0, 0.5, 0.0, 0.5,
  10186. 0.0, 0.0, 0.5, 0.5,
  10187. 0.0, 0.0, 0.0, 1.0
  10188. );
  10189. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  10190. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  10191. }
  10192. _renderer.setRenderTarget( shadowMap );
  10193. _renderer.clear();
  10194. // render shadow map for each cube face (if omni-directional) or
  10195. // run a single pass if not
  10196. for ( var face = 0; face < faceCount; face ++ ) {
  10197. if ( isPointLight ) {
  10198. _lookTarget.copy( shadowCamera.position );
  10199. _lookTarget.add( cubeDirections[ face ] );
  10200. shadowCamera.up.copy( cubeUps[ face ] );
  10201. shadowCamera.lookAt( _lookTarget );
  10202. shadowCamera.updateMatrixWorld();
  10203. var vpDimensions = cube2DViewPorts[ face ];
  10204. _state.viewport( vpDimensions );
  10205. }
  10206. // update camera matrices and frustum
  10207. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  10208. _frustum.setFromMatrix( _projScreenMatrix );
  10209. // set object matrices & frustum culling
  10210. renderObject( scene, camera, shadowCamera, isPointLight );
  10211. }
  10212. }
  10213. scope.needsUpdate = false;
  10214. };
  10215. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  10216. var geometry = object.geometry;
  10217. var result = null;
  10218. var materialVariants = _depthMaterials;
  10219. var customMaterial = object.customDepthMaterial;
  10220. if ( isPointLight ) {
  10221. materialVariants = _distanceMaterials;
  10222. customMaterial = object.customDistanceMaterial;
  10223. }
  10224. if ( ! customMaterial ) {
  10225. var useMorphing = false;
  10226. if ( material.morphTargets ) {
  10227. if ( geometry && geometry.isBufferGeometry ) {
  10228. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  10229. } else if ( geometry && geometry.isGeometry ) {
  10230. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  10231. }
  10232. }
  10233. if ( object.isSkinnedMesh && material.skinning === false ) {
  10234. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  10235. }
  10236. var useSkinning = object.isSkinnedMesh && material.skinning;
  10237. var variantIndex = 0;
  10238. if ( useMorphing ) variantIndex |= _MorphingFlag;
  10239. if ( useSkinning ) variantIndex |= _SkinningFlag;
  10240. result = materialVariants[ variantIndex ];
  10241. } else {
  10242. result = customMaterial;
  10243. }
  10244. if ( _renderer.localClippingEnabled &&
  10245. material.clipShadows === true &&
  10246. material.clippingPlanes.length !== 0 ) {
  10247. // in this case we need a unique material instance reflecting the
  10248. // appropriate state
  10249. var keyA = result.uuid, keyB = material.uuid;
  10250. var materialsForVariant = _materialCache[ keyA ];
  10251. if ( materialsForVariant === undefined ) {
  10252. materialsForVariant = {};
  10253. _materialCache[ keyA ] = materialsForVariant;
  10254. }
  10255. var cachedMaterial = materialsForVariant[ keyB ];
  10256. if ( cachedMaterial === undefined ) {
  10257. cachedMaterial = result.clone();
  10258. materialsForVariant[ keyB ] = cachedMaterial;
  10259. }
  10260. result = cachedMaterial;
  10261. }
  10262. result.visible = material.visible;
  10263. result.wireframe = material.wireframe;
  10264. var side = material.side;
  10265. if ( scope.renderSingleSided && side == DoubleSide ) {
  10266. side = FrontSide;
  10267. }
  10268. if ( scope.renderReverseSided ) {
  10269. if ( side === FrontSide ) side = BackSide;
  10270. else if ( side === BackSide ) side = FrontSide;
  10271. }
  10272. result.side = side;
  10273. result.clipShadows = material.clipShadows;
  10274. result.clippingPlanes = material.clippingPlanes;
  10275. result.clipIntersection = material.clipIntersection;
  10276. result.wireframeLinewidth = material.wireframeLinewidth;
  10277. result.linewidth = material.linewidth;
  10278. if ( isPointLight && result.isMeshDistanceMaterial ) {
  10279. result.referencePosition.copy( lightPositionWorld );
  10280. result.nearDistance = shadowCameraNear;
  10281. result.farDistance = shadowCameraFar;
  10282. }
  10283. return result;
  10284. }
  10285. function renderObject( object, camera, shadowCamera, isPointLight ) {
  10286. if ( object.visible === false ) return;
  10287. var visible = object.layers.test( camera.layers );
  10288. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  10289. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  10290. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  10291. var geometry = _objects.update( object );
  10292. var material = object.material;
  10293. if ( Array.isArray( material ) ) {
  10294. var groups = geometry.groups;
  10295. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  10296. var group = groups[ k ];
  10297. var groupMaterial = material[ group.materialIndex ];
  10298. if ( groupMaterial && groupMaterial.visible ) {
  10299. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  10300. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  10301. }
  10302. }
  10303. } else if ( material.visible ) {
  10304. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  10305. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  10306. }
  10307. }
  10308. }
  10309. var children = object.children;
  10310. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10311. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  10312. }
  10313. }
  10314. }
  10315. /**
  10316. * @author mrdoob / http://mrdoob.com/
  10317. */
  10318. function WebGLAttributes( gl ) {
  10319. var buffers = {};
  10320. function createBuffer( attribute, bufferType ) {
  10321. var array = attribute.array;
  10322. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10323. var buffer = gl.createBuffer();
  10324. gl.bindBuffer( bufferType, buffer );
  10325. gl.bufferData( bufferType, array, usage );
  10326. attribute.onUploadCallback();
  10327. var type = gl.FLOAT;
  10328. if ( array instanceof Float32Array ) {
  10329. type = gl.FLOAT;
  10330. } else if ( array instanceof Float64Array ) {
  10331. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  10332. } else if ( array instanceof Uint16Array ) {
  10333. type = gl.UNSIGNED_SHORT;
  10334. } else if ( array instanceof Int16Array ) {
  10335. type = gl.SHORT;
  10336. } else if ( array instanceof Uint32Array ) {
  10337. type = gl.UNSIGNED_INT;
  10338. } else if ( array instanceof Int32Array ) {
  10339. type = gl.INT;
  10340. } else if ( array instanceof Int8Array ) {
  10341. type = gl.BYTE;
  10342. } else if ( array instanceof Uint8Array ) {
  10343. type = gl.UNSIGNED_BYTE;
  10344. }
  10345. return {
  10346. buffer: buffer,
  10347. type: type,
  10348. bytesPerElement: array.BYTES_PER_ELEMENT,
  10349. version: attribute.version
  10350. };
  10351. }
  10352. function updateBuffer( buffer, attribute, bufferType ) {
  10353. var array = attribute.array;
  10354. var updateRange = attribute.updateRange;
  10355. gl.bindBuffer( bufferType, buffer );
  10356. if ( attribute.dynamic === false ) {
  10357. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  10358. } else if ( updateRange.count === - 1 ) {
  10359. // Not using update ranges
  10360. gl.bufferSubData( bufferType, 0, array );
  10361. } else if ( updateRange.count === 0 ) {
  10362. 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.' );
  10363. } else {
  10364. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  10365. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  10366. updateRange.count = -1; // reset range
  10367. }
  10368. }
  10369. //
  10370. function get( attribute ) {
  10371. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10372. return buffers[ attribute.uuid ];
  10373. }
  10374. function remove( attribute ) {
  10375. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10376. var data = buffers[ attribute.uuid ];
  10377. if ( data ) {
  10378. gl.deleteBuffer( data.buffer );
  10379. delete buffers[ attribute.uuid ];
  10380. }
  10381. }
  10382. function update( attribute, bufferType ) {
  10383. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10384. var data = buffers[ attribute.uuid ];
  10385. if ( data === undefined ) {
  10386. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  10387. } else if ( data.version < attribute.version ) {
  10388. updateBuffer( data.buffer, attribute, bufferType );
  10389. data.version = attribute.version;
  10390. }
  10391. }
  10392. return {
  10393. get: get,
  10394. remove: remove,
  10395. update: update
  10396. };
  10397. }
  10398. /**
  10399. * @author mrdoob / http://mrdoob.com/
  10400. * @author WestLangley / http://github.com/WestLangley
  10401. * @author bhouston / http://clara.io
  10402. */
  10403. function Euler( x, y, z, order ) {
  10404. this._x = x || 0;
  10405. this._y = y || 0;
  10406. this._z = z || 0;
  10407. this._order = order || Euler.DefaultOrder;
  10408. }
  10409. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  10410. Euler.DefaultOrder = 'XYZ';
  10411. Object.defineProperties( Euler.prototype, {
  10412. x: {
  10413. get: function () {
  10414. return this._x;
  10415. },
  10416. set: function ( value ) {
  10417. this._x = value;
  10418. this.onChangeCallback();
  10419. }
  10420. },
  10421. y: {
  10422. get: function () {
  10423. return this._y;
  10424. },
  10425. set: function ( value ) {
  10426. this._y = value;
  10427. this.onChangeCallback();
  10428. }
  10429. },
  10430. z: {
  10431. get: function () {
  10432. return this._z;
  10433. },
  10434. set: function ( value ) {
  10435. this._z = value;
  10436. this.onChangeCallback();
  10437. }
  10438. },
  10439. order: {
  10440. get: function () {
  10441. return this._order;
  10442. },
  10443. set: function ( value ) {
  10444. this._order = value;
  10445. this.onChangeCallback();
  10446. }
  10447. }
  10448. } );
  10449. Object.assign( Euler.prototype, {
  10450. isEuler: true,
  10451. set: function ( x, y, z, order ) {
  10452. this._x = x;
  10453. this._y = y;
  10454. this._z = z;
  10455. this._order = order || this._order;
  10456. this.onChangeCallback();
  10457. return this;
  10458. },
  10459. clone: function () {
  10460. return new this.constructor( this._x, this._y, this._z, this._order );
  10461. },
  10462. copy: function ( euler ) {
  10463. this._x = euler._x;
  10464. this._y = euler._y;
  10465. this._z = euler._z;
  10466. this._order = euler._order;
  10467. this.onChangeCallback();
  10468. return this;
  10469. },
  10470. setFromRotationMatrix: function ( m, order, update ) {
  10471. var clamp = _Math.clamp;
  10472. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10473. var te = m.elements;
  10474. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  10475. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  10476. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  10477. order = order || this._order;
  10478. if ( order === 'XYZ' ) {
  10479. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  10480. if ( Math.abs( m13 ) < 0.99999 ) {
  10481. this._x = Math.atan2( - m23, m33 );
  10482. this._z = Math.atan2( - m12, m11 );
  10483. } else {
  10484. this._x = Math.atan2( m32, m22 );
  10485. this._z = 0;
  10486. }
  10487. } else if ( order === 'YXZ' ) {
  10488. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  10489. if ( Math.abs( m23 ) < 0.99999 ) {
  10490. this._y = Math.atan2( m13, m33 );
  10491. this._z = Math.atan2( m21, m22 );
  10492. } else {
  10493. this._y = Math.atan2( - m31, m11 );
  10494. this._z = 0;
  10495. }
  10496. } else if ( order === 'ZXY' ) {
  10497. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  10498. if ( Math.abs( m32 ) < 0.99999 ) {
  10499. this._y = Math.atan2( - m31, m33 );
  10500. this._z = Math.atan2( - m12, m22 );
  10501. } else {
  10502. this._y = 0;
  10503. this._z = Math.atan2( m21, m11 );
  10504. }
  10505. } else if ( order === 'ZYX' ) {
  10506. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  10507. if ( Math.abs( m31 ) < 0.99999 ) {
  10508. this._x = Math.atan2( m32, m33 );
  10509. this._z = Math.atan2( m21, m11 );
  10510. } else {
  10511. this._x = 0;
  10512. this._z = Math.atan2( - m12, m22 );
  10513. }
  10514. } else if ( order === 'YZX' ) {
  10515. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  10516. if ( Math.abs( m21 ) < 0.99999 ) {
  10517. this._x = Math.atan2( - m23, m22 );
  10518. this._y = Math.atan2( - m31, m11 );
  10519. } else {
  10520. this._x = 0;
  10521. this._y = Math.atan2( m13, m33 );
  10522. }
  10523. } else if ( order === 'XZY' ) {
  10524. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  10525. if ( Math.abs( m12 ) < 0.99999 ) {
  10526. this._x = Math.atan2( m32, m22 );
  10527. this._y = Math.atan2( m13, m11 );
  10528. } else {
  10529. this._x = Math.atan2( - m23, m33 );
  10530. this._y = 0;
  10531. }
  10532. } else {
  10533. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  10534. }
  10535. this._order = order;
  10536. if ( update !== false ) this.onChangeCallback();
  10537. return this;
  10538. },
  10539. setFromQuaternion: function () {
  10540. var matrix = new Matrix4();
  10541. return function setFromQuaternion( q, order, update ) {
  10542. matrix.makeRotationFromQuaternion( q );
  10543. return this.setFromRotationMatrix( matrix, order, update );
  10544. };
  10545. }(),
  10546. setFromVector3: function ( v, order ) {
  10547. return this.set( v.x, v.y, v.z, order || this._order );
  10548. },
  10549. reorder: function () {
  10550. // WARNING: this discards revolution information -bhouston
  10551. var q = new Quaternion();
  10552. return function reorder( newOrder ) {
  10553. q.setFromEuler( this );
  10554. return this.setFromQuaternion( q, newOrder );
  10555. };
  10556. }(),
  10557. equals: function ( euler ) {
  10558. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10559. },
  10560. fromArray: function ( array ) {
  10561. this._x = array[ 0 ];
  10562. this._y = array[ 1 ];
  10563. this._z = array[ 2 ];
  10564. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10565. this.onChangeCallback();
  10566. return this;
  10567. },
  10568. toArray: function ( array, offset ) {
  10569. if ( array === undefined ) array = [];
  10570. if ( offset === undefined ) offset = 0;
  10571. array[ offset ] = this._x;
  10572. array[ offset + 1 ] = this._y;
  10573. array[ offset + 2 ] = this._z;
  10574. array[ offset + 3 ] = this._order;
  10575. return array;
  10576. },
  10577. toVector3: function ( optionalResult ) {
  10578. if ( optionalResult ) {
  10579. return optionalResult.set( this._x, this._y, this._z );
  10580. } else {
  10581. return new Vector3( this._x, this._y, this._z );
  10582. }
  10583. },
  10584. onChange: function ( callback ) {
  10585. this.onChangeCallback = callback;
  10586. return this;
  10587. },
  10588. onChangeCallback: function () {}
  10589. } );
  10590. /**
  10591. * @author mrdoob / http://mrdoob.com/
  10592. */
  10593. function Layers() {
  10594. this.mask = 1 | 0;
  10595. }
  10596. Object.assign( Layers.prototype, {
  10597. set: function ( channel ) {
  10598. this.mask = 1 << channel | 0;
  10599. },
  10600. enable: function ( channel ) {
  10601. this.mask |= 1 << channel | 0;
  10602. },
  10603. toggle: function ( channel ) {
  10604. this.mask ^= 1 << channel | 0;
  10605. },
  10606. disable: function ( channel ) {
  10607. this.mask &= ~ ( 1 << channel | 0 );
  10608. },
  10609. test: function ( layers ) {
  10610. return ( this.mask & layers.mask ) !== 0;
  10611. }
  10612. } );
  10613. /**
  10614. * @author mrdoob / http://mrdoob.com/
  10615. * @author mikael emtinger / http://gomo.se/
  10616. * @author alteredq / http://alteredqualia.com/
  10617. * @author WestLangley / http://github.com/WestLangley
  10618. * @author elephantatwork / www.elephantatwork.ch
  10619. */
  10620. var object3DId = 0;
  10621. function Object3D() {
  10622. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  10623. this.uuid = _Math.generateUUID();
  10624. this.name = '';
  10625. this.type = 'Object3D';
  10626. this.parent = null;
  10627. this.children = [];
  10628. this.up = Object3D.DefaultUp.clone();
  10629. var position = new Vector3();
  10630. var rotation = new Euler();
  10631. var quaternion = new Quaternion();
  10632. var scale = new Vector3( 1, 1, 1 );
  10633. function onRotationChange() {
  10634. quaternion.setFromEuler( rotation, false );
  10635. }
  10636. function onQuaternionChange() {
  10637. rotation.setFromQuaternion( quaternion, undefined, false );
  10638. }
  10639. rotation.onChange( onRotationChange );
  10640. quaternion.onChange( onQuaternionChange );
  10641. Object.defineProperties( this, {
  10642. position: {
  10643. enumerable: true,
  10644. value: position
  10645. },
  10646. rotation: {
  10647. enumerable: true,
  10648. value: rotation
  10649. },
  10650. quaternion: {
  10651. enumerable: true,
  10652. value: quaternion
  10653. },
  10654. scale: {
  10655. enumerable: true,
  10656. value: scale
  10657. },
  10658. modelViewMatrix: {
  10659. value: new Matrix4()
  10660. },
  10661. normalMatrix: {
  10662. value: new Matrix3()
  10663. }
  10664. } );
  10665. this.matrix = new Matrix4();
  10666. this.matrixWorld = new Matrix4();
  10667. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  10668. this.matrixWorldNeedsUpdate = false;
  10669. this.layers = new Layers();
  10670. this.visible = true;
  10671. this.castShadow = false;
  10672. this.receiveShadow = false;
  10673. this.frustumCulled = true;
  10674. this.renderOrder = 0;
  10675. this.userData = {};
  10676. }
  10677. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  10678. Object3D.DefaultMatrixAutoUpdate = true;
  10679. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  10680. isObject3D: true,
  10681. onBeforeRender: function () {},
  10682. onAfterRender: function () {},
  10683. applyMatrix: function ( matrix ) {
  10684. this.matrix.multiplyMatrices( matrix, this.matrix );
  10685. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10686. },
  10687. applyQuaternion: function ( q ) {
  10688. this.quaternion.premultiply( q );
  10689. return this;
  10690. },
  10691. setRotationFromAxisAngle: function ( axis, angle ) {
  10692. // assumes axis is normalized
  10693. this.quaternion.setFromAxisAngle( axis, angle );
  10694. },
  10695. setRotationFromEuler: function ( euler ) {
  10696. this.quaternion.setFromEuler( euler, true );
  10697. },
  10698. setRotationFromMatrix: function ( m ) {
  10699. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10700. this.quaternion.setFromRotationMatrix( m );
  10701. },
  10702. setRotationFromQuaternion: function ( q ) {
  10703. // assumes q is normalized
  10704. this.quaternion.copy( q );
  10705. },
  10706. rotateOnAxis: function () {
  10707. // rotate object on axis in object space
  10708. // axis is assumed to be normalized
  10709. var q1 = new Quaternion();
  10710. return function rotateOnAxis( axis, angle ) {
  10711. q1.setFromAxisAngle( axis, angle );
  10712. this.quaternion.multiply( q1 );
  10713. return this;
  10714. };
  10715. }(),
  10716. rotateX: function () {
  10717. var v1 = new Vector3( 1, 0, 0 );
  10718. return function rotateX( angle ) {
  10719. return this.rotateOnAxis( v1, angle );
  10720. };
  10721. }(),
  10722. rotateY: function () {
  10723. var v1 = new Vector3( 0, 1, 0 );
  10724. return function rotateY( angle ) {
  10725. return this.rotateOnAxis( v1, angle );
  10726. };
  10727. }(),
  10728. rotateZ: function () {
  10729. var v1 = new Vector3( 0, 0, 1 );
  10730. return function rotateZ( angle ) {
  10731. return this.rotateOnAxis( v1, angle );
  10732. };
  10733. }(),
  10734. translateOnAxis: function () {
  10735. // translate object by distance along axis in object space
  10736. // axis is assumed to be normalized
  10737. var v1 = new Vector3();
  10738. return function translateOnAxis( axis, distance ) {
  10739. v1.copy( axis ).applyQuaternion( this.quaternion );
  10740. this.position.add( v1.multiplyScalar( distance ) );
  10741. return this;
  10742. };
  10743. }(),
  10744. translateX: function () {
  10745. var v1 = new Vector3( 1, 0, 0 );
  10746. return function translateX( distance ) {
  10747. return this.translateOnAxis( v1, distance );
  10748. };
  10749. }(),
  10750. translateY: function () {
  10751. var v1 = new Vector3( 0, 1, 0 );
  10752. return function translateY( distance ) {
  10753. return this.translateOnAxis( v1, distance );
  10754. };
  10755. }(),
  10756. translateZ: function () {
  10757. var v1 = new Vector3( 0, 0, 1 );
  10758. return function translateZ( distance ) {
  10759. return this.translateOnAxis( v1, distance );
  10760. };
  10761. }(),
  10762. localToWorld: function ( vector ) {
  10763. return vector.applyMatrix4( this.matrixWorld );
  10764. },
  10765. worldToLocal: function () {
  10766. var m1 = new Matrix4();
  10767. return function worldToLocal( vector ) {
  10768. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  10769. };
  10770. }(),
  10771. lookAt: function () {
  10772. // This method does not support objects with rotated and/or translated parent(s)
  10773. var m1 = new Matrix4();
  10774. return function lookAt( vector ) {
  10775. if ( this.isCamera ) {
  10776. m1.lookAt( this.position, vector, this.up );
  10777. } else {
  10778. m1.lookAt( vector, this.position, this.up );
  10779. }
  10780. this.quaternion.setFromRotationMatrix( m1 );
  10781. };
  10782. }(),
  10783. add: function ( object ) {
  10784. if ( arguments.length > 1 ) {
  10785. for ( var i = 0; i < arguments.length; i ++ ) {
  10786. this.add( arguments[ i ] );
  10787. }
  10788. return this;
  10789. }
  10790. if ( object === this ) {
  10791. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  10792. return this;
  10793. }
  10794. if ( ( object && object.isObject3D ) ) {
  10795. if ( object.parent !== null ) {
  10796. object.parent.remove( object );
  10797. }
  10798. object.parent = this;
  10799. object.dispatchEvent( { type: 'added' } );
  10800. this.children.push( object );
  10801. } else {
  10802. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  10803. }
  10804. return this;
  10805. },
  10806. remove: function ( object ) {
  10807. if ( arguments.length > 1 ) {
  10808. for ( var i = 0; i < arguments.length; i ++ ) {
  10809. this.remove( arguments[ i ] );
  10810. }
  10811. return this;
  10812. }
  10813. var index = this.children.indexOf( object );
  10814. if ( index !== - 1 ) {
  10815. object.parent = null;
  10816. object.dispatchEvent( { type: 'removed' } );
  10817. this.children.splice( index, 1 );
  10818. }
  10819. return this;
  10820. },
  10821. getObjectById: function ( id ) {
  10822. return this.getObjectByProperty( 'id', id );
  10823. },
  10824. getObjectByName: function ( name ) {
  10825. return this.getObjectByProperty( 'name', name );
  10826. },
  10827. getObjectByProperty: function ( name, value ) {
  10828. if ( this[ name ] === value ) return this;
  10829. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  10830. var child = this.children[ i ];
  10831. var object = child.getObjectByProperty( name, value );
  10832. if ( object !== undefined ) {
  10833. return object;
  10834. }
  10835. }
  10836. return undefined;
  10837. },
  10838. getWorldPosition: function ( optionalTarget ) {
  10839. var result = optionalTarget || new Vector3();
  10840. this.updateMatrixWorld( true );
  10841. return result.setFromMatrixPosition( this.matrixWorld );
  10842. },
  10843. getWorldQuaternion: function () {
  10844. var position = new Vector3();
  10845. var scale = new Vector3();
  10846. return function getWorldQuaternion( optionalTarget ) {
  10847. var result = optionalTarget || new Quaternion();
  10848. this.updateMatrixWorld( true );
  10849. this.matrixWorld.decompose( position, result, scale );
  10850. return result;
  10851. };
  10852. }(),
  10853. getWorldRotation: function () {
  10854. var quaternion = new Quaternion();
  10855. return function getWorldRotation( optionalTarget ) {
  10856. var result = optionalTarget || new Euler();
  10857. this.getWorldQuaternion( quaternion );
  10858. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  10859. };
  10860. }(),
  10861. getWorldScale: function () {
  10862. var position = new Vector3();
  10863. var quaternion = new Quaternion();
  10864. return function getWorldScale( optionalTarget ) {
  10865. var result = optionalTarget || new Vector3();
  10866. this.updateMatrixWorld( true );
  10867. this.matrixWorld.decompose( position, quaternion, result );
  10868. return result;
  10869. };
  10870. }(),
  10871. getWorldDirection: function () {
  10872. var quaternion = new Quaternion();
  10873. return function getWorldDirection( optionalTarget ) {
  10874. var result = optionalTarget || new Vector3();
  10875. this.getWorldQuaternion( quaternion );
  10876. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  10877. };
  10878. }(),
  10879. raycast: function () {},
  10880. traverse: function ( callback ) {
  10881. callback( this );
  10882. var children = this.children;
  10883. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10884. children[ i ].traverse( callback );
  10885. }
  10886. },
  10887. traverseVisible: function ( callback ) {
  10888. if ( this.visible === false ) return;
  10889. callback( this );
  10890. var children = this.children;
  10891. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10892. children[ i ].traverseVisible( callback );
  10893. }
  10894. },
  10895. traverseAncestors: function ( callback ) {
  10896. var parent = this.parent;
  10897. if ( parent !== null ) {
  10898. callback( parent );
  10899. parent.traverseAncestors( callback );
  10900. }
  10901. },
  10902. updateMatrix: function () {
  10903. this.matrix.compose( this.position, this.quaternion, this.scale );
  10904. this.matrixWorldNeedsUpdate = true;
  10905. },
  10906. updateMatrixWorld: function ( force ) {
  10907. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10908. if ( this.matrixWorldNeedsUpdate || force ) {
  10909. if ( this.parent === null ) {
  10910. this.matrixWorld.copy( this.matrix );
  10911. } else {
  10912. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10913. }
  10914. this.matrixWorldNeedsUpdate = false;
  10915. force = true;
  10916. }
  10917. // update children
  10918. var children = this.children;
  10919. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10920. children[ i ].updateMatrixWorld( force );
  10921. }
  10922. },
  10923. toJSON: function ( meta ) {
  10924. // meta is '' when called from JSON.stringify
  10925. var isRootObject = ( meta === undefined || meta === '' );
  10926. var output = {};
  10927. // meta is a hash used to collect geometries, materials.
  10928. // not providing it implies that this is the root object
  10929. // being serialized.
  10930. if ( isRootObject ) {
  10931. // initialize meta obj
  10932. meta = {
  10933. geometries: {},
  10934. materials: {},
  10935. textures: {},
  10936. images: {}
  10937. };
  10938. output.metadata = {
  10939. version: 4.5,
  10940. type: 'Object',
  10941. generator: 'Object3D.toJSON'
  10942. };
  10943. }
  10944. // standard Object3D serialization
  10945. var object = {};
  10946. object.uuid = this.uuid;
  10947. object.type = this.type;
  10948. if ( this.name !== '' ) object.name = this.name;
  10949. if ( this.castShadow === true ) object.castShadow = true;
  10950. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10951. if ( this.visible === false ) object.visible = false;
  10952. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  10953. object.matrix = this.matrix.toArray();
  10954. //
  10955. function serialize( library, element ) {
  10956. if ( library[ element.uuid ] === undefined ) {
  10957. library[ element.uuid ] = element.toJSON( meta );
  10958. }
  10959. return element.uuid;
  10960. }
  10961. if ( this.geometry !== undefined ) {
  10962. object.geometry = serialize( meta.geometries, this.geometry );
  10963. }
  10964. if ( this.material !== undefined ) {
  10965. if ( Array.isArray( this.material ) ) {
  10966. var uuids = [];
  10967. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  10968. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10969. }
  10970. object.material = uuids;
  10971. } else {
  10972. object.material = serialize( meta.materials, this.material );
  10973. }
  10974. }
  10975. //
  10976. if ( this.children.length > 0 ) {
  10977. object.children = [];
  10978. for ( var i = 0; i < this.children.length; i ++ ) {
  10979. object.children.push( this.children[ i ].toJSON( meta ).object );
  10980. }
  10981. }
  10982. if ( isRootObject ) {
  10983. var geometries = extractFromCache( meta.geometries );
  10984. var materials = extractFromCache( meta.materials );
  10985. var textures = extractFromCache( meta.textures );
  10986. var images = extractFromCache( meta.images );
  10987. if ( geometries.length > 0 ) output.geometries = geometries;
  10988. if ( materials.length > 0 ) output.materials = materials;
  10989. if ( textures.length > 0 ) output.textures = textures;
  10990. if ( images.length > 0 ) output.images = images;
  10991. }
  10992. output.object = object;
  10993. return output;
  10994. // extract data from the cache hash
  10995. // remove metadata on each item
  10996. // and return as array
  10997. function extractFromCache( cache ) {
  10998. var values = [];
  10999. for ( var key in cache ) {
  11000. var data = cache[ key ];
  11001. delete data.metadata;
  11002. values.push( data );
  11003. }
  11004. return values;
  11005. }
  11006. },
  11007. clone: function ( recursive ) {
  11008. return new this.constructor().copy( this, recursive );
  11009. },
  11010. copy: function ( source, recursive ) {
  11011. if ( recursive === undefined ) recursive = true;
  11012. this.name = source.name;
  11013. this.up.copy( source.up );
  11014. this.position.copy( source.position );
  11015. this.quaternion.copy( source.quaternion );
  11016. this.scale.copy( source.scale );
  11017. this.matrix.copy( source.matrix );
  11018. this.matrixWorld.copy( source.matrixWorld );
  11019. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11020. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11021. this.layers.mask = source.layers.mask;
  11022. this.visible = source.visible;
  11023. this.castShadow = source.castShadow;
  11024. this.receiveShadow = source.receiveShadow;
  11025. this.frustumCulled = source.frustumCulled;
  11026. this.renderOrder = source.renderOrder;
  11027. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11028. if ( recursive === true ) {
  11029. for ( var i = 0; i < source.children.length; i ++ ) {
  11030. var child = source.children[ i ];
  11031. this.add( child.clone() );
  11032. }
  11033. }
  11034. return this;
  11035. }
  11036. } );
  11037. /**
  11038. * @author mrdoob / http://mrdoob.com/
  11039. * @author mikael emtinger / http://gomo.se/
  11040. * @author WestLangley / http://github.com/WestLangley
  11041. */
  11042. function Camera() {
  11043. Object3D.call( this );
  11044. this.type = 'Camera';
  11045. this.matrixWorldInverse = new Matrix4();
  11046. this.projectionMatrix = new Matrix4();
  11047. }
  11048. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  11049. constructor: Camera,
  11050. isCamera: true,
  11051. copy: function ( source, recursive ) {
  11052. Object3D.prototype.copy.call( this, source, recursive );
  11053. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  11054. this.projectionMatrix.copy( source.projectionMatrix );
  11055. return this;
  11056. },
  11057. getWorldDirection: function () {
  11058. var quaternion = new Quaternion();
  11059. return function getWorldDirection( optionalTarget ) {
  11060. var result = optionalTarget || new Vector3();
  11061. this.getWorldQuaternion( quaternion );
  11062. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  11063. };
  11064. }(),
  11065. updateMatrixWorld: function ( force ) {
  11066. Object3D.prototype.updateMatrixWorld.call( this, force );
  11067. this.matrixWorldInverse.getInverse( this.matrixWorld );
  11068. },
  11069. clone: function () {
  11070. return new this.constructor().copy( this );
  11071. }
  11072. } );
  11073. /**
  11074. * @author alteredq / http://alteredqualia.com/
  11075. * @author arose / http://github.com/arose
  11076. */
  11077. function OrthographicCamera( left, right, top, bottom, near, far ) {
  11078. Camera.call( this );
  11079. this.type = 'OrthographicCamera';
  11080. this.zoom = 1;
  11081. this.view = null;
  11082. this.left = left;
  11083. this.right = right;
  11084. this.top = top;
  11085. this.bottom = bottom;
  11086. this.near = ( near !== undefined ) ? near : 0.1;
  11087. this.far = ( far !== undefined ) ? far : 2000;
  11088. this.updateProjectionMatrix();
  11089. }
  11090. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11091. constructor: OrthographicCamera,
  11092. isOrthographicCamera: true,
  11093. copy: function ( source, recursive ) {
  11094. Camera.prototype.copy.call( this, source, recursive );
  11095. this.left = source.left;
  11096. this.right = source.right;
  11097. this.top = source.top;
  11098. this.bottom = source.bottom;
  11099. this.near = source.near;
  11100. this.far = source.far;
  11101. this.zoom = source.zoom;
  11102. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11103. return this;
  11104. },
  11105. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  11106. this.view = {
  11107. fullWidth: fullWidth,
  11108. fullHeight: fullHeight,
  11109. offsetX: x,
  11110. offsetY: y,
  11111. width: width,
  11112. height: height
  11113. };
  11114. this.updateProjectionMatrix();
  11115. },
  11116. clearViewOffset: function() {
  11117. this.view = null;
  11118. this.updateProjectionMatrix();
  11119. },
  11120. updateProjectionMatrix: function () {
  11121. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  11122. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  11123. var cx = ( this.right + this.left ) / 2;
  11124. var cy = ( this.top + this.bottom ) / 2;
  11125. var left = cx - dx;
  11126. var right = cx + dx;
  11127. var top = cy + dy;
  11128. var bottom = cy - dy;
  11129. if ( this.view !== null ) {
  11130. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  11131. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  11132. var scaleW = ( this.right - this.left ) / this.view.width;
  11133. var scaleH = ( this.top - this.bottom ) / this.view.height;
  11134. left += scaleW * ( this.view.offsetX / zoomW );
  11135. right = left + scaleW * ( this.view.width / zoomW );
  11136. top -= scaleH * ( this.view.offsetY / zoomH );
  11137. bottom = top - scaleH * ( this.view.height / zoomH );
  11138. }
  11139. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  11140. },
  11141. toJSON: function ( meta ) {
  11142. var data = Object3D.prototype.toJSON.call( this, meta );
  11143. data.object.zoom = this.zoom;
  11144. data.object.left = this.left;
  11145. data.object.right = this.right;
  11146. data.object.top = this.top;
  11147. data.object.bottom = this.bottom;
  11148. data.object.near = this.near;
  11149. data.object.far = this.far;
  11150. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11151. return data;
  11152. }
  11153. } );
  11154. /**
  11155. * @author mrdoob / http://mrdoob.com/
  11156. * @author greggman / http://games.greggman.com/
  11157. * @author zz85 / http://www.lab4games.net/zz85/blog
  11158. * @author tschw
  11159. */
  11160. function PerspectiveCamera( fov, aspect, near, far ) {
  11161. Camera.call( this );
  11162. this.type = 'PerspectiveCamera';
  11163. this.fov = fov !== undefined ? fov : 50;
  11164. this.zoom = 1;
  11165. this.near = near !== undefined ? near : 0.1;
  11166. this.far = far !== undefined ? far : 2000;
  11167. this.focus = 10;
  11168. this.aspect = aspect !== undefined ? aspect : 1;
  11169. this.view = null;
  11170. this.filmGauge = 35; // width of the film (default in millimeters)
  11171. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  11172. this.updateProjectionMatrix();
  11173. }
  11174. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11175. constructor: PerspectiveCamera,
  11176. isPerspectiveCamera: true,
  11177. copy: function ( source, recursive ) {
  11178. Camera.prototype.copy.call( this, source, recursive );
  11179. this.fov = source.fov;
  11180. this.zoom = source.zoom;
  11181. this.near = source.near;
  11182. this.far = source.far;
  11183. this.focus = source.focus;
  11184. this.aspect = source.aspect;
  11185. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11186. this.filmGauge = source.filmGauge;
  11187. this.filmOffset = source.filmOffset;
  11188. return this;
  11189. },
  11190. /**
  11191. * Sets the FOV by focal length in respect to the current .filmGauge.
  11192. *
  11193. * The default film gauge is 35, so that the focal length can be specified for
  11194. * a 35mm (full frame) camera.
  11195. *
  11196. * Values for focal length and film gauge must have the same unit.
  11197. */
  11198. setFocalLength: function ( focalLength ) {
  11199. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  11200. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  11201. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  11202. this.updateProjectionMatrix();
  11203. },
  11204. /**
  11205. * Calculates the focal length from the current .fov and .filmGauge.
  11206. */
  11207. getFocalLength: function () {
  11208. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  11209. return 0.5 * this.getFilmHeight() / vExtentSlope;
  11210. },
  11211. getEffectiveFOV: function () {
  11212. return _Math.RAD2DEG * 2 * Math.atan(
  11213. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  11214. },
  11215. getFilmWidth: function () {
  11216. // film not completely covered in portrait format (aspect < 1)
  11217. return this.filmGauge * Math.min( this.aspect, 1 );
  11218. },
  11219. getFilmHeight: function () {
  11220. // film not completely covered in landscape format (aspect > 1)
  11221. return this.filmGauge / Math.max( this.aspect, 1 );
  11222. },
  11223. /**
  11224. * Sets an offset in a larger frustum. This is useful for multi-window or
  11225. * multi-monitor/multi-machine setups.
  11226. *
  11227. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  11228. * the monitors are in grid like this
  11229. *
  11230. * +---+---+---+
  11231. * | A | B | C |
  11232. * +---+---+---+
  11233. * | D | E | F |
  11234. * +---+---+---+
  11235. *
  11236. * then for each monitor you would call it like this
  11237. *
  11238. * var w = 1920;
  11239. * var h = 1080;
  11240. * var fullWidth = w * 3;
  11241. * var fullHeight = h * 2;
  11242. *
  11243. * --A--
  11244. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  11245. * --B--
  11246. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  11247. * --C--
  11248. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  11249. * --D--
  11250. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  11251. * --E--
  11252. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  11253. * --F--
  11254. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  11255. *
  11256. * Note there is no reason monitors have to be the same size or in a grid.
  11257. */
  11258. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  11259. this.aspect = fullWidth / fullHeight;
  11260. this.view = {
  11261. fullWidth: fullWidth,
  11262. fullHeight: fullHeight,
  11263. offsetX: x,
  11264. offsetY: y,
  11265. width: width,
  11266. height: height
  11267. };
  11268. this.updateProjectionMatrix();
  11269. },
  11270. clearViewOffset: function () {
  11271. this.view = null;
  11272. this.updateProjectionMatrix();
  11273. },
  11274. updateProjectionMatrix: function () {
  11275. var near = this.near,
  11276. top = near * Math.tan(
  11277. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  11278. height = 2 * top,
  11279. width = this.aspect * height,
  11280. left = - 0.5 * width,
  11281. view = this.view;
  11282. if ( view !== null ) {
  11283. var fullWidth = view.fullWidth,
  11284. fullHeight = view.fullHeight;
  11285. left += view.offsetX * width / fullWidth;
  11286. top -= view.offsetY * height / fullHeight;
  11287. width *= view.width / fullWidth;
  11288. height *= view.height / fullHeight;
  11289. }
  11290. var skew = this.filmOffset;
  11291. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  11292. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  11293. },
  11294. toJSON: function ( meta ) {
  11295. var data = Object3D.prototype.toJSON.call( this, meta );
  11296. data.object.fov = this.fov;
  11297. data.object.zoom = this.zoom;
  11298. data.object.near = this.near;
  11299. data.object.far = this.far;
  11300. data.object.focus = this.focus;
  11301. data.object.aspect = this.aspect;
  11302. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11303. data.object.filmGauge = this.filmGauge;
  11304. data.object.filmOffset = this.filmOffset;
  11305. return data;
  11306. }
  11307. } );
  11308. /**
  11309. * @author mrdoob / http://mrdoob.com/
  11310. * @author alteredq / http://alteredqualia.com/
  11311. */
  11312. function Face3( a, b, c, normal, color, materialIndex ) {
  11313. this.a = a;
  11314. this.b = b;
  11315. this.c = c;
  11316. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  11317. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  11318. this.color = ( color && color.isColor ) ? color : new Color();
  11319. this.vertexColors = Array.isArray( color ) ? color : [];
  11320. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  11321. }
  11322. Object.assign( Face3.prototype, {
  11323. clone: function () {
  11324. return new this.constructor().copy( this );
  11325. },
  11326. copy: function ( source ) {
  11327. this.a = source.a;
  11328. this.b = source.b;
  11329. this.c = source.c;
  11330. this.normal.copy( source.normal );
  11331. this.color.copy( source.color );
  11332. this.materialIndex = source.materialIndex;
  11333. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  11334. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  11335. }
  11336. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  11337. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  11338. }
  11339. return this;
  11340. }
  11341. } );
  11342. /**
  11343. * @author mrdoob / http://mrdoob.com/
  11344. * @author kile / http://kile.stravaganza.org/
  11345. * @author alteredq / http://alteredqualia.com/
  11346. * @author mikael emtinger / http://gomo.se/
  11347. * @author zz85 / http://www.lab4games.net/zz85/blog
  11348. * @author bhouston / http://clara.io
  11349. */
  11350. var count = 0;
  11351. function GeometryIdCount() { return count++; }
  11352. function Geometry() {
  11353. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  11354. this.uuid = _Math.generateUUID();
  11355. this.name = '';
  11356. this.type = 'Geometry';
  11357. this.vertices = [];
  11358. this.colors = [];
  11359. this.faces = [];
  11360. this.faceVertexUvs = [[]];
  11361. this.morphTargets = [];
  11362. this.morphNormals = [];
  11363. this.skinWeights = [];
  11364. this.skinIndices = [];
  11365. this.lineDistances = [];
  11366. this.boundingBox = null;
  11367. this.boundingSphere = null;
  11368. // update flags
  11369. this.elementsNeedUpdate = false;
  11370. this.verticesNeedUpdate = false;
  11371. this.uvsNeedUpdate = false;
  11372. this.normalsNeedUpdate = false;
  11373. this.colorsNeedUpdate = false;
  11374. this.lineDistancesNeedUpdate = false;
  11375. this.groupsNeedUpdate = false;
  11376. }
  11377. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  11378. isGeometry: true,
  11379. applyMatrix: function ( matrix ) {
  11380. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11381. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  11382. var vertex = this.vertices[ i ];
  11383. vertex.applyMatrix4( matrix );
  11384. }
  11385. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  11386. var face = this.faces[ i ];
  11387. face.normal.applyMatrix3( normalMatrix ).normalize();
  11388. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  11389. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  11390. }
  11391. }
  11392. if ( this.boundingBox !== null ) {
  11393. this.computeBoundingBox();
  11394. }
  11395. if ( this.boundingSphere !== null ) {
  11396. this.computeBoundingSphere();
  11397. }
  11398. this.verticesNeedUpdate = true;
  11399. this.normalsNeedUpdate = true;
  11400. return this;
  11401. },
  11402. rotateX: function () {
  11403. // rotate geometry around world x-axis
  11404. var m1 = new Matrix4();
  11405. return function rotateX( angle ) {
  11406. m1.makeRotationX( angle );
  11407. this.applyMatrix( m1 );
  11408. return this;
  11409. };
  11410. }(),
  11411. rotateY: function () {
  11412. // rotate geometry around world y-axis
  11413. var m1 = new Matrix4();
  11414. return function rotateY( angle ) {
  11415. m1.makeRotationY( angle );
  11416. this.applyMatrix( m1 );
  11417. return this;
  11418. };
  11419. }(),
  11420. rotateZ: function () {
  11421. // rotate geometry around world z-axis
  11422. var m1 = new Matrix4();
  11423. return function rotateZ( angle ) {
  11424. m1.makeRotationZ( angle );
  11425. this.applyMatrix( m1 );
  11426. return this;
  11427. };
  11428. }(),
  11429. translate: function () {
  11430. // translate geometry
  11431. var m1 = new Matrix4();
  11432. return function translate( x, y, z ) {
  11433. m1.makeTranslation( x, y, z );
  11434. this.applyMatrix( m1 );
  11435. return this;
  11436. };
  11437. }(),
  11438. scale: function () {
  11439. // scale geometry
  11440. var m1 = new Matrix4();
  11441. return function scale( x, y, z ) {
  11442. m1.makeScale( x, y, z );
  11443. this.applyMatrix( m1 );
  11444. return this;
  11445. };
  11446. }(),
  11447. lookAt: function () {
  11448. var obj = new Object3D();
  11449. return function lookAt( vector ) {
  11450. obj.lookAt( vector );
  11451. obj.updateMatrix();
  11452. this.applyMatrix( obj.matrix );
  11453. };
  11454. }(),
  11455. fromBufferGeometry: function ( geometry ) {
  11456. var scope = this;
  11457. var indices = geometry.index !== null ? geometry.index.array : undefined;
  11458. var attributes = geometry.attributes;
  11459. var positions = attributes.position.array;
  11460. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  11461. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  11462. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  11463. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  11464. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  11465. var tempNormals = [];
  11466. var tempUVs = [];
  11467. var tempUVs2 = [];
  11468. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  11469. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  11470. if ( normals !== undefined ) {
  11471. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  11472. }
  11473. if ( colors !== undefined ) {
  11474. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  11475. }
  11476. if ( uvs !== undefined ) {
  11477. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  11478. }
  11479. if ( uvs2 !== undefined ) {
  11480. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  11481. }
  11482. }
  11483. function addFace( a, b, c, materialIndex ) {
  11484. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  11485. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  11486. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  11487. scope.faces.push( face );
  11488. if ( uvs !== undefined ) {
  11489. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  11490. }
  11491. if ( uvs2 !== undefined ) {
  11492. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  11493. }
  11494. }
  11495. var groups = geometry.groups;
  11496. if ( groups.length > 0 ) {
  11497. for ( var i = 0; i < groups.length; i ++ ) {
  11498. var group = groups[ i ];
  11499. var start = group.start;
  11500. var count = group.count;
  11501. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  11502. if ( indices !== undefined ) {
  11503. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  11504. } else {
  11505. addFace( j, j + 1, j + 2, group.materialIndex );
  11506. }
  11507. }
  11508. }
  11509. } else {
  11510. if ( indices !== undefined ) {
  11511. for ( var i = 0; i < indices.length; i += 3 ) {
  11512. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  11513. }
  11514. } else {
  11515. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  11516. addFace( i, i + 1, i + 2 );
  11517. }
  11518. }
  11519. }
  11520. this.computeFaceNormals();
  11521. if ( geometry.boundingBox !== null ) {
  11522. this.boundingBox = geometry.boundingBox.clone();
  11523. }
  11524. if ( geometry.boundingSphere !== null ) {
  11525. this.boundingSphere = geometry.boundingSphere.clone();
  11526. }
  11527. return this;
  11528. },
  11529. center: function () {
  11530. this.computeBoundingBox();
  11531. var offset = this.boundingBox.getCenter().negate();
  11532. this.translate( offset.x, offset.y, offset.z );
  11533. return offset;
  11534. },
  11535. normalize: function () {
  11536. this.computeBoundingSphere();
  11537. var center = this.boundingSphere.center;
  11538. var radius = this.boundingSphere.radius;
  11539. var s = radius === 0 ? 1 : 1.0 / radius;
  11540. var matrix = new Matrix4();
  11541. matrix.set(
  11542. s, 0, 0, - s * center.x,
  11543. 0, s, 0, - s * center.y,
  11544. 0, 0, s, - s * center.z,
  11545. 0, 0, 0, 1
  11546. );
  11547. this.applyMatrix( matrix );
  11548. return this;
  11549. },
  11550. computeFaceNormals: function () {
  11551. var cb = new Vector3(), ab = new Vector3();
  11552. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11553. var face = this.faces[ f ];
  11554. var vA = this.vertices[ face.a ];
  11555. var vB = this.vertices[ face.b ];
  11556. var vC = this.vertices[ face.c ];
  11557. cb.subVectors( vC, vB );
  11558. ab.subVectors( vA, vB );
  11559. cb.cross( ab );
  11560. cb.normalize();
  11561. face.normal.copy( cb );
  11562. }
  11563. },
  11564. computeVertexNormals: function ( areaWeighted ) {
  11565. if ( areaWeighted === undefined ) areaWeighted = true;
  11566. var v, vl, f, fl, face, vertices;
  11567. vertices = new Array( this.vertices.length );
  11568. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11569. vertices[ v ] = new Vector3();
  11570. }
  11571. if ( areaWeighted ) {
  11572. // vertex normals weighted by triangle areas
  11573. // http://www.iquilezles.org/www/articles/normals/normals.htm
  11574. var vA, vB, vC;
  11575. var cb = new Vector3(), ab = new Vector3();
  11576. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11577. face = this.faces[ f ];
  11578. vA = this.vertices[ face.a ];
  11579. vB = this.vertices[ face.b ];
  11580. vC = this.vertices[ face.c ];
  11581. cb.subVectors( vC, vB );
  11582. ab.subVectors( vA, vB );
  11583. cb.cross( ab );
  11584. vertices[ face.a ].add( cb );
  11585. vertices[ face.b ].add( cb );
  11586. vertices[ face.c ].add( cb );
  11587. }
  11588. } else {
  11589. this.computeFaceNormals();
  11590. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11591. face = this.faces[ f ];
  11592. vertices[ face.a ].add( face.normal );
  11593. vertices[ face.b ].add( face.normal );
  11594. vertices[ face.c ].add( face.normal );
  11595. }
  11596. }
  11597. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11598. vertices[ v ].normalize();
  11599. }
  11600. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11601. face = this.faces[ f ];
  11602. var vertexNormals = face.vertexNormals;
  11603. if ( vertexNormals.length === 3 ) {
  11604. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  11605. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  11606. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  11607. } else {
  11608. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  11609. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  11610. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  11611. }
  11612. }
  11613. if ( this.faces.length > 0 ) {
  11614. this.normalsNeedUpdate = true;
  11615. }
  11616. },
  11617. computeFlatVertexNormals: function () {
  11618. var f, fl, face;
  11619. this.computeFaceNormals();
  11620. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11621. face = this.faces[ f ];
  11622. var vertexNormals = face.vertexNormals;
  11623. if ( vertexNormals.length === 3 ) {
  11624. vertexNormals[ 0 ].copy( face.normal );
  11625. vertexNormals[ 1 ].copy( face.normal );
  11626. vertexNormals[ 2 ].copy( face.normal );
  11627. } else {
  11628. vertexNormals[ 0 ] = face.normal.clone();
  11629. vertexNormals[ 1 ] = face.normal.clone();
  11630. vertexNormals[ 2 ] = face.normal.clone();
  11631. }
  11632. }
  11633. if ( this.faces.length > 0 ) {
  11634. this.normalsNeedUpdate = true;
  11635. }
  11636. },
  11637. computeMorphNormals: function () {
  11638. var i, il, f, fl, face;
  11639. // save original normals
  11640. // - create temp variables on first access
  11641. // otherwise just copy (for faster repeated calls)
  11642. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11643. face = this.faces[ f ];
  11644. if ( ! face.__originalFaceNormal ) {
  11645. face.__originalFaceNormal = face.normal.clone();
  11646. } else {
  11647. face.__originalFaceNormal.copy( face.normal );
  11648. }
  11649. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  11650. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  11651. if ( ! face.__originalVertexNormals[ i ] ) {
  11652. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  11653. } else {
  11654. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  11655. }
  11656. }
  11657. }
  11658. // use temp geometry to compute face and vertex normals for each morph
  11659. var tmpGeo = new Geometry();
  11660. tmpGeo.faces = this.faces;
  11661. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  11662. // create on first access
  11663. if ( ! this.morphNormals[ i ] ) {
  11664. this.morphNormals[ i ] = {};
  11665. this.morphNormals[ i ].faceNormals = [];
  11666. this.morphNormals[ i ].vertexNormals = [];
  11667. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  11668. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  11669. var faceNormal, vertexNormals;
  11670. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11671. faceNormal = new Vector3();
  11672. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  11673. dstNormalsFace.push( faceNormal );
  11674. dstNormalsVertex.push( vertexNormals );
  11675. }
  11676. }
  11677. var morphNormals = this.morphNormals[ i ];
  11678. // set vertices to morph target
  11679. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  11680. // compute morph normals
  11681. tmpGeo.computeFaceNormals();
  11682. tmpGeo.computeVertexNormals();
  11683. // store morph normals
  11684. var faceNormal, vertexNormals;
  11685. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11686. face = this.faces[ f ];
  11687. faceNormal = morphNormals.faceNormals[ f ];
  11688. vertexNormals = morphNormals.vertexNormals[ f ];
  11689. faceNormal.copy( face.normal );
  11690. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  11691. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  11692. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  11693. }
  11694. }
  11695. // restore original normals
  11696. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11697. face = this.faces[ f ];
  11698. face.normal = face.__originalFaceNormal;
  11699. face.vertexNormals = face.__originalVertexNormals;
  11700. }
  11701. },
  11702. computeLineDistances: function () {
  11703. var d = 0;
  11704. var vertices = this.vertices;
  11705. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  11706. if ( i > 0 ) {
  11707. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  11708. }
  11709. this.lineDistances[ i ] = d;
  11710. }
  11711. },
  11712. computeBoundingBox: function () {
  11713. if ( this.boundingBox === null ) {
  11714. this.boundingBox = new Box3();
  11715. }
  11716. this.boundingBox.setFromPoints( this.vertices );
  11717. },
  11718. computeBoundingSphere: function () {
  11719. if ( this.boundingSphere === null ) {
  11720. this.boundingSphere = new Sphere();
  11721. }
  11722. this.boundingSphere.setFromPoints( this.vertices );
  11723. },
  11724. merge: function ( geometry, matrix, materialIndexOffset ) {
  11725. if ( ! ( geometry && geometry.isGeometry ) ) {
  11726. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  11727. return;
  11728. }
  11729. var normalMatrix,
  11730. vertexOffset = this.vertices.length,
  11731. vertices1 = this.vertices,
  11732. vertices2 = geometry.vertices,
  11733. faces1 = this.faces,
  11734. faces2 = geometry.faces,
  11735. uvs1 = this.faceVertexUvs[ 0 ],
  11736. uvs2 = geometry.faceVertexUvs[ 0 ],
  11737. colors1 = this.colors,
  11738. colors2 = geometry.colors;
  11739. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  11740. if ( matrix !== undefined ) {
  11741. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11742. }
  11743. // vertices
  11744. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  11745. var vertex = vertices2[ i ];
  11746. var vertexCopy = vertex.clone();
  11747. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  11748. vertices1.push( vertexCopy );
  11749. }
  11750. // colors
  11751. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  11752. colors1.push( colors2[ i ].clone() );
  11753. }
  11754. // faces
  11755. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  11756. var face = faces2[ i ], faceCopy, normal, color,
  11757. faceVertexNormals = face.vertexNormals,
  11758. faceVertexColors = face.vertexColors;
  11759. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  11760. faceCopy.normal.copy( face.normal );
  11761. if ( normalMatrix !== undefined ) {
  11762. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  11763. }
  11764. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  11765. normal = faceVertexNormals[ j ].clone();
  11766. if ( normalMatrix !== undefined ) {
  11767. normal.applyMatrix3( normalMatrix ).normalize();
  11768. }
  11769. faceCopy.vertexNormals.push( normal );
  11770. }
  11771. faceCopy.color.copy( face.color );
  11772. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  11773. color = faceVertexColors[ j ];
  11774. faceCopy.vertexColors.push( color.clone() );
  11775. }
  11776. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  11777. faces1.push( faceCopy );
  11778. }
  11779. // uvs
  11780. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  11781. var uv = uvs2[ i ], uvCopy = [];
  11782. if ( uv === undefined ) {
  11783. continue;
  11784. }
  11785. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  11786. uvCopy.push( uv[ j ].clone() );
  11787. }
  11788. uvs1.push( uvCopy );
  11789. }
  11790. },
  11791. mergeMesh: function ( mesh ) {
  11792. if ( ! ( mesh && mesh.isMesh ) ) {
  11793. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  11794. return;
  11795. }
  11796. mesh.matrixAutoUpdate && mesh.updateMatrix();
  11797. this.merge( mesh.geometry, mesh.matrix );
  11798. },
  11799. /*
  11800. * Checks for duplicate vertices with hashmap.
  11801. * Duplicated vertices are removed
  11802. * and faces' vertices are updated.
  11803. */
  11804. mergeVertices: function () {
  11805. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  11806. var unique = [], changes = [];
  11807. var v, key;
  11808. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  11809. var precision = Math.pow( 10, precisionPoints );
  11810. var i, il, face;
  11811. var indices, j, jl;
  11812. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  11813. v = this.vertices[ i ];
  11814. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  11815. if ( verticesMap[ key ] === undefined ) {
  11816. verticesMap[ key ] = i;
  11817. unique.push( this.vertices[ i ] );
  11818. changes[ i ] = unique.length - 1;
  11819. } else {
  11820. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  11821. changes[ i ] = changes[ verticesMap[ key ] ];
  11822. }
  11823. }
  11824. // if faces are completely degenerate after merging vertices, we
  11825. // have to remove them from the geometry.
  11826. var faceIndicesToRemove = [];
  11827. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  11828. face = this.faces[ i ];
  11829. face.a = changes[ face.a ];
  11830. face.b = changes[ face.b ];
  11831. face.c = changes[ face.c ];
  11832. indices = [ face.a, face.b, face.c ];
  11833. // if any duplicate vertices are found in a Face3
  11834. // we have to remove the face as nothing can be saved
  11835. for ( var n = 0; n < 3; n ++ ) {
  11836. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  11837. faceIndicesToRemove.push( i );
  11838. break;
  11839. }
  11840. }
  11841. }
  11842. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  11843. var idx = faceIndicesToRemove[ i ];
  11844. this.faces.splice( idx, 1 );
  11845. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  11846. this.faceVertexUvs[ j ].splice( idx, 1 );
  11847. }
  11848. }
  11849. // Use unique set of vertices
  11850. var diff = this.vertices.length - unique.length;
  11851. this.vertices = unique;
  11852. return diff;
  11853. },
  11854. sortFacesByMaterialIndex: function () {
  11855. var faces = this.faces;
  11856. var length = faces.length;
  11857. // tag faces
  11858. for ( var i = 0; i < length; i ++ ) {
  11859. faces[ i ]._id = i;
  11860. }
  11861. // sort faces
  11862. function materialIndexSort( a, b ) {
  11863. return a.materialIndex - b.materialIndex;
  11864. }
  11865. faces.sort( materialIndexSort );
  11866. // sort uvs
  11867. var uvs1 = this.faceVertexUvs[ 0 ];
  11868. var uvs2 = this.faceVertexUvs[ 1 ];
  11869. var newUvs1, newUvs2;
  11870. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  11871. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  11872. for ( var i = 0; i < length; i ++ ) {
  11873. var id = faces[ i ]._id;
  11874. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  11875. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  11876. }
  11877. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  11878. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  11879. },
  11880. toJSON: function () {
  11881. var data = {
  11882. metadata: {
  11883. version: 4.5,
  11884. type: 'Geometry',
  11885. generator: 'Geometry.toJSON'
  11886. }
  11887. };
  11888. // standard Geometry serialization
  11889. data.uuid = this.uuid;
  11890. data.type = this.type;
  11891. if ( this.name !== '' ) data.name = this.name;
  11892. if ( this.parameters !== undefined ) {
  11893. var parameters = this.parameters;
  11894. for ( var key in parameters ) {
  11895. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11896. }
  11897. return data;
  11898. }
  11899. var vertices = [];
  11900. for ( var i = 0; i < this.vertices.length; i ++ ) {
  11901. var vertex = this.vertices[ i ];
  11902. vertices.push( vertex.x, vertex.y, vertex.z );
  11903. }
  11904. var faces = [];
  11905. var normals = [];
  11906. var normalsHash = {};
  11907. var colors = [];
  11908. var colorsHash = {};
  11909. var uvs = [];
  11910. var uvsHash = {};
  11911. for ( var i = 0; i < this.faces.length; i ++ ) {
  11912. var face = this.faces[ i ];
  11913. var hasMaterial = true;
  11914. var hasFaceUv = false; // deprecated
  11915. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  11916. var hasFaceNormal = face.normal.length() > 0;
  11917. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  11918. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  11919. var hasFaceVertexColor = face.vertexColors.length > 0;
  11920. var faceType = 0;
  11921. faceType = setBit( faceType, 0, 0 ); // isQuad
  11922. faceType = setBit( faceType, 1, hasMaterial );
  11923. faceType = setBit( faceType, 2, hasFaceUv );
  11924. faceType = setBit( faceType, 3, hasFaceVertexUv );
  11925. faceType = setBit( faceType, 4, hasFaceNormal );
  11926. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  11927. faceType = setBit( faceType, 6, hasFaceColor );
  11928. faceType = setBit( faceType, 7, hasFaceVertexColor );
  11929. faces.push( faceType );
  11930. faces.push( face.a, face.b, face.c );
  11931. faces.push( face.materialIndex );
  11932. if ( hasFaceVertexUv ) {
  11933. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  11934. faces.push(
  11935. getUvIndex( faceVertexUvs[ 0 ] ),
  11936. getUvIndex( faceVertexUvs[ 1 ] ),
  11937. getUvIndex( faceVertexUvs[ 2 ] )
  11938. );
  11939. }
  11940. if ( hasFaceNormal ) {
  11941. faces.push( getNormalIndex( face.normal ) );
  11942. }
  11943. if ( hasFaceVertexNormal ) {
  11944. var vertexNormals = face.vertexNormals;
  11945. faces.push(
  11946. getNormalIndex( vertexNormals[ 0 ] ),
  11947. getNormalIndex( vertexNormals[ 1 ] ),
  11948. getNormalIndex( vertexNormals[ 2 ] )
  11949. );
  11950. }
  11951. if ( hasFaceColor ) {
  11952. faces.push( getColorIndex( face.color ) );
  11953. }
  11954. if ( hasFaceVertexColor ) {
  11955. var vertexColors = face.vertexColors;
  11956. faces.push(
  11957. getColorIndex( vertexColors[ 0 ] ),
  11958. getColorIndex( vertexColors[ 1 ] ),
  11959. getColorIndex( vertexColors[ 2 ] )
  11960. );
  11961. }
  11962. }
  11963. function setBit( value, position, enabled ) {
  11964. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  11965. }
  11966. function getNormalIndex( normal ) {
  11967. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  11968. if ( normalsHash[ hash ] !== undefined ) {
  11969. return normalsHash[ hash ];
  11970. }
  11971. normalsHash[ hash ] = normals.length / 3;
  11972. normals.push( normal.x, normal.y, normal.z );
  11973. return normalsHash[ hash ];
  11974. }
  11975. function getColorIndex( color ) {
  11976. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  11977. if ( colorsHash[ hash ] !== undefined ) {
  11978. return colorsHash[ hash ];
  11979. }
  11980. colorsHash[ hash ] = colors.length;
  11981. colors.push( color.getHex() );
  11982. return colorsHash[ hash ];
  11983. }
  11984. function getUvIndex( uv ) {
  11985. var hash = uv.x.toString() + uv.y.toString();
  11986. if ( uvsHash[ hash ] !== undefined ) {
  11987. return uvsHash[ hash ];
  11988. }
  11989. uvsHash[ hash ] = uvs.length / 2;
  11990. uvs.push( uv.x, uv.y );
  11991. return uvsHash[ hash ];
  11992. }
  11993. data.data = {};
  11994. data.data.vertices = vertices;
  11995. data.data.normals = normals;
  11996. if ( colors.length > 0 ) data.data.colors = colors;
  11997. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  11998. data.data.faces = faces;
  11999. return data;
  12000. },
  12001. clone: function () {
  12002. /*
  12003. // Handle primitives
  12004. var parameters = this.parameters;
  12005. if ( parameters !== undefined ) {
  12006. var values = [];
  12007. for ( var key in parameters ) {
  12008. values.push( parameters[ key ] );
  12009. }
  12010. var geometry = Object.create( this.constructor.prototype );
  12011. this.constructor.apply( geometry, values );
  12012. return geometry;
  12013. }
  12014. return new this.constructor().copy( this );
  12015. */
  12016. return new Geometry().copy( this );
  12017. },
  12018. copy: function ( source ) {
  12019. var i, il, j, jl, k, kl;
  12020. // reset
  12021. this.vertices = [];
  12022. this.colors = [];
  12023. this.faces = [];
  12024. this.faceVertexUvs = [[]];
  12025. this.morphTargets = [];
  12026. this.morphNormals = [];
  12027. this.skinWeights = [];
  12028. this.skinIndices = [];
  12029. this.lineDistances = [];
  12030. this.boundingBox = null;
  12031. this.boundingSphere = null;
  12032. // name
  12033. this.name = source.name;
  12034. // vertices
  12035. var vertices = source.vertices;
  12036. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  12037. this.vertices.push( vertices[ i ].clone() );
  12038. }
  12039. // colors
  12040. var colors = source.colors;
  12041. for ( i = 0, il = colors.length; i < il; i ++ ) {
  12042. this.colors.push( colors[ i ].clone() );
  12043. }
  12044. // faces
  12045. var faces = source.faces;
  12046. for ( i = 0, il = faces.length; i < il; i ++ ) {
  12047. this.faces.push( faces[ i ].clone() );
  12048. }
  12049. // face vertex uvs
  12050. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  12051. var faceVertexUvs = source.faceVertexUvs[ i ];
  12052. if ( this.faceVertexUvs[ i ] === undefined ) {
  12053. this.faceVertexUvs[ i ] = [];
  12054. }
  12055. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  12056. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  12057. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  12058. var uv = uvs[ k ];
  12059. uvsCopy.push( uv.clone() );
  12060. }
  12061. this.faceVertexUvs[ i ].push( uvsCopy );
  12062. }
  12063. }
  12064. // morph targets
  12065. var morphTargets = source.morphTargets;
  12066. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  12067. var morphTarget = {};
  12068. morphTarget.name = morphTargets[ i ].name;
  12069. // vertices
  12070. if ( morphTargets[ i ].vertices !== undefined ) {
  12071. morphTarget.vertices = [];
  12072. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  12073. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  12074. }
  12075. }
  12076. // normals
  12077. if ( morphTargets[ i ].normals !== undefined ) {
  12078. morphTarget.normals = [];
  12079. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  12080. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  12081. }
  12082. }
  12083. this.morphTargets.push( morphTarget );
  12084. }
  12085. // morph normals
  12086. var morphNormals = source.morphNormals;
  12087. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  12088. var morphNormal = {};
  12089. // vertex normals
  12090. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  12091. morphNormal.vertexNormals = [];
  12092. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  12093. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  12094. var destVertexNormal = {};
  12095. destVertexNormal.a = srcVertexNormal.a.clone();
  12096. destVertexNormal.b = srcVertexNormal.b.clone();
  12097. destVertexNormal.c = srcVertexNormal.c.clone();
  12098. morphNormal.vertexNormals.push( destVertexNormal );
  12099. }
  12100. }
  12101. // face normals
  12102. if ( morphNormals[ i ].faceNormals !== undefined ) {
  12103. morphNormal.faceNormals = [];
  12104. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  12105. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  12106. }
  12107. }
  12108. this.morphNormals.push( morphNormal );
  12109. }
  12110. // skin weights
  12111. var skinWeights = source.skinWeights;
  12112. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  12113. this.skinWeights.push( skinWeights[ i ].clone() );
  12114. }
  12115. // skin indices
  12116. var skinIndices = source.skinIndices;
  12117. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  12118. this.skinIndices.push( skinIndices[ i ].clone() );
  12119. }
  12120. // line distances
  12121. var lineDistances = source.lineDistances;
  12122. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  12123. this.lineDistances.push( lineDistances[ i ] );
  12124. }
  12125. // bounding box
  12126. var boundingBox = source.boundingBox;
  12127. if ( boundingBox !== null ) {
  12128. this.boundingBox = boundingBox.clone();
  12129. }
  12130. // bounding sphere
  12131. var boundingSphere = source.boundingSphere;
  12132. if ( boundingSphere !== null ) {
  12133. this.boundingSphere = boundingSphere.clone();
  12134. }
  12135. // update flags
  12136. this.elementsNeedUpdate = source.elementsNeedUpdate;
  12137. this.verticesNeedUpdate = source.verticesNeedUpdate;
  12138. this.uvsNeedUpdate = source.uvsNeedUpdate;
  12139. this.normalsNeedUpdate = source.normalsNeedUpdate;
  12140. this.colorsNeedUpdate = source.colorsNeedUpdate;
  12141. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  12142. this.groupsNeedUpdate = source.groupsNeedUpdate;
  12143. return this;
  12144. },
  12145. dispose: function () {
  12146. this.dispatchEvent( { type: 'dispose' } );
  12147. }
  12148. } );
  12149. /**
  12150. * @author mrdoob / http://mrdoob.com/
  12151. */
  12152. function BufferAttribute( array, itemSize, normalized ) {
  12153. if ( Array.isArray( array ) ) {
  12154. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12155. }
  12156. this.uuid = _Math.generateUUID();
  12157. this.name = '';
  12158. this.array = array;
  12159. this.itemSize = itemSize;
  12160. this.count = array !== undefined ? array.length / itemSize : 0;
  12161. this.normalized = normalized === true;
  12162. this.dynamic = false;
  12163. this.updateRange = { offset: 0, count: - 1 };
  12164. this.onUploadCallback = function () {};
  12165. this.version = 0;
  12166. }
  12167. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  12168. set: function ( value ) {
  12169. if ( value === true ) this.version ++;
  12170. }
  12171. } );
  12172. Object.assign( BufferAttribute.prototype, {
  12173. isBufferAttribute: true,
  12174. setArray: function ( array ) {
  12175. if ( Array.isArray( array ) ) {
  12176. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12177. }
  12178. this.count = array !== undefined ? array.length / this.itemSize : 0;
  12179. this.array = array;
  12180. },
  12181. setDynamic: function ( value ) {
  12182. this.dynamic = value;
  12183. return this;
  12184. },
  12185. copy: function ( source ) {
  12186. this.array = new source.array.constructor( source.array );
  12187. this.itemSize = source.itemSize;
  12188. this.count = source.count;
  12189. this.normalized = source.normalized;
  12190. this.dynamic = source.dynamic;
  12191. return this;
  12192. },
  12193. copyAt: function ( index1, attribute, index2 ) {
  12194. index1 *= this.itemSize;
  12195. index2 *= attribute.itemSize;
  12196. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  12197. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12198. }
  12199. return this;
  12200. },
  12201. copyArray: function ( array ) {
  12202. this.array.set( array );
  12203. return this;
  12204. },
  12205. copyColorsArray: function ( colors ) {
  12206. var array = this.array, offset = 0;
  12207. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  12208. var color = colors[ i ];
  12209. if ( color === undefined ) {
  12210. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  12211. color = new Color();
  12212. }
  12213. array[ offset ++ ] = color.r;
  12214. array[ offset ++ ] = color.g;
  12215. array[ offset ++ ] = color.b;
  12216. }
  12217. return this;
  12218. },
  12219. copyIndicesArray: function ( indices ) {
  12220. var array = this.array, offset = 0;
  12221. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  12222. var index = indices[ i ];
  12223. array[ offset ++ ] = index.a;
  12224. array[ offset ++ ] = index.b;
  12225. array[ offset ++ ] = index.c;
  12226. }
  12227. return this;
  12228. },
  12229. copyVector2sArray: function ( vectors ) {
  12230. var array = this.array, offset = 0;
  12231. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  12232. var vector = vectors[ i ];
  12233. if ( vector === undefined ) {
  12234. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  12235. vector = new Vector2();
  12236. }
  12237. array[ offset ++ ] = vector.x;
  12238. array[ offset ++ ] = vector.y;
  12239. }
  12240. return this;
  12241. },
  12242. copyVector3sArray: function ( vectors ) {
  12243. var array = this.array, offset = 0;
  12244. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  12245. var vector = vectors[ i ];
  12246. if ( vector === undefined ) {
  12247. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  12248. vector = new Vector3();
  12249. }
  12250. array[ offset ++ ] = vector.x;
  12251. array[ offset ++ ] = vector.y;
  12252. array[ offset ++ ] = vector.z;
  12253. }
  12254. return this;
  12255. },
  12256. copyVector4sArray: function ( vectors ) {
  12257. var array = this.array, offset = 0;
  12258. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  12259. var vector = vectors[ i ];
  12260. if ( vector === undefined ) {
  12261. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  12262. vector = new Vector4();
  12263. }
  12264. array[ offset ++ ] = vector.x;
  12265. array[ offset ++ ] = vector.y;
  12266. array[ offset ++ ] = vector.z;
  12267. array[ offset ++ ] = vector.w;
  12268. }
  12269. return this;
  12270. },
  12271. set: function ( value, offset ) {
  12272. if ( offset === undefined ) offset = 0;
  12273. this.array.set( value, offset );
  12274. return this;
  12275. },
  12276. getX: function ( index ) {
  12277. return this.array[ index * this.itemSize ];
  12278. },
  12279. setX: function ( index, x ) {
  12280. this.array[ index * this.itemSize ] = x;
  12281. return this;
  12282. },
  12283. getY: function ( index ) {
  12284. return this.array[ index * this.itemSize + 1 ];
  12285. },
  12286. setY: function ( index, y ) {
  12287. this.array[ index * this.itemSize + 1 ] = y;
  12288. return this;
  12289. },
  12290. getZ: function ( index ) {
  12291. return this.array[ index * this.itemSize + 2 ];
  12292. },
  12293. setZ: function ( index, z ) {
  12294. this.array[ index * this.itemSize + 2 ] = z;
  12295. return this;
  12296. },
  12297. getW: function ( index ) {
  12298. return this.array[ index * this.itemSize + 3 ];
  12299. },
  12300. setW: function ( index, w ) {
  12301. this.array[ index * this.itemSize + 3 ] = w;
  12302. return this;
  12303. },
  12304. setXY: function ( index, x, y ) {
  12305. index *= this.itemSize;
  12306. this.array[ index + 0 ] = x;
  12307. this.array[ index + 1 ] = y;
  12308. return this;
  12309. },
  12310. setXYZ: function ( index, x, y, z ) {
  12311. index *= this.itemSize;
  12312. this.array[ index + 0 ] = x;
  12313. this.array[ index + 1 ] = y;
  12314. this.array[ index + 2 ] = z;
  12315. return this;
  12316. },
  12317. setXYZW: function ( index, x, y, z, w ) {
  12318. index *= this.itemSize;
  12319. this.array[ index + 0 ] = x;
  12320. this.array[ index + 1 ] = y;
  12321. this.array[ index + 2 ] = z;
  12322. this.array[ index + 3 ] = w;
  12323. return this;
  12324. },
  12325. onUpload: function ( callback ) {
  12326. this.onUploadCallback = callback;
  12327. return this;
  12328. },
  12329. clone: function () {
  12330. return new this.constructor( this.array, this.itemSize ).copy( this );
  12331. }
  12332. } );
  12333. //
  12334. function Int8BufferAttribute( array, itemSize ) {
  12335. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  12336. }
  12337. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12338. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  12339. function Uint8BufferAttribute( array, itemSize ) {
  12340. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  12341. }
  12342. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12343. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  12344. function Uint8ClampedBufferAttribute( array, itemSize ) {
  12345. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  12346. }
  12347. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12348. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  12349. function Int16BufferAttribute( array, itemSize ) {
  12350. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  12351. }
  12352. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12353. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  12354. function Uint16BufferAttribute( array, itemSize ) {
  12355. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  12356. }
  12357. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12358. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  12359. function Int32BufferAttribute( array, itemSize ) {
  12360. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  12361. }
  12362. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12363. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  12364. function Uint32BufferAttribute( array, itemSize ) {
  12365. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  12366. }
  12367. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12368. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  12369. function Float32BufferAttribute( array, itemSize ) {
  12370. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  12371. }
  12372. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12373. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  12374. function Float64BufferAttribute( array, itemSize ) {
  12375. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  12376. }
  12377. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12378. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  12379. /**
  12380. * @author mrdoob / http://mrdoob.com/
  12381. */
  12382. function DirectGeometry() {
  12383. this.indices = [];
  12384. this.vertices = [];
  12385. this.normals = [];
  12386. this.colors = [];
  12387. this.uvs = [];
  12388. this.uvs2 = [];
  12389. this.groups = [];
  12390. this.morphTargets = {};
  12391. this.skinWeights = [];
  12392. this.skinIndices = [];
  12393. // this.lineDistances = [];
  12394. this.boundingBox = null;
  12395. this.boundingSphere = null;
  12396. // update flags
  12397. this.verticesNeedUpdate = false;
  12398. this.normalsNeedUpdate = false;
  12399. this.colorsNeedUpdate = false;
  12400. this.uvsNeedUpdate = false;
  12401. this.groupsNeedUpdate = false;
  12402. }
  12403. Object.assign( DirectGeometry.prototype, {
  12404. computeGroups: function ( geometry ) {
  12405. var group;
  12406. var groups = [];
  12407. var materialIndex = undefined;
  12408. var faces = geometry.faces;
  12409. for ( var i = 0; i < faces.length; i ++ ) {
  12410. var face = faces[ i ];
  12411. // materials
  12412. if ( face.materialIndex !== materialIndex ) {
  12413. materialIndex = face.materialIndex;
  12414. if ( group !== undefined ) {
  12415. group.count = ( i * 3 ) - group.start;
  12416. groups.push( group );
  12417. }
  12418. group = {
  12419. start: i * 3,
  12420. materialIndex: materialIndex
  12421. };
  12422. }
  12423. }
  12424. if ( group !== undefined ) {
  12425. group.count = ( i * 3 ) - group.start;
  12426. groups.push( group );
  12427. }
  12428. this.groups = groups;
  12429. },
  12430. fromGeometry: function ( geometry ) {
  12431. var faces = geometry.faces;
  12432. var vertices = geometry.vertices;
  12433. var faceVertexUvs = geometry.faceVertexUvs;
  12434. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  12435. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  12436. // morphs
  12437. var morphTargets = geometry.morphTargets;
  12438. var morphTargetsLength = morphTargets.length;
  12439. var morphTargetsPosition;
  12440. if ( morphTargetsLength > 0 ) {
  12441. morphTargetsPosition = [];
  12442. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  12443. morphTargetsPosition[ i ] = [];
  12444. }
  12445. this.morphTargets.position = morphTargetsPosition;
  12446. }
  12447. var morphNormals = geometry.morphNormals;
  12448. var morphNormalsLength = morphNormals.length;
  12449. var morphTargetsNormal;
  12450. if ( morphNormalsLength > 0 ) {
  12451. morphTargetsNormal = [];
  12452. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  12453. morphTargetsNormal[ i ] = [];
  12454. }
  12455. this.morphTargets.normal = morphTargetsNormal;
  12456. }
  12457. // skins
  12458. var skinIndices = geometry.skinIndices;
  12459. var skinWeights = geometry.skinWeights;
  12460. var hasSkinIndices = skinIndices.length === vertices.length;
  12461. var hasSkinWeights = skinWeights.length === vertices.length;
  12462. //
  12463. for ( var i = 0; i < faces.length; i ++ ) {
  12464. var face = faces[ i ];
  12465. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  12466. var vertexNormals = face.vertexNormals;
  12467. if ( vertexNormals.length === 3 ) {
  12468. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  12469. } else {
  12470. var normal = face.normal;
  12471. this.normals.push( normal, normal, normal );
  12472. }
  12473. var vertexColors = face.vertexColors;
  12474. if ( vertexColors.length === 3 ) {
  12475. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  12476. } else {
  12477. var color = face.color;
  12478. this.colors.push( color, color, color );
  12479. }
  12480. if ( hasFaceVertexUv === true ) {
  12481. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  12482. if ( vertexUvs !== undefined ) {
  12483. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  12484. } else {
  12485. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  12486. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  12487. }
  12488. }
  12489. if ( hasFaceVertexUv2 === true ) {
  12490. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  12491. if ( vertexUvs !== undefined ) {
  12492. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  12493. } else {
  12494. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  12495. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  12496. }
  12497. }
  12498. // morphs
  12499. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  12500. var morphTarget = morphTargets[ j ].vertices;
  12501. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  12502. }
  12503. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  12504. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  12505. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  12506. }
  12507. // skins
  12508. if ( hasSkinIndices ) {
  12509. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  12510. }
  12511. if ( hasSkinWeights ) {
  12512. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  12513. }
  12514. }
  12515. this.computeGroups( geometry );
  12516. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12517. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12518. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12519. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12520. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12521. return this;
  12522. }
  12523. } );
  12524. /**
  12525. * @author mrdoob / http://mrdoob.com/
  12526. */
  12527. function arrayMax( array ) {
  12528. if ( array.length === 0 ) return - Infinity;
  12529. var max = array[ 0 ];
  12530. for ( var i = 1, l = array.length; i < l; ++ i ) {
  12531. if ( array[ i ] > max ) max = array[ i ];
  12532. }
  12533. return max;
  12534. }
  12535. /**
  12536. * @author alteredq / http://alteredqualia.com/
  12537. * @author mrdoob / http://mrdoob.com/
  12538. */
  12539. function BufferGeometry() {
  12540. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  12541. this.uuid = _Math.generateUUID();
  12542. this.name = '';
  12543. this.type = 'BufferGeometry';
  12544. this.index = null;
  12545. this.attributes = {};
  12546. this.morphAttributes = {};
  12547. this.groups = [];
  12548. this.boundingBox = null;
  12549. this.boundingSphere = null;
  12550. this.drawRange = { start: 0, count: Infinity };
  12551. }
  12552. BufferGeometry.MaxIndex = 65535;
  12553. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  12554. isBufferGeometry: true,
  12555. getIndex: function () {
  12556. return this.index;
  12557. },
  12558. setIndex: function ( index ) {
  12559. if ( Array.isArray( index ) ) {
  12560. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  12561. } else {
  12562. this.index = index;
  12563. }
  12564. },
  12565. addAttribute: function ( name, attribute ) {
  12566. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  12567. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  12568. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  12569. return;
  12570. }
  12571. if ( name === 'index' ) {
  12572. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  12573. this.setIndex( attribute );
  12574. return;
  12575. }
  12576. this.attributes[ name ] = attribute;
  12577. return this;
  12578. },
  12579. getAttribute: function ( name ) {
  12580. return this.attributes[ name ];
  12581. },
  12582. removeAttribute: function ( name ) {
  12583. delete this.attributes[ name ];
  12584. return this;
  12585. },
  12586. addGroup: function ( start, count, materialIndex ) {
  12587. this.groups.push( {
  12588. start: start,
  12589. count: count,
  12590. materialIndex: materialIndex !== undefined ? materialIndex : 0
  12591. } );
  12592. },
  12593. clearGroups: function () {
  12594. this.groups = [];
  12595. },
  12596. setDrawRange: function ( start, count ) {
  12597. this.drawRange.start = start;
  12598. this.drawRange.count = count;
  12599. },
  12600. applyMatrix: function ( matrix ) {
  12601. var position = this.attributes.position;
  12602. if ( position !== undefined ) {
  12603. matrix.applyToBufferAttribute( position );
  12604. position.needsUpdate = true;
  12605. }
  12606. var normal = this.attributes.normal;
  12607. if ( normal !== undefined ) {
  12608. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12609. normalMatrix.applyToBufferAttribute( normal );
  12610. normal.needsUpdate = true;
  12611. }
  12612. if ( this.boundingBox !== null ) {
  12613. this.computeBoundingBox();
  12614. }
  12615. if ( this.boundingSphere !== null ) {
  12616. this.computeBoundingSphere();
  12617. }
  12618. return this;
  12619. },
  12620. rotateX: function () {
  12621. // rotate geometry around world x-axis
  12622. var m1 = new Matrix4();
  12623. return function rotateX( angle ) {
  12624. m1.makeRotationX( angle );
  12625. this.applyMatrix( m1 );
  12626. return this;
  12627. };
  12628. }(),
  12629. rotateY: function () {
  12630. // rotate geometry around world y-axis
  12631. var m1 = new Matrix4();
  12632. return function rotateY( angle ) {
  12633. m1.makeRotationY( angle );
  12634. this.applyMatrix( m1 );
  12635. return this;
  12636. };
  12637. }(),
  12638. rotateZ: function () {
  12639. // rotate geometry around world z-axis
  12640. var m1 = new Matrix4();
  12641. return function rotateZ( angle ) {
  12642. m1.makeRotationZ( angle );
  12643. this.applyMatrix( m1 );
  12644. return this;
  12645. };
  12646. }(),
  12647. translate: function () {
  12648. // translate geometry
  12649. var m1 = new Matrix4();
  12650. return function translate( x, y, z ) {
  12651. m1.makeTranslation( x, y, z );
  12652. this.applyMatrix( m1 );
  12653. return this;
  12654. };
  12655. }(),
  12656. scale: function () {
  12657. // scale geometry
  12658. var m1 = new Matrix4();
  12659. return function scale( x, y, z ) {
  12660. m1.makeScale( x, y, z );
  12661. this.applyMatrix( m1 );
  12662. return this;
  12663. };
  12664. }(),
  12665. lookAt: function () {
  12666. var obj = new Object3D();
  12667. return function lookAt( vector ) {
  12668. obj.lookAt( vector );
  12669. obj.updateMatrix();
  12670. this.applyMatrix( obj.matrix );
  12671. };
  12672. }(),
  12673. center: function () {
  12674. this.computeBoundingBox();
  12675. var offset = this.boundingBox.getCenter().negate();
  12676. this.translate( offset.x, offset.y, offset.z );
  12677. return offset;
  12678. },
  12679. setFromObject: function ( object ) {
  12680. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  12681. var geometry = object.geometry;
  12682. if ( object.isPoints || object.isLine ) {
  12683. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  12684. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  12685. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  12686. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  12687. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  12688. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  12689. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  12690. }
  12691. if ( geometry.boundingSphere !== null ) {
  12692. this.boundingSphere = geometry.boundingSphere.clone();
  12693. }
  12694. if ( geometry.boundingBox !== null ) {
  12695. this.boundingBox = geometry.boundingBox.clone();
  12696. }
  12697. } else if ( object.isMesh ) {
  12698. if ( geometry && geometry.isGeometry ) {
  12699. this.fromGeometry( geometry );
  12700. }
  12701. }
  12702. return this;
  12703. },
  12704. updateFromObject: function ( object ) {
  12705. var geometry = object.geometry;
  12706. if ( object.isMesh ) {
  12707. var direct = geometry.__directGeometry;
  12708. if ( geometry.elementsNeedUpdate === true ) {
  12709. direct = undefined;
  12710. geometry.elementsNeedUpdate = false;
  12711. }
  12712. if ( direct === undefined ) {
  12713. return this.fromGeometry( geometry );
  12714. }
  12715. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12716. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12717. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12718. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12719. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12720. geometry.verticesNeedUpdate = false;
  12721. geometry.normalsNeedUpdate = false;
  12722. geometry.colorsNeedUpdate = false;
  12723. geometry.uvsNeedUpdate = false;
  12724. geometry.groupsNeedUpdate = false;
  12725. geometry = direct;
  12726. }
  12727. var attribute;
  12728. if ( geometry.verticesNeedUpdate === true ) {
  12729. attribute = this.attributes.position;
  12730. if ( attribute !== undefined ) {
  12731. attribute.copyVector3sArray( geometry.vertices );
  12732. attribute.needsUpdate = true;
  12733. }
  12734. geometry.verticesNeedUpdate = false;
  12735. }
  12736. if ( geometry.normalsNeedUpdate === true ) {
  12737. attribute = this.attributes.normal;
  12738. if ( attribute !== undefined ) {
  12739. attribute.copyVector3sArray( geometry.normals );
  12740. attribute.needsUpdate = true;
  12741. }
  12742. geometry.normalsNeedUpdate = false;
  12743. }
  12744. if ( geometry.colorsNeedUpdate === true ) {
  12745. attribute = this.attributes.color;
  12746. if ( attribute !== undefined ) {
  12747. attribute.copyColorsArray( geometry.colors );
  12748. attribute.needsUpdate = true;
  12749. }
  12750. geometry.colorsNeedUpdate = false;
  12751. }
  12752. if ( geometry.uvsNeedUpdate ) {
  12753. attribute = this.attributes.uv;
  12754. if ( attribute !== undefined ) {
  12755. attribute.copyVector2sArray( geometry.uvs );
  12756. attribute.needsUpdate = true;
  12757. }
  12758. geometry.uvsNeedUpdate = false;
  12759. }
  12760. if ( geometry.lineDistancesNeedUpdate ) {
  12761. attribute = this.attributes.lineDistance;
  12762. if ( attribute !== undefined ) {
  12763. attribute.copyArray( geometry.lineDistances );
  12764. attribute.needsUpdate = true;
  12765. }
  12766. geometry.lineDistancesNeedUpdate = false;
  12767. }
  12768. if ( geometry.groupsNeedUpdate ) {
  12769. geometry.computeGroups( object.geometry );
  12770. this.groups = geometry.groups;
  12771. geometry.groupsNeedUpdate = false;
  12772. }
  12773. return this;
  12774. },
  12775. fromGeometry: function ( geometry ) {
  12776. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  12777. return this.fromDirectGeometry( geometry.__directGeometry );
  12778. },
  12779. fromDirectGeometry: function ( geometry ) {
  12780. var positions = new Float32Array( geometry.vertices.length * 3 );
  12781. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  12782. if ( geometry.normals.length > 0 ) {
  12783. var normals = new Float32Array( geometry.normals.length * 3 );
  12784. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  12785. }
  12786. if ( geometry.colors.length > 0 ) {
  12787. var colors = new Float32Array( geometry.colors.length * 3 );
  12788. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  12789. }
  12790. if ( geometry.uvs.length > 0 ) {
  12791. var uvs = new Float32Array( geometry.uvs.length * 2 );
  12792. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  12793. }
  12794. if ( geometry.uvs2.length > 0 ) {
  12795. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  12796. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  12797. }
  12798. if ( geometry.indices.length > 0 ) {
  12799. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  12800. var indices = new TypeArray( geometry.indices.length * 3 );
  12801. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  12802. }
  12803. // groups
  12804. this.groups = geometry.groups;
  12805. // morphs
  12806. for ( var name in geometry.morphTargets ) {
  12807. var array = [];
  12808. var morphTargets = geometry.morphTargets[ name ];
  12809. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  12810. var morphTarget = morphTargets[ i ];
  12811. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  12812. array.push( attribute.copyVector3sArray( morphTarget ) );
  12813. }
  12814. this.morphAttributes[ name ] = array;
  12815. }
  12816. // skinning
  12817. if ( geometry.skinIndices.length > 0 ) {
  12818. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  12819. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  12820. }
  12821. if ( geometry.skinWeights.length > 0 ) {
  12822. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  12823. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  12824. }
  12825. //
  12826. if ( geometry.boundingSphere !== null ) {
  12827. this.boundingSphere = geometry.boundingSphere.clone();
  12828. }
  12829. if ( geometry.boundingBox !== null ) {
  12830. this.boundingBox = geometry.boundingBox.clone();
  12831. }
  12832. return this;
  12833. },
  12834. computeBoundingBox: function () {
  12835. if ( this.boundingBox === null ) {
  12836. this.boundingBox = new Box3();
  12837. }
  12838. var position = this.attributes.position;
  12839. if ( position !== undefined ) {
  12840. this.boundingBox.setFromBufferAttribute( position );
  12841. } else {
  12842. this.boundingBox.makeEmpty();
  12843. }
  12844. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  12845. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  12846. }
  12847. },
  12848. computeBoundingSphere: function () {
  12849. var box = new Box3();
  12850. var vector = new Vector3();
  12851. return function computeBoundingSphere() {
  12852. if ( this.boundingSphere === null ) {
  12853. this.boundingSphere = new Sphere();
  12854. }
  12855. var position = this.attributes.position;
  12856. if ( position ) {
  12857. var center = this.boundingSphere.center;
  12858. box.setFromBufferAttribute( position );
  12859. box.getCenter( center );
  12860. // hoping to find a boundingSphere with a radius smaller than the
  12861. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12862. var maxRadiusSq = 0;
  12863. for ( var i = 0, il = position.count; i < il; i ++ ) {
  12864. vector.x = position.getX( i );
  12865. vector.y = position.getY( i );
  12866. vector.z = position.getZ( i );
  12867. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  12868. }
  12869. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  12870. if ( isNaN( this.boundingSphere.radius ) ) {
  12871. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  12872. }
  12873. }
  12874. };
  12875. }(),
  12876. computeFaceNormals: function () {
  12877. // backwards compatibility
  12878. },
  12879. computeVertexNormals: function () {
  12880. var index = this.index;
  12881. var attributes = this.attributes;
  12882. var groups = this.groups;
  12883. if ( attributes.position ) {
  12884. var positions = attributes.position.array;
  12885. if ( attributes.normal === undefined ) {
  12886. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  12887. } else {
  12888. // reset existing normals to zero
  12889. var array = attributes.normal.array;
  12890. for ( var i = 0, il = array.length; i < il; i ++ ) {
  12891. array[ i ] = 0;
  12892. }
  12893. }
  12894. var normals = attributes.normal.array;
  12895. var vA, vB, vC;
  12896. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  12897. var cb = new Vector3(), ab = new Vector3();
  12898. // indexed elements
  12899. if ( index ) {
  12900. var indices = index.array;
  12901. if ( groups.length === 0 ) {
  12902. this.addGroup( 0, indices.length );
  12903. }
  12904. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  12905. var group = groups[ j ];
  12906. var start = group.start;
  12907. var count = group.count;
  12908. for ( var i = start, il = start + count; i < il; i += 3 ) {
  12909. vA = indices[ i + 0 ] * 3;
  12910. vB = indices[ i + 1 ] * 3;
  12911. vC = indices[ i + 2 ] * 3;
  12912. pA.fromArray( positions, vA );
  12913. pB.fromArray( positions, vB );
  12914. pC.fromArray( positions, vC );
  12915. cb.subVectors( pC, pB );
  12916. ab.subVectors( pA, pB );
  12917. cb.cross( ab );
  12918. normals[ vA ] += cb.x;
  12919. normals[ vA + 1 ] += cb.y;
  12920. normals[ vA + 2 ] += cb.z;
  12921. normals[ vB ] += cb.x;
  12922. normals[ vB + 1 ] += cb.y;
  12923. normals[ vB + 2 ] += cb.z;
  12924. normals[ vC ] += cb.x;
  12925. normals[ vC + 1 ] += cb.y;
  12926. normals[ vC + 2 ] += cb.z;
  12927. }
  12928. }
  12929. } else {
  12930. // non-indexed elements (unconnected triangle soup)
  12931. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  12932. pA.fromArray( positions, i );
  12933. pB.fromArray( positions, i + 3 );
  12934. pC.fromArray( positions, i + 6 );
  12935. cb.subVectors( pC, pB );
  12936. ab.subVectors( pA, pB );
  12937. cb.cross( ab );
  12938. normals[ i ] = cb.x;
  12939. normals[ i + 1 ] = cb.y;
  12940. normals[ i + 2 ] = cb.z;
  12941. normals[ i + 3 ] = cb.x;
  12942. normals[ i + 4 ] = cb.y;
  12943. normals[ i + 5 ] = cb.z;
  12944. normals[ i + 6 ] = cb.x;
  12945. normals[ i + 7 ] = cb.y;
  12946. normals[ i + 8 ] = cb.z;
  12947. }
  12948. }
  12949. this.normalizeNormals();
  12950. attributes.normal.needsUpdate = true;
  12951. }
  12952. },
  12953. merge: function ( geometry, offset ) {
  12954. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  12955. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  12956. return;
  12957. }
  12958. if ( offset === undefined ) offset = 0;
  12959. var attributes = this.attributes;
  12960. for ( var key in attributes ) {
  12961. if ( geometry.attributes[ key ] === undefined ) continue;
  12962. var attribute1 = attributes[ key ];
  12963. var attributeArray1 = attribute1.array;
  12964. var attribute2 = geometry.attributes[ key ];
  12965. var attributeArray2 = attribute2.array;
  12966. var attributeSize = attribute2.itemSize;
  12967. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  12968. attributeArray1[ j ] = attributeArray2[ i ];
  12969. }
  12970. }
  12971. return this;
  12972. },
  12973. normalizeNormals: function () {
  12974. var vector = new Vector3();
  12975. return function normalizeNormals() {
  12976. var normals = this.attributes.normal;
  12977. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  12978. vector.x = normals.getX( i );
  12979. vector.y = normals.getY( i );
  12980. vector.z = normals.getZ( i );
  12981. vector.normalize();
  12982. normals.setXYZ( i, vector.x, vector.y, vector.z );
  12983. }
  12984. };
  12985. }(),
  12986. toNonIndexed: function () {
  12987. if ( this.index === null ) {
  12988. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  12989. return this;
  12990. }
  12991. var geometry2 = new BufferGeometry();
  12992. var indices = this.index.array;
  12993. var attributes = this.attributes;
  12994. for ( var name in attributes ) {
  12995. var attribute = attributes[ name ];
  12996. var array = attribute.array;
  12997. var itemSize = attribute.itemSize;
  12998. var array2 = new array.constructor( indices.length * itemSize );
  12999. var index = 0, index2 = 0;
  13000. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  13001. index = indices[ i ] * itemSize;
  13002. for ( var j = 0; j < itemSize; j ++ ) {
  13003. array2[ index2 ++ ] = array[ index ++ ];
  13004. }
  13005. }
  13006. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  13007. }
  13008. return geometry2;
  13009. },
  13010. toJSON: function () {
  13011. var data = {
  13012. metadata: {
  13013. version: 4.5,
  13014. type: 'BufferGeometry',
  13015. generator: 'BufferGeometry.toJSON'
  13016. }
  13017. };
  13018. // standard BufferGeometry serialization
  13019. data.uuid = this.uuid;
  13020. data.type = this.type;
  13021. if ( this.name !== '' ) data.name = this.name;
  13022. if ( this.parameters !== undefined ) {
  13023. var parameters = this.parameters;
  13024. for ( var key in parameters ) {
  13025. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  13026. }
  13027. return data;
  13028. }
  13029. data.data = { attributes: {} };
  13030. var index = this.index;
  13031. if ( index !== null ) {
  13032. var array = Array.prototype.slice.call( index.array );
  13033. data.data.index = {
  13034. type: index.array.constructor.name,
  13035. array: array
  13036. };
  13037. }
  13038. var attributes = this.attributes;
  13039. for ( var key in attributes ) {
  13040. var attribute = attributes[ key ];
  13041. var array = Array.prototype.slice.call( attribute.array );
  13042. data.data.attributes[ key ] = {
  13043. itemSize: attribute.itemSize,
  13044. type: attribute.array.constructor.name,
  13045. array: array,
  13046. normalized: attribute.normalized
  13047. };
  13048. }
  13049. var groups = this.groups;
  13050. if ( groups.length > 0 ) {
  13051. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  13052. }
  13053. var boundingSphere = this.boundingSphere;
  13054. if ( boundingSphere !== null ) {
  13055. data.data.boundingSphere = {
  13056. center: boundingSphere.center.toArray(),
  13057. radius: boundingSphere.radius
  13058. };
  13059. }
  13060. return data;
  13061. },
  13062. clone: function () {
  13063. /*
  13064. // Handle primitives
  13065. var parameters = this.parameters;
  13066. if ( parameters !== undefined ) {
  13067. var values = [];
  13068. for ( var key in parameters ) {
  13069. values.push( parameters[ key ] );
  13070. }
  13071. var geometry = Object.create( this.constructor.prototype );
  13072. this.constructor.apply( geometry, values );
  13073. return geometry;
  13074. }
  13075. return new this.constructor().copy( this );
  13076. */
  13077. return new BufferGeometry().copy( this );
  13078. },
  13079. copy: function ( source ) {
  13080. var name, i, l;
  13081. // reset
  13082. this.index = null;
  13083. this.attributes = {};
  13084. this.morphAttributes = {};
  13085. this.groups = [];
  13086. this.boundingBox = null;
  13087. this.boundingSphere = null;
  13088. // name
  13089. this.name = source.name;
  13090. // index
  13091. var index = source.index;
  13092. if ( index !== null ) {
  13093. this.setIndex( index.clone() );
  13094. }
  13095. // attributes
  13096. var attributes = source.attributes;
  13097. for ( name in attributes ) {
  13098. var attribute = attributes[ name ];
  13099. this.addAttribute( name, attribute.clone() );
  13100. }
  13101. // morph attributes
  13102. var morphAttributes = source.morphAttributes;
  13103. for ( name in morphAttributes ) {
  13104. var array = [];
  13105. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  13106. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  13107. array.push( morphAttribute[ i ].clone() );
  13108. }
  13109. this.morphAttributes[ name ] = array;
  13110. }
  13111. // groups
  13112. var groups = source.groups;
  13113. for ( i = 0, l = groups.length; i < l; i ++ ) {
  13114. var group = groups[ i ];
  13115. this.addGroup( group.start, group.count, group.materialIndex );
  13116. }
  13117. // bounding box
  13118. var boundingBox = source.boundingBox;
  13119. if ( boundingBox !== null ) {
  13120. this.boundingBox = boundingBox.clone();
  13121. }
  13122. // bounding sphere
  13123. var boundingSphere = source.boundingSphere;
  13124. if ( boundingSphere !== null ) {
  13125. this.boundingSphere = boundingSphere.clone();
  13126. }
  13127. // draw range
  13128. this.drawRange.start = source.drawRange.start;
  13129. this.drawRange.count = source.drawRange.count;
  13130. return this;
  13131. },
  13132. dispose: function () {
  13133. this.dispatchEvent( { type: 'dispose' } );
  13134. }
  13135. } );
  13136. /**
  13137. * @author mrdoob / http://mrdoob.com/
  13138. * @author Mugen87 / https://github.com/Mugen87
  13139. */
  13140. // BoxGeometry
  13141. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13142. Geometry.call( this );
  13143. this.type = 'BoxGeometry';
  13144. this.parameters = {
  13145. width: width,
  13146. height: height,
  13147. depth: depth,
  13148. widthSegments: widthSegments,
  13149. heightSegments: heightSegments,
  13150. depthSegments: depthSegments
  13151. };
  13152. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13153. this.mergeVertices();
  13154. }
  13155. BoxGeometry.prototype = Object.create( Geometry.prototype );
  13156. BoxGeometry.prototype.constructor = BoxGeometry;
  13157. // BoxBufferGeometry
  13158. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13159. BufferGeometry.call( this );
  13160. this.type = 'BoxBufferGeometry';
  13161. this.parameters = {
  13162. width: width,
  13163. height: height,
  13164. depth: depth,
  13165. widthSegments: widthSegments,
  13166. heightSegments: heightSegments,
  13167. depthSegments: depthSegments
  13168. };
  13169. var scope = this;
  13170. // segments
  13171. widthSegments = Math.floor( widthSegments ) || 1;
  13172. heightSegments = Math.floor( heightSegments ) || 1;
  13173. depthSegments = Math.floor( depthSegments ) || 1;
  13174. // buffers
  13175. var indices = [];
  13176. var vertices = [];
  13177. var normals = [];
  13178. var uvs = [];
  13179. // helper variables
  13180. var numberOfVertices = 0;
  13181. var groupStart = 0;
  13182. // build each side of the box geometry
  13183. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13184. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13185. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13186. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13187. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13188. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13189. // build geometry
  13190. this.setIndex( indices );
  13191. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13192. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13193. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13194. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13195. var segmentWidth = width / gridX;
  13196. var segmentHeight = height / gridY;
  13197. var widthHalf = width / 2;
  13198. var heightHalf = height / 2;
  13199. var depthHalf = depth / 2;
  13200. var gridX1 = gridX + 1;
  13201. var gridY1 = gridY + 1;
  13202. var vertexCounter = 0;
  13203. var groupCount = 0;
  13204. var ix, iy;
  13205. var vector = new Vector3();
  13206. // generate vertices, normals and uvs
  13207. for ( iy = 0; iy < gridY1; iy ++ ) {
  13208. var y = iy * segmentHeight - heightHalf;
  13209. for ( ix = 0; ix < gridX1; ix ++ ) {
  13210. var x = ix * segmentWidth - widthHalf;
  13211. // set values to correct vector component
  13212. vector[ u ] = x * udir;
  13213. vector[ v ] = y * vdir;
  13214. vector[ w ] = depthHalf;
  13215. // now apply vector to vertex buffer
  13216. vertices.push( vector.x, vector.y, vector.z );
  13217. // set values to correct vector component
  13218. vector[ u ] = 0;
  13219. vector[ v ] = 0;
  13220. vector[ w ] = depth > 0 ? 1 : - 1;
  13221. // now apply vector to normal buffer
  13222. normals.push( vector.x, vector.y, vector.z );
  13223. // uvs
  13224. uvs.push( ix / gridX );
  13225. uvs.push( 1 - ( iy / gridY ) );
  13226. // counters
  13227. vertexCounter += 1;
  13228. }
  13229. }
  13230. // indices
  13231. // 1. you need three indices to draw a single face
  13232. // 2. a single segment consists of two faces
  13233. // 3. so we need to generate six (2*3) indices per segment
  13234. for ( iy = 0; iy < gridY; iy ++ ) {
  13235. for ( ix = 0; ix < gridX; ix ++ ) {
  13236. var a = numberOfVertices + ix + gridX1 * iy;
  13237. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13238. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13239. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13240. // faces
  13241. indices.push( a, b, d );
  13242. indices.push( b, c, d );
  13243. // increase counter
  13244. groupCount += 6;
  13245. }
  13246. }
  13247. // add a group to the geometry. this will ensure multi material support
  13248. scope.addGroup( groupStart, groupCount, materialIndex );
  13249. // calculate new start value for groups
  13250. groupStart += groupCount;
  13251. // update total number of vertices
  13252. numberOfVertices += vertexCounter;
  13253. }
  13254. }
  13255. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13256. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13257. /**
  13258. * @author mrdoob / http://mrdoob.com/
  13259. * @author Mugen87 / https://github.com/Mugen87
  13260. */
  13261. // PlaneGeometry
  13262. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  13263. Geometry.call( this );
  13264. this.type = 'PlaneGeometry';
  13265. this.parameters = {
  13266. width: width,
  13267. height: height,
  13268. widthSegments: widthSegments,
  13269. heightSegments: heightSegments
  13270. };
  13271. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  13272. this.mergeVertices();
  13273. }
  13274. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  13275. PlaneGeometry.prototype.constructor = PlaneGeometry;
  13276. // PlaneBufferGeometry
  13277. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  13278. BufferGeometry.call( this );
  13279. this.type = 'PlaneBufferGeometry';
  13280. this.parameters = {
  13281. width: width,
  13282. height: height,
  13283. widthSegments: widthSegments,
  13284. heightSegments: heightSegments
  13285. };
  13286. var width_half = width / 2;
  13287. var height_half = height / 2;
  13288. var gridX = Math.floor( widthSegments ) || 1;
  13289. var gridY = Math.floor( heightSegments ) || 1;
  13290. var gridX1 = gridX + 1;
  13291. var gridY1 = gridY + 1;
  13292. var segment_width = width / gridX;
  13293. var segment_height = height / gridY;
  13294. var ix, iy;
  13295. // buffers
  13296. var indices = [];
  13297. var vertices = [];
  13298. var normals = [];
  13299. var uvs = [];
  13300. // generate vertices, normals and uvs
  13301. for ( iy = 0; iy < gridY1; iy ++ ) {
  13302. var y = iy * segment_height - height_half;
  13303. for ( ix = 0; ix < gridX1; ix ++ ) {
  13304. var x = ix * segment_width - width_half;
  13305. vertices.push( x, - y, 0 );
  13306. normals.push( 0, 0, 1 );
  13307. uvs.push( ix / gridX );
  13308. uvs.push( 1 - ( iy / gridY ) );
  13309. }
  13310. }
  13311. // indices
  13312. for ( iy = 0; iy < gridY; iy ++ ) {
  13313. for ( ix = 0; ix < gridX; ix ++ ) {
  13314. var a = ix + gridX1 * iy;
  13315. var b = ix + gridX1 * ( iy + 1 );
  13316. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13317. var d = ( ix + 1 ) + gridX1 * iy;
  13318. // faces
  13319. indices.push( a, b, d );
  13320. indices.push( b, c, d );
  13321. }
  13322. }
  13323. // build geometry
  13324. this.setIndex( indices );
  13325. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13326. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13327. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13328. }
  13329. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13330. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  13331. /**
  13332. * @author mrdoob / http://mrdoob.com/
  13333. * @author alteredq / http://alteredqualia.com/
  13334. *
  13335. * parameters = {
  13336. * color: <hex>,
  13337. * opacity: <float>,
  13338. * map: new THREE.Texture( <Image> ),
  13339. *
  13340. * lightMap: new THREE.Texture( <Image> ),
  13341. * lightMapIntensity: <float>
  13342. *
  13343. * aoMap: new THREE.Texture( <Image> ),
  13344. * aoMapIntensity: <float>
  13345. *
  13346. * specularMap: new THREE.Texture( <Image> ),
  13347. *
  13348. * alphaMap: new THREE.Texture( <Image> ),
  13349. *
  13350. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  13351. * combine: THREE.Multiply,
  13352. * reflectivity: <float>,
  13353. * refractionRatio: <float>,
  13354. *
  13355. * depthTest: <bool>,
  13356. * depthWrite: <bool>,
  13357. *
  13358. * wireframe: <boolean>,
  13359. * wireframeLinewidth: <float>,
  13360. *
  13361. * skinning: <bool>,
  13362. * morphTargets: <bool>
  13363. * }
  13364. */
  13365. function MeshBasicMaterial( parameters ) {
  13366. Material.call( this );
  13367. this.type = 'MeshBasicMaterial';
  13368. this.color = new Color( 0xffffff ); // emissive
  13369. this.map = null;
  13370. this.lightMap = null;
  13371. this.lightMapIntensity = 1.0;
  13372. this.aoMap = null;
  13373. this.aoMapIntensity = 1.0;
  13374. this.specularMap = null;
  13375. this.alphaMap = null;
  13376. this.envMap = null;
  13377. this.combine = MultiplyOperation;
  13378. this.reflectivity = 1;
  13379. this.refractionRatio = 0.98;
  13380. this.wireframe = false;
  13381. this.wireframeLinewidth = 1;
  13382. this.wireframeLinecap = 'round';
  13383. this.wireframeLinejoin = 'round';
  13384. this.skinning = false;
  13385. this.morphTargets = false;
  13386. this.lights = false;
  13387. this.setValues( parameters );
  13388. }
  13389. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  13390. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  13391. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  13392. MeshBasicMaterial.prototype.copy = function ( source ) {
  13393. Material.prototype.copy.call( this, source );
  13394. this.color.copy( source.color );
  13395. this.map = source.map;
  13396. this.lightMap = source.lightMap;
  13397. this.lightMapIntensity = source.lightMapIntensity;
  13398. this.aoMap = source.aoMap;
  13399. this.aoMapIntensity = source.aoMapIntensity;
  13400. this.specularMap = source.specularMap;
  13401. this.alphaMap = source.alphaMap;
  13402. this.envMap = source.envMap;
  13403. this.combine = source.combine;
  13404. this.reflectivity = source.reflectivity;
  13405. this.refractionRatio = source.refractionRatio;
  13406. this.wireframe = source.wireframe;
  13407. this.wireframeLinewidth = source.wireframeLinewidth;
  13408. this.wireframeLinecap = source.wireframeLinecap;
  13409. this.wireframeLinejoin = source.wireframeLinejoin;
  13410. this.skinning = source.skinning;
  13411. this.morphTargets = source.morphTargets;
  13412. return this;
  13413. };
  13414. /**
  13415. * @author bhouston / http://clara.io
  13416. */
  13417. function Ray( origin, direction ) {
  13418. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  13419. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  13420. }
  13421. Object.assign( Ray.prototype, {
  13422. set: function ( origin, direction ) {
  13423. this.origin.copy( origin );
  13424. this.direction.copy( direction );
  13425. return this;
  13426. },
  13427. clone: function () {
  13428. return new this.constructor().copy( this );
  13429. },
  13430. copy: function ( ray ) {
  13431. this.origin.copy( ray.origin );
  13432. this.direction.copy( ray.direction );
  13433. return this;
  13434. },
  13435. at: function ( t, optionalTarget ) {
  13436. var result = optionalTarget || new Vector3();
  13437. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  13438. },
  13439. lookAt: function ( v ) {
  13440. this.direction.copy( v ).sub( this.origin ).normalize();
  13441. return this;
  13442. },
  13443. recast: function () {
  13444. var v1 = new Vector3();
  13445. return function recast( t ) {
  13446. this.origin.copy( this.at( t, v1 ) );
  13447. return this;
  13448. };
  13449. }(),
  13450. closestPointToPoint: function ( point, optionalTarget ) {
  13451. var result = optionalTarget || new Vector3();
  13452. result.subVectors( point, this.origin );
  13453. var directionDistance = result.dot( this.direction );
  13454. if ( directionDistance < 0 ) {
  13455. return result.copy( this.origin );
  13456. }
  13457. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  13458. },
  13459. distanceToPoint: function ( point ) {
  13460. return Math.sqrt( this.distanceSqToPoint( point ) );
  13461. },
  13462. distanceSqToPoint: function () {
  13463. var v1 = new Vector3();
  13464. return function distanceSqToPoint( point ) {
  13465. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  13466. // point behind the ray
  13467. if ( directionDistance < 0 ) {
  13468. return this.origin.distanceToSquared( point );
  13469. }
  13470. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  13471. return v1.distanceToSquared( point );
  13472. };
  13473. }(),
  13474. distanceSqToSegment: function () {
  13475. var segCenter = new Vector3();
  13476. var segDir = new Vector3();
  13477. var diff = new Vector3();
  13478. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  13479. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  13480. // It returns the min distance between the ray and the segment
  13481. // defined by v0 and v1
  13482. // It can also set two optional targets :
  13483. // - The closest point on the ray
  13484. // - The closest point on the segment
  13485. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  13486. segDir.copy( v1 ).sub( v0 ).normalize();
  13487. diff.copy( this.origin ).sub( segCenter );
  13488. var segExtent = v0.distanceTo( v1 ) * 0.5;
  13489. var a01 = - this.direction.dot( segDir );
  13490. var b0 = diff.dot( this.direction );
  13491. var b1 = - diff.dot( segDir );
  13492. var c = diff.lengthSq();
  13493. var det = Math.abs( 1 - a01 * a01 );
  13494. var s0, s1, sqrDist, extDet;
  13495. if ( det > 0 ) {
  13496. // The ray and segment are not parallel.
  13497. s0 = a01 * b1 - b0;
  13498. s1 = a01 * b0 - b1;
  13499. extDet = segExtent * det;
  13500. if ( s0 >= 0 ) {
  13501. if ( s1 >= - extDet ) {
  13502. if ( s1 <= extDet ) {
  13503. // region 0
  13504. // Minimum at interior points of ray and segment.
  13505. var invDet = 1 / det;
  13506. s0 *= invDet;
  13507. s1 *= invDet;
  13508. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  13509. } else {
  13510. // region 1
  13511. s1 = segExtent;
  13512. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  13513. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13514. }
  13515. } else {
  13516. // region 5
  13517. s1 = - segExtent;
  13518. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  13519. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13520. }
  13521. } else {
  13522. if ( s1 <= - extDet ) {
  13523. // region 4
  13524. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  13525. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  13526. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13527. } else if ( s1 <= extDet ) {
  13528. // region 3
  13529. s0 = 0;
  13530. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  13531. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  13532. } else {
  13533. // region 2
  13534. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  13535. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  13536. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13537. }
  13538. }
  13539. } else {
  13540. // Ray and segment are parallel.
  13541. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  13542. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  13543. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13544. }
  13545. if ( optionalPointOnRay ) {
  13546. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  13547. }
  13548. if ( optionalPointOnSegment ) {
  13549. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  13550. }
  13551. return sqrDist;
  13552. };
  13553. }(),
  13554. intersectSphere: function () {
  13555. var v1 = new Vector3();
  13556. return function intersectSphere( sphere, optionalTarget ) {
  13557. v1.subVectors( sphere.center, this.origin );
  13558. var tca = v1.dot( this.direction );
  13559. var d2 = v1.dot( v1 ) - tca * tca;
  13560. var radius2 = sphere.radius * sphere.radius;
  13561. if ( d2 > radius2 ) return null;
  13562. var thc = Math.sqrt( radius2 - d2 );
  13563. // t0 = first intersect point - entrance on front of sphere
  13564. var t0 = tca - thc;
  13565. // t1 = second intersect point - exit point on back of sphere
  13566. var t1 = tca + thc;
  13567. // test to see if both t0 and t1 are behind the ray - if so, return null
  13568. if ( t0 < 0 && t1 < 0 ) return null;
  13569. // test to see if t0 is behind the ray:
  13570. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  13571. // in order to always return an intersect point that is in front of the ray.
  13572. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  13573. // else t0 is in front of the ray, so return the first collision point scaled by t0
  13574. return this.at( t0, optionalTarget );
  13575. };
  13576. }(),
  13577. intersectsSphere: function ( sphere ) {
  13578. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  13579. },
  13580. distanceToPlane: function ( plane ) {
  13581. var denominator = plane.normal.dot( this.direction );
  13582. if ( denominator === 0 ) {
  13583. // line is coplanar, return origin
  13584. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  13585. return 0;
  13586. }
  13587. // Null is preferable to undefined since undefined means.... it is undefined
  13588. return null;
  13589. }
  13590. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  13591. // Return if the ray never intersects the plane
  13592. return t >= 0 ? t : null;
  13593. },
  13594. intersectPlane: function ( plane, optionalTarget ) {
  13595. var t = this.distanceToPlane( plane );
  13596. if ( t === null ) {
  13597. return null;
  13598. }
  13599. return this.at( t, optionalTarget );
  13600. },
  13601. intersectsPlane: function ( plane ) {
  13602. // check if the ray lies on the plane first
  13603. var distToPoint = plane.distanceToPoint( this.origin );
  13604. if ( distToPoint === 0 ) {
  13605. return true;
  13606. }
  13607. var denominator = plane.normal.dot( this.direction );
  13608. if ( denominator * distToPoint < 0 ) {
  13609. return true;
  13610. }
  13611. // ray origin is behind the plane (and is pointing behind it)
  13612. return false;
  13613. },
  13614. intersectBox: function ( box, optionalTarget ) {
  13615. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  13616. var invdirx = 1 / this.direction.x,
  13617. invdiry = 1 / this.direction.y,
  13618. invdirz = 1 / this.direction.z;
  13619. var origin = this.origin;
  13620. if ( invdirx >= 0 ) {
  13621. tmin = ( box.min.x - origin.x ) * invdirx;
  13622. tmax = ( box.max.x - origin.x ) * invdirx;
  13623. } else {
  13624. tmin = ( box.max.x - origin.x ) * invdirx;
  13625. tmax = ( box.min.x - origin.x ) * invdirx;
  13626. }
  13627. if ( invdiry >= 0 ) {
  13628. tymin = ( box.min.y - origin.y ) * invdiry;
  13629. tymax = ( box.max.y - origin.y ) * invdiry;
  13630. } else {
  13631. tymin = ( box.max.y - origin.y ) * invdiry;
  13632. tymax = ( box.min.y - origin.y ) * invdiry;
  13633. }
  13634. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  13635. // These lines also handle the case where tmin or tmax is NaN
  13636. // (result of 0 * Infinity). x !== x returns true if x is NaN
  13637. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  13638. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  13639. if ( invdirz >= 0 ) {
  13640. tzmin = ( box.min.z - origin.z ) * invdirz;
  13641. tzmax = ( box.max.z - origin.z ) * invdirz;
  13642. } else {
  13643. tzmin = ( box.max.z - origin.z ) * invdirz;
  13644. tzmax = ( box.min.z - origin.z ) * invdirz;
  13645. }
  13646. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  13647. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  13648. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  13649. //return point closest to the ray (positive side)
  13650. if ( tmax < 0 ) return null;
  13651. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  13652. },
  13653. intersectsBox: ( function () {
  13654. var v = new Vector3();
  13655. return function intersectsBox( box ) {
  13656. return this.intersectBox( box, v ) !== null;
  13657. };
  13658. } )(),
  13659. intersectTriangle: function () {
  13660. // Compute the offset origin, edges, and normal.
  13661. var diff = new Vector3();
  13662. var edge1 = new Vector3();
  13663. var edge2 = new Vector3();
  13664. var normal = new Vector3();
  13665. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  13666. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  13667. edge1.subVectors( b, a );
  13668. edge2.subVectors( c, a );
  13669. normal.crossVectors( edge1, edge2 );
  13670. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  13671. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  13672. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  13673. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  13674. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  13675. var DdN = this.direction.dot( normal );
  13676. var sign;
  13677. if ( DdN > 0 ) {
  13678. if ( backfaceCulling ) return null;
  13679. sign = 1;
  13680. } else if ( DdN < 0 ) {
  13681. sign = - 1;
  13682. DdN = - DdN;
  13683. } else {
  13684. return null;
  13685. }
  13686. diff.subVectors( this.origin, a );
  13687. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  13688. // b1 < 0, no intersection
  13689. if ( DdQxE2 < 0 ) {
  13690. return null;
  13691. }
  13692. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  13693. // b2 < 0, no intersection
  13694. if ( DdE1xQ < 0 ) {
  13695. return null;
  13696. }
  13697. // b1+b2 > 1, no intersection
  13698. if ( DdQxE2 + DdE1xQ > DdN ) {
  13699. return null;
  13700. }
  13701. // Line intersects triangle, check if ray does.
  13702. var QdN = - sign * diff.dot( normal );
  13703. // t < 0, no intersection
  13704. if ( QdN < 0 ) {
  13705. return null;
  13706. }
  13707. // Ray intersects triangle.
  13708. return this.at( QdN / DdN, optionalTarget );
  13709. };
  13710. }(),
  13711. applyMatrix4: function ( matrix4 ) {
  13712. this.origin.applyMatrix4( matrix4 );
  13713. this.direction.transformDirection( matrix4 );
  13714. return this;
  13715. },
  13716. equals: function ( ray ) {
  13717. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  13718. }
  13719. } );
  13720. /**
  13721. * @author bhouston / http://clara.io
  13722. */
  13723. function Line3( start, end ) {
  13724. this.start = ( start !== undefined ) ? start : new Vector3();
  13725. this.end = ( end !== undefined ) ? end : new Vector3();
  13726. }
  13727. Object.assign( Line3.prototype, {
  13728. set: function ( start, end ) {
  13729. this.start.copy( start );
  13730. this.end.copy( end );
  13731. return this;
  13732. },
  13733. clone: function () {
  13734. return new this.constructor().copy( this );
  13735. },
  13736. copy: function ( line ) {
  13737. this.start.copy( line.start );
  13738. this.end.copy( line.end );
  13739. return this;
  13740. },
  13741. getCenter: function ( optionalTarget ) {
  13742. var result = optionalTarget || new Vector3();
  13743. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  13744. },
  13745. delta: function ( optionalTarget ) {
  13746. var result = optionalTarget || new Vector3();
  13747. return result.subVectors( this.end, this.start );
  13748. },
  13749. distanceSq: function () {
  13750. return this.start.distanceToSquared( this.end );
  13751. },
  13752. distance: function () {
  13753. return this.start.distanceTo( this.end );
  13754. },
  13755. at: function ( t, optionalTarget ) {
  13756. var result = optionalTarget || new Vector3();
  13757. return this.delta( result ).multiplyScalar( t ).add( this.start );
  13758. },
  13759. closestPointToPointParameter: function () {
  13760. var startP = new Vector3();
  13761. var startEnd = new Vector3();
  13762. return function closestPointToPointParameter( point, clampToLine ) {
  13763. startP.subVectors( point, this.start );
  13764. startEnd.subVectors( this.end, this.start );
  13765. var startEnd2 = startEnd.dot( startEnd );
  13766. var startEnd_startP = startEnd.dot( startP );
  13767. var t = startEnd_startP / startEnd2;
  13768. if ( clampToLine ) {
  13769. t = _Math.clamp( t, 0, 1 );
  13770. }
  13771. return t;
  13772. };
  13773. }(),
  13774. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  13775. var t = this.closestPointToPointParameter( point, clampToLine );
  13776. var result = optionalTarget || new Vector3();
  13777. return this.delta( result ).multiplyScalar( t ).add( this.start );
  13778. },
  13779. applyMatrix4: function ( matrix ) {
  13780. this.start.applyMatrix4( matrix );
  13781. this.end.applyMatrix4( matrix );
  13782. return this;
  13783. },
  13784. equals: function ( line ) {
  13785. return line.start.equals( this.start ) && line.end.equals( this.end );
  13786. }
  13787. } );
  13788. /**
  13789. * @author bhouston / http://clara.io
  13790. * @author mrdoob / http://mrdoob.com/
  13791. */
  13792. function Triangle( a, b, c ) {
  13793. this.a = ( a !== undefined ) ? a : new Vector3();
  13794. this.b = ( b !== undefined ) ? b : new Vector3();
  13795. this.c = ( c !== undefined ) ? c : new Vector3();
  13796. }
  13797. Object.assign( Triangle, {
  13798. normal: function () {
  13799. var v0 = new Vector3();
  13800. return function normal( a, b, c, optionalTarget ) {
  13801. var result = optionalTarget || new Vector3();
  13802. result.subVectors( c, b );
  13803. v0.subVectors( a, b );
  13804. result.cross( v0 );
  13805. var resultLengthSq = result.lengthSq();
  13806. if ( resultLengthSq > 0 ) {
  13807. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  13808. }
  13809. return result.set( 0, 0, 0 );
  13810. };
  13811. }(),
  13812. // static/instance method to calculate barycentric coordinates
  13813. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  13814. barycoordFromPoint: function () {
  13815. var v0 = new Vector3();
  13816. var v1 = new Vector3();
  13817. var v2 = new Vector3();
  13818. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  13819. v0.subVectors( c, a );
  13820. v1.subVectors( b, a );
  13821. v2.subVectors( point, a );
  13822. var dot00 = v0.dot( v0 );
  13823. var dot01 = v0.dot( v1 );
  13824. var dot02 = v0.dot( v2 );
  13825. var dot11 = v1.dot( v1 );
  13826. var dot12 = v1.dot( v2 );
  13827. var denom = ( dot00 * dot11 - dot01 * dot01 );
  13828. var result = optionalTarget || new Vector3();
  13829. // collinear or singular triangle
  13830. if ( denom === 0 ) {
  13831. // arbitrary location outside of triangle?
  13832. // not sure if this is the best idea, maybe should be returning undefined
  13833. return result.set( - 2, - 1, - 1 );
  13834. }
  13835. var invDenom = 1 / denom;
  13836. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  13837. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  13838. // barycentric coordinates must always sum to 1
  13839. return result.set( 1 - u - v, v, u );
  13840. };
  13841. }(),
  13842. containsPoint: function () {
  13843. var v1 = new Vector3();
  13844. return function containsPoint( point, a, b, c ) {
  13845. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  13846. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  13847. };
  13848. }()
  13849. } );
  13850. Object.assign( Triangle.prototype, {
  13851. set: function ( a, b, c ) {
  13852. this.a.copy( a );
  13853. this.b.copy( b );
  13854. this.c.copy( c );
  13855. return this;
  13856. },
  13857. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  13858. this.a.copy( points[ i0 ] );
  13859. this.b.copy( points[ i1 ] );
  13860. this.c.copy( points[ i2 ] );
  13861. return this;
  13862. },
  13863. clone: function () {
  13864. return new this.constructor().copy( this );
  13865. },
  13866. copy: function ( triangle ) {
  13867. this.a.copy( triangle.a );
  13868. this.b.copy( triangle.b );
  13869. this.c.copy( triangle.c );
  13870. return this;
  13871. },
  13872. area: function () {
  13873. var v0 = new Vector3();
  13874. var v1 = new Vector3();
  13875. return function area() {
  13876. v0.subVectors( this.c, this.b );
  13877. v1.subVectors( this.a, this.b );
  13878. return v0.cross( v1 ).length() * 0.5;
  13879. };
  13880. }(),
  13881. midpoint: function ( optionalTarget ) {
  13882. var result = optionalTarget || new Vector3();
  13883. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  13884. },
  13885. normal: function ( optionalTarget ) {
  13886. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  13887. },
  13888. plane: function ( optionalTarget ) {
  13889. var result = optionalTarget || new Plane();
  13890. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  13891. },
  13892. barycoordFromPoint: function ( point, optionalTarget ) {
  13893. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  13894. },
  13895. containsPoint: function ( point ) {
  13896. return Triangle.containsPoint( point, this.a, this.b, this.c );
  13897. },
  13898. closestPointToPoint: function () {
  13899. var plane = new Plane();
  13900. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  13901. var projectedPoint = new Vector3();
  13902. var closestPoint = new Vector3();
  13903. return function closestPointToPoint( point, optionalTarget ) {
  13904. var result = optionalTarget || new Vector3();
  13905. var minDistance = Infinity;
  13906. // project the point onto the plane of the triangle
  13907. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  13908. plane.projectPoint( point, projectedPoint );
  13909. // check if the projection lies within the triangle
  13910. if( this.containsPoint( projectedPoint ) === true ) {
  13911. // if so, this is the closest point
  13912. result.copy( projectedPoint );
  13913. } else {
  13914. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  13915. edgeList[ 0 ].set( this.a, this.b );
  13916. edgeList[ 1 ].set( this.b, this.c );
  13917. edgeList[ 2 ].set( this.c, this.a );
  13918. for( var i = 0; i < edgeList.length; i ++ ) {
  13919. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  13920. var distance = projectedPoint.distanceToSquared( closestPoint );
  13921. if( distance < minDistance ) {
  13922. minDistance = distance;
  13923. result.copy( closestPoint );
  13924. }
  13925. }
  13926. }
  13927. return result;
  13928. };
  13929. }(),
  13930. equals: function ( triangle ) {
  13931. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  13932. }
  13933. } );
  13934. /**
  13935. * @author mrdoob / http://mrdoob.com/
  13936. * @author alteredq / http://alteredqualia.com/
  13937. * @author mikael emtinger / http://gomo.se/
  13938. * @author jonobr1 / http://jonobr1.com/
  13939. */
  13940. function Mesh( geometry, material ) {
  13941. Object3D.call( this );
  13942. this.type = 'Mesh';
  13943. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13944. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13945. this.drawMode = TrianglesDrawMode;
  13946. this.updateMorphTargets();
  13947. }
  13948. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13949. constructor: Mesh,
  13950. isMesh: true,
  13951. setDrawMode: function ( value ) {
  13952. this.drawMode = value;
  13953. },
  13954. copy: function ( source ) {
  13955. Object3D.prototype.copy.call( this, source );
  13956. this.drawMode = source.drawMode;
  13957. return this;
  13958. },
  13959. updateMorphTargets: function () {
  13960. var geometry = this.geometry;
  13961. var m, ml, name;
  13962. if ( geometry.isBufferGeometry ) {
  13963. var morphAttributes = geometry.morphAttributes;
  13964. var keys = Object.keys( morphAttributes );
  13965. if ( keys.length > 0 ) {
  13966. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  13967. if ( morphAttribute !== undefined ) {
  13968. this.morphTargetInfluences = [];
  13969. this.morphTargetDictionary = {};
  13970. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  13971. name = morphAttribute[ m ].name || String( m );
  13972. this.morphTargetInfluences.push( 0 );
  13973. this.morphTargetDictionary[ name ] = m;
  13974. }
  13975. }
  13976. }
  13977. } else {
  13978. var morphTargets = geometry.morphTargets;
  13979. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  13980. this.morphTargetInfluences = [];
  13981. this.morphTargetDictionary = {};
  13982. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  13983. name = morphTargets[ m ].name || String( m );
  13984. this.morphTargetInfluences.push( 0 );
  13985. this.morphTargetDictionary[ name ] = m;
  13986. }
  13987. }
  13988. }
  13989. },
  13990. raycast: ( function () {
  13991. var inverseMatrix = new Matrix4();
  13992. var ray = new Ray();
  13993. var sphere = new Sphere();
  13994. var vA = new Vector3();
  13995. var vB = new Vector3();
  13996. var vC = new Vector3();
  13997. var tempA = new Vector3();
  13998. var tempB = new Vector3();
  13999. var tempC = new Vector3();
  14000. var uvA = new Vector2();
  14001. var uvB = new Vector2();
  14002. var uvC = new Vector2();
  14003. var barycoord = new Vector3();
  14004. var intersectionPoint = new Vector3();
  14005. var intersectionPointWorld = new Vector3();
  14006. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  14007. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  14008. uv1.multiplyScalar( barycoord.x );
  14009. uv2.multiplyScalar( barycoord.y );
  14010. uv3.multiplyScalar( barycoord.z );
  14011. uv1.add( uv2 ).add( uv3 );
  14012. return uv1.clone();
  14013. }
  14014. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  14015. var intersect;
  14016. if ( material.side === BackSide ) {
  14017. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  14018. } else {
  14019. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  14020. }
  14021. if ( intersect === null ) return null;
  14022. intersectionPointWorld.copy( point );
  14023. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  14024. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  14025. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  14026. return {
  14027. distance: distance,
  14028. point: intersectionPointWorld.clone(),
  14029. object: object
  14030. };
  14031. }
  14032. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  14033. vA.fromBufferAttribute( position, a );
  14034. vB.fromBufferAttribute( position, b );
  14035. vC.fromBufferAttribute( position, c );
  14036. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  14037. if ( intersection ) {
  14038. if ( uv ) {
  14039. uvA.fromBufferAttribute( uv, a );
  14040. uvB.fromBufferAttribute( uv, b );
  14041. uvC.fromBufferAttribute( uv, c );
  14042. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  14043. }
  14044. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  14045. intersection.faceIndex = a;
  14046. }
  14047. return intersection;
  14048. }
  14049. return function raycast( raycaster, intersects ) {
  14050. var geometry = this.geometry;
  14051. var material = this.material;
  14052. var matrixWorld = this.matrixWorld;
  14053. if ( material === undefined ) return;
  14054. // Checking boundingSphere distance to ray
  14055. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14056. sphere.copy( geometry.boundingSphere );
  14057. sphere.applyMatrix4( matrixWorld );
  14058. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14059. //
  14060. inverseMatrix.getInverse( matrixWorld );
  14061. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14062. // Check boundingBox before continuing
  14063. if ( geometry.boundingBox !== null ) {
  14064. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  14065. }
  14066. var intersection;
  14067. if ( geometry.isBufferGeometry ) {
  14068. var a, b, c;
  14069. var index = geometry.index;
  14070. var position = geometry.attributes.position;
  14071. var uv = geometry.attributes.uv;
  14072. var i, l;
  14073. if ( index !== null ) {
  14074. // indexed buffer geometry
  14075. for ( i = 0, l = index.count; i < l; i += 3 ) {
  14076. a = index.getX( i );
  14077. b = index.getX( i + 1 );
  14078. c = index.getX( i + 2 );
  14079. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  14080. if ( intersection ) {
  14081. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  14082. intersects.push( intersection );
  14083. }
  14084. }
  14085. } else {
  14086. // non-indexed buffer geometry
  14087. for ( i = 0, l = position.count; i < l; i += 3 ) {
  14088. a = i;
  14089. b = i + 1;
  14090. c = i + 2;
  14091. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  14092. if ( intersection ) {
  14093. intersection.index = a; // triangle number in positions buffer semantics
  14094. intersects.push( intersection );
  14095. }
  14096. }
  14097. }
  14098. } else if ( geometry.isGeometry ) {
  14099. var fvA, fvB, fvC;
  14100. var isMultiMaterial = Array.isArray( material );
  14101. var vertices = geometry.vertices;
  14102. var faces = geometry.faces;
  14103. var uvs;
  14104. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  14105. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  14106. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  14107. var face = faces[ f ];
  14108. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  14109. if ( faceMaterial === undefined ) continue;
  14110. fvA = vertices[ face.a ];
  14111. fvB = vertices[ face.b ];
  14112. fvC = vertices[ face.c ];
  14113. if ( faceMaterial.morphTargets === true ) {
  14114. var morphTargets = geometry.morphTargets;
  14115. var morphInfluences = this.morphTargetInfluences;
  14116. vA.set( 0, 0, 0 );
  14117. vB.set( 0, 0, 0 );
  14118. vC.set( 0, 0, 0 );
  14119. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  14120. var influence = morphInfluences[ t ];
  14121. if ( influence === 0 ) continue;
  14122. var targets = morphTargets[ t ].vertices;
  14123. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  14124. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  14125. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  14126. }
  14127. vA.add( fvA );
  14128. vB.add( fvB );
  14129. vC.add( fvC );
  14130. fvA = vA;
  14131. fvB = vB;
  14132. fvC = vC;
  14133. }
  14134. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  14135. if ( intersection ) {
  14136. if ( uvs && uvs[ f ] ) {
  14137. var uvs_f = uvs[ f ];
  14138. uvA.copy( uvs_f[ 0 ] );
  14139. uvB.copy( uvs_f[ 1 ] );
  14140. uvC.copy( uvs_f[ 2 ] );
  14141. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  14142. }
  14143. intersection.face = face;
  14144. intersection.faceIndex = f;
  14145. intersects.push( intersection );
  14146. }
  14147. }
  14148. }
  14149. };
  14150. }() ),
  14151. clone: function () {
  14152. return new this.constructor( this.geometry, this.material ).copy( this );
  14153. }
  14154. } );
  14155. /**
  14156. * @author mrdoob / http://mrdoob.com/
  14157. */
  14158. function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) {
  14159. var clearColor = new Color( 0x000000 );
  14160. var clearAlpha = 0;
  14161. var planeCamera, planeMesh;
  14162. var boxMesh;
  14163. function render( renderList, scene, camera, forceClear ) {
  14164. var background = scene.background;
  14165. if ( background === null ) {
  14166. setClear( clearColor, clearAlpha );
  14167. } else if ( background && background.isColor ) {
  14168. setClear( background, 1 );
  14169. forceClear = true;
  14170. }
  14171. if ( renderer.autoClear || forceClear ) {
  14172. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  14173. }
  14174. if ( background && background.isCubeTexture ) {
  14175. if ( boxMesh === undefined ) {
  14176. boxMesh = new Mesh(
  14177. new BoxBufferGeometry( 1, 1, 1 ),
  14178. new ShaderMaterial( {
  14179. uniforms: ShaderLib.cube.uniforms,
  14180. vertexShader: ShaderLib.cube.vertexShader,
  14181. fragmentShader: ShaderLib.cube.fragmentShader,
  14182. side: BackSide,
  14183. depthTest: true,
  14184. depthWrite: false,
  14185. polygonOffset: true,
  14186. fog: false
  14187. } )
  14188. );
  14189. boxMesh.geometry.removeAttribute( 'normal' );
  14190. boxMesh.geometry.removeAttribute( 'uv' );
  14191. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14192. var scale = camera.far;
  14193. this.matrixWorld.makeScale( scale, scale, scale );
  14194. this.matrixWorld.copyPosition( camera.matrixWorld );
  14195. this.material.polygonOffsetUnits = scale * 10;
  14196. };
  14197. geometries.update( boxMesh.geometry );
  14198. }
  14199. boxMesh.material.uniforms.tCube.value = background;
  14200. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  14201. } else if ( background && background.isTexture ) {
  14202. if ( planeCamera === undefined ) {
  14203. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14204. planeMesh = new Mesh(
  14205. new PlaneBufferGeometry( 2, 2 ),
  14206. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  14207. );
  14208. geometries.update( planeMesh.geometry );
  14209. }
  14210. planeMesh.material.map = background;
  14211. // TODO Push this to renderList
  14212. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  14213. }
  14214. }
  14215. function setClear( color, alpha ) {
  14216. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  14217. }
  14218. return {
  14219. getClearColor: function () {
  14220. return clearColor;
  14221. },
  14222. setClearColor: function ( color, alpha ) {
  14223. clearColor.set( color );
  14224. clearAlpha = alpha !== undefined ? alpha : 1;
  14225. setClear( clearColor, clearAlpha );
  14226. },
  14227. getClearAlpha: function () {
  14228. return clearAlpha;
  14229. },
  14230. setClearAlpha: function ( alpha ) {
  14231. clearAlpha = alpha;
  14232. setClear( clearColor, clearAlpha );
  14233. },
  14234. render: render
  14235. };
  14236. }
  14237. /**
  14238. * @author mrdoob / http://mrdoob.com/
  14239. */
  14240. function painterSortStable( a, b ) {
  14241. if ( a.renderOrder !== b.renderOrder ) {
  14242. return a.renderOrder - b.renderOrder;
  14243. } else if ( a.program && b.program && a.program !== b.program ) {
  14244. return a.program.id - b.program.id;
  14245. } else if ( a.material.id !== b.material.id ) {
  14246. return a.material.id - b.material.id;
  14247. } else if ( a.z !== b.z ) {
  14248. return a.z - b.z;
  14249. } else {
  14250. return a.id - b.id;
  14251. }
  14252. }
  14253. function reversePainterSortStable( a, b ) {
  14254. if ( a.renderOrder !== b.renderOrder ) {
  14255. return a.renderOrder - b.renderOrder;
  14256. } if ( a.z !== b.z ) {
  14257. return b.z - a.z;
  14258. } else {
  14259. return a.id - b.id;
  14260. }
  14261. }
  14262. function WebGLRenderList() {
  14263. var renderItems = [];
  14264. var renderItemsIndex = 0;
  14265. var opaque = [];
  14266. var transparent = [];
  14267. function init() {
  14268. renderItemsIndex = 0;
  14269. opaque.length = 0;
  14270. transparent.length = 0;
  14271. }
  14272. function push( object, geometry, material, z, group ) {
  14273. var renderItem = renderItems[ renderItemsIndex ];
  14274. if ( renderItem === undefined ) {
  14275. renderItem = {
  14276. id: object.id,
  14277. object: object,
  14278. geometry: geometry,
  14279. material: material,
  14280. program: material.program,
  14281. renderOrder: object.renderOrder,
  14282. z: z,
  14283. group: group
  14284. };
  14285. renderItems[ renderItemsIndex ] = renderItem;
  14286. } else {
  14287. renderItem.id = object.id;
  14288. renderItem.object = object;
  14289. renderItem.geometry = geometry;
  14290. renderItem.material = material;
  14291. renderItem.program = material.program;
  14292. renderItem.renderOrder = object.renderOrder;
  14293. renderItem.z = z;
  14294. renderItem.group = group;
  14295. }
  14296. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  14297. renderItemsIndex ++;
  14298. }
  14299. function sort() {
  14300. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  14301. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  14302. }
  14303. return {
  14304. opaque: opaque,
  14305. transparent: transparent,
  14306. init: init,
  14307. push: push,
  14308. sort: sort
  14309. };
  14310. }
  14311. function WebGLRenderLists() {
  14312. var lists = {};
  14313. function get( scene, camera ) {
  14314. var hash = scene.id + ',' + camera.id;
  14315. var list = lists[ hash ];
  14316. if ( list === undefined ) {
  14317. // console.log( 'THREE.WebGLRenderLists:', hash );
  14318. list = new WebGLRenderList();
  14319. lists[ hash ] = list;
  14320. }
  14321. return list;
  14322. }
  14323. function dispose() {
  14324. lists = {};
  14325. }
  14326. return {
  14327. get: get,
  14328. dispose: dispose
  14329. };
  14330. }
  14331. /**
  14332. * @author mrdoob / http://mrdoob.com/
  14333. */
  14334. function absNumericalSort( a, b ) {
  14335. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  14336. }
  14337. function WebGLMorphtargets( gl ) {
  14338. var influencesList = {};
  14339. var morphInfluences = new Float32Array( 8 );
  14340. function update( object, geometry, material, program ) {
  14341. var objectInfluences = object.morphTargetInfluences;
  14342. var length = objectInfluences.length;
  14343. var influences = influencesList[ geometry.id ];
  14344. if ( influences === undefined ) {
  14345. // initialise list
  14346. influences = [];
  14347. for ( var i = 0; i < length; i ++ ) {
  14348. influences[ i ] = [ i, 0 ];
  14349. }
  14350. influencesList[ geometry.id ] = influences;
  14351. }
  14352. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  14353. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  14354. // Remove current morphAttributes
  14355. for ( var i = 0; i < length; i ++ ) {
  14356. var influence = influences[ i ];
  14357. if ( influence[ 1 ] !== 0 ) {
  14358. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  14359. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  14360. }
  14361. }
  14362. // Collect influences
  14363. for ( var i = 0; i < length; i ++ ) {
  14364. var influence = influences[ i ];
  14365. influence[ 0 ] = i;
  14366. influence[ 1 ] = objectInfluences[ i ];
  14367. }
  14368. influences.sort( absNumericalSort );
  14369. // Add morphAttributes
  14370. for ( var i = 0; i < 8; i ++ ) {
  14371. var influence = influences[ i ];
  14372. if ( influence ) {
  14373. var index = influence[ 0 ];
  14374. var value = influence[ 1 ];
  14375. if ( value ) {
  14376. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  14377. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  14378. morphInfluences[ i ] = value;
  14379. continue;
  14380. }
  14381. }
  14382. morphInfluences[ i ] = 0;
  14383. }
  14384. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  14385. }
  14386. return {
  14387. update: update
  14388. }
  14389. }
  14390. /**
  14391. * @author mrdoob / http://mrdoob.com/
  14392. */
  14393. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  14394. var mode;
  14395. function setMode( value ) {
  14396. mode = value;
  14397. }
  14398. var type, bytesPerElement;
  14399. function setIndex( value ) {
  14400. type = value.type;
  14401. bytesPerElement = value.bytesPerElement;
  14402. }
  14403. function render( start, count ) {
  14404. gl.drawElements( mode, count, type, start * bytesPerElement );
  14405. infoRender.calls ++;
  14406. infoRender.vertices += count;
  14407. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  14408. else if ( mode === gl.POINTS ) infoRender.points += count;
  14409. }
  14410. function renderInstances( geometry, start, count ) {
  14411. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14412. if ( extension === null ) {
  14413. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14414. return;
  14415. }
  14416. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  14417. infoRender.calls ++;
  14418. infoRender.vertices += count * geometry.maxInstancedCount;
  14419. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  14420. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  14421. }
  14422. //
  14423. this.setMode = setMode;
  14424. this.setIndex = setIndex;
  14425. this.render = render;
  14426. this.renderInstances = renderInstances;
  14427. }
  14428. /**
  14429. * @author mrdoob / http://mrdoob.com/
  14430. */
  14431. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  14432. var mode;
  14433. function setMode( value ) {
  14434. mode = value;
  14435. }
  14436. function render( start, count ) {
  14437. gl.drawArrays( mode, start, count );
  14438. infoRender.calls ++;
  14439. infoRender.vertices += count;
  14440. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  14441. else if ( mode === gl.POINTS ) infoRender.points += count;
  14442. }
  14443. function renderInstances( geometry, start, count ) {
  14444. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14445. if ( extension === null ) {
  14446. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14447. return;
  14448. }
  14449. var position = geometry.attributes.position;
  14450. if ( position.isInterleavedBufferAttribute ) {
  14451. count = position.data.count;
  14452. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  14453. } else {
  14454. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  14455. }
  14456. infoRender.calls ++;
  14457. infoRender.vertices += count * geometry.maxInstancedCount;
  14458. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  14459. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  14460. }
  14461. //
  14462. this.setMode = setMode;
  14463. this.render = render;
  14464. this.renderInstances = renderInstances;
  14465. }
  14466. /**
  14467. * @author mrdoob / http://mrdoob.com/
  14468. */
  14469. function WebGLGeometries( gl, attributes, infoMemory ) {
  14470. var geometries = {};
  14471. var wireframeAttributes = {};
  14472. function onGeometryDispose( event ) {
  14473. var geometry = event.target;
  14474. var buffergeometry = geometries[ geometry.id ];
  14475. if ( buffergeometry.index !== null ) {
  14476. attributes.remove( buffergeometry.index );
  14477. }
  14478. for ( var name in buffergeometry.attributes ) {
  14479. attributes.remove( buffergeometry.attributes[ name ] );
  14480. }
  14481. geometry.removeEventListener( 'dispose', onGeometryDispose );
  14482. delete geometries[ geometry.id ];
  14483. // TODO Remove duplicate code
  14484. var attribute = wireframeAttributes[ geometry.id ];
  14485. if ( attribute ) {
  14486. attributes.remove( attribute );
  14487. delete wireframeAttributes[ geometry.id ];
  14488. }
  14489. attribute = wireframeAttributes[ buffergeometry.id ];
  14490. if ( attribute ) {
  14491. attributes.remove( attribute );
  14492. delete wireframeAttributes[ buffergeometry.id ];
  14493. }
  14494. //
  14495. infoMemory.geometries --;
  14496. }
  14497. function get( object, geometry ) {
  14498. var buffergeometry = geometries[ geometry.id ];
  14499. if ( buffergeometry ) return buffergeometry;
  14500. geometry.addEventListener( 'dispose', onGeometryDispose );
  14501. if ( geometry.isBufferGeometry ) {
  14502. buffergeometry = geometry;
  14503. } else if ( geometry.isGeometry ) {
  14504. if ( geometry._bufferGeometry === undefined ) {
  14505. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  14506. }
  14507. buffergeometry = geometry._bufferGeometry;
  14508. }
  14509. geometries[ geometry.id ] = buffergeometry;
  14510. infoMemory.geometries ++;
  14511. return buffergeometry;
  14512. }
  14513. function update( geometry ) {
  14514. var index = geometry.index;
  14515. var geometryAttributes = geometry.attributes;
  14516. if ( index !== null ) {
  14517. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  14518. }
  14519. for ( var name in geometryAttributes ) {
  14520. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  14521. }
  14522. // morph targets
  14523. var morphAttributes = geometry.morphAttributes;
  14524. for ( var name in morphAttributes ) {
  14525. var array = morphAttributes[ name ];
  14526. for ( var i = 0, l = array.length; i < l; i ++ ) {
  14527. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  14528. }
  14529. }
  14530. }
  14531. function getWireframeAttribute( geometry ) {
  14532. var attribute = wireframeAttributes[ geometry.id ];
  14533. if ( attribute ) return attribute;
  14534. var indices = [];
  14535. var geometryIndex = geometry.index;
  14536. var geometryAttributes = geometry.attributes;
  14537. // console.time( 'wireframe' );
  14538. if ( geometryIndex !== null ) {
  14539. var array = geometryIndex.array;
  14540. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  14541. var a = array[ i + 0 ];
  14542. var b = array[ i + 1 ];
  14543. var c = array[ i + 2 ];
  14544. indices.push( a, b, b, c, c, a );
  14545. }
  14546. } else {
  14547. var array = geometryAttributes.position.array;
  14548. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  14549. var a = i + 0;
  14550. var b = i + 1;
  14551. var c = i + 2;
  14552. indices.push( a, b, b, c, c, a );
  14553. }
  14554. }
  14555. // console.timeEnd( 'wireframe' );
  14556. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  14557. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  14558. wireframeAttributes[ geometry.id ] = attribute;
  14559. return attribute;
  14560. }
  14561. return {
  14562. get: get,
  14563. update: update,
  14564. getWireframeAttribute: getWireframeAttribute
  14565. };
  14566. }
  14567. /**
  14568. * @author mrdoob / http://mrdoob.com/
  14569. */
  14570. function UniformsCache() {
  14571. var lights = {};
  14572. return {
  14573. get: function ( light ) {
  14574. if ( lights[ light.id ] !== undefined ) {
  14575. return lights[ light.id ];
  14576. }
  14577. var uniforms;
  14578. switch ( light.type ) {
  14579. case 'DirectionalLight':
  14580. uniforms = {
  14581. direction: new Vector3(),
  14582. color: new Color(),
  14583. shadow: false,
  14584. shadowBias: 0,
  14585. shadowRadius: 1,
  14586. shadowMapSize: new Vector2()
  14587. };
  14588. break;
  14589. case 'SpotLight':
  14590. uniforms = {
  14591. position: new Vector3(),
  14592. direction: new Vector3(),
  14593. color: new Color(),
  14594. distance: 0,
  14595. coneCos: 0,
  14596. penumbraCos: 0,
  14597. decay: 0,
  14598. shadow: false,
  14599. shadowBias: 0,
  14600. shadowRadius: 1,
  14601. shadowMapSize: new Vector2()
  14602. };
  14603. break;
  14604. case 'PointLight':
  14605. uniforms = {
  14606. position: new Vector3(),
  14607. color: new Color(),
  14608. distance: 0,
  14609. decay: 0,
  14610. shadow: false,
  14611. shadowBias: 0,
  14612. shadowRadius: 1,
  14613. shadowMapSize: new Vector2(),
  14614. shadowCameraNear: 1,
  14615. shadowCameraFar: 1000
  14616. };
  14617. break;
  14618. case 'HemisphereLight':
  14619. uniforms = {
  14620. direction: new Vector3(),
  14621. skyColor: new Color(),
  14622. groundColor: new Color()
  14623. };
  14624. break;
  14625. case 'RectAreaLight':
  14626. uniforms = {
  14627. color: new Color(),
  14628. position: new Vector3(),
  14629. halfWidth: new Vector3(),
  14630. halfHeight: new Vector3()
  14631. // TODO (abelnation): set RectAreaLight shadow uniforms
  14632. };
  14633. break;
  14634. }
  14635. lights[ light.id ] = uniforms;
  14636. return uniforms;
  14637. }
  14638. };
  14639. }
  14640. function WebGLLights() {
  14641. var cache = new UniformsCache();
  14642. var state = {
  14643. hash: '',
  14644. ambient: [ 0, 0, 0 ],
  14645. directional: [],
  14646. directionalShadowMap: [],
  14647. directionalShadowMatrix: [],
  14648. spot: [],
  14649. spotShadowMap: [],
  14650. spotShadowMatrix: [],
  14651. rectArea: [],
  14652. point: [],
  14653. pointShadowMap: [],
  14654. pointShadowMatrix: [],
  14655. hemi: []
  14656. };
  14657. var vector3 = new Vector3();
  14658. var matrix4 = new Matrix4();
  14659. var matrix42 = new Matrix4();
  14660. function setup( lights, shadows, camera ) {
  14661. var r = 0, g = 0, b = 0;
  14662. var directionalLength = 0;
  14663. var pointLength = 0;
  14664. var spotLength = 0;
  14665. var rectAreaLength = 0;
  14666. var hemiLength = 0;
  14667. var viewMatrix = camera.matrixWorldInverse;
  14668. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  14669. var light = lights[ i ];
  14670. var color = light.color;
  14671. var intensity = light.intensity;
  14672. var distance = light.distance;
  14673. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  14674. if ( light.isAmbientLight ) {
  14675. r += color.r * intensity;
  14676. g += color.g * intensity;
  14677. b += color.b * intensity;
  14678. } else if ( light.isDirectionalLight ) {
  14679. var uniforms = cache.get( light );
  14680. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14681. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14682. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14683. uniforms.direction.sub( vector3 );
  14684. uniforms.direction.transformDirection( viewMatrix );
  14685. uniforms.shadow = light.castShadow;
  14686. if ( light.castShadow ) {
  14687. var shadow = light.shadow;
  14688. uniforms.shadowBias = shadow.bias;
  14689. uniforms.shadowRadius = shadow.radius;
  14690. uniforms.shadowMapSize = shadow.mapSize;
  14691. }
  14692. state.directionalShadowMap[ directionalLength ] = shadowMap;
  14693. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  14694. state.directional[ directionalLength ] = uniforms;
  14695. directionalLength ++;
  14696. } else if ( light.isSpotLight ) {
  14697. var uniforms = cache.get( light );
  14698. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14699. uniforms.position.applyMatrix4( viewMatrix );
  14700. uniforms.color.copy( color ).multiplyScalar( intensity );
  14701. uniforms.distance = distance;
  14702. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14703. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14704. uniforms.direction.sub( vector3 );
  14705. uniforms.direction.transformDirection( viewMatrix );
  14706. uniforms.coneCos = Math.cos( light.angle );
  14707. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  14708. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14709. uniforms.shadow = light.castShadow;
  14710. if ( light.castShadow ) {
  14711. var shadow = light.shadow;
  14712. uniforms.shadowBias = shadow.bias;
  14713. uniforms.shadowRadius = shadow.radius;
  14714. uniforms.shadowMapSize = shadow.mapSize;
  14715. }
  14716. state.spotShadowMap[ spotLength ] = shadowMap;
  14717. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  14718. state.spot[ spotLength ] = uniforms;
  14719. spotLength ++;
  14720. } else if ( light.isRectAreaLight ) {
  14721. var uniforms = cache.get( light );
  14722. // (a) intensity controls irradiance of entire light
  14723. uniforms.color
  14724. .copy( color )
  14725. .multiplyScalar( intensity / ( light.width * light.height ) );
  14726. // (b) intensity controls the radiance per light area
  14727. // uniforms.color.copy( color ).multiplyScalar( intensity );
  14728. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14729. uniforms.position.applyMatrix4( viewMatrix );
  14730. // extract local rotation of light to derive width/height half vectors
  14731. matrix42.identity();
  14732. matrix4.copy( light.matrixWorld );
  14733. matrix4.premultiply( viewMatrix );
  14734. matrix42.extractRotation( matrix4 );
  14735. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  14736. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  14737. uniforms.halfWidth.applyMatrix4( matrix42 );
  14738. uniforms.halfHeight.applyMatrix4( matrix42 );
  14739. // TODO (abelnation): RectAreaLight distance?
  14740. // uniforms.distance = distance;
  14741. state.rectArea[ rectAreaLength ] = uniforms;
  14742. rectAreaLength ++;
  14743. } else if ( light.isPointLight ) {
  14744. var uniforms = cache.get( light );
  14745. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14746. uniforms.position.applyMatrix4( viewMatrix );
  14747. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14748. uniforms.distance = light.distance;
  14749. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14750. uniforms.shadow = light.castShadow;
  14751. if ( light.castShadow ) {
  14752. var shadow = light.shadow;
  14753. uniforms.shadowBias = shadow.bias;
  14754. uniforms.shadowRadius = shadow.radius;
  14755. uniforms.shadowMapSize = shadow.mapSize;
  14756. uniforms.shadowCameraNear = shadow.camera.near;
  14757. uniforms.shadowCameraFar = shadow.camera.far;
  14758. }
  14759. state.pointShadowMap[ pointLength ] = shadowMap;
  14760. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  14761. state.point[ pointLength ] = uniforms;
  14762. pointLength ++;
  14763. } else if ( light.isHemisphereLight ) {
  14764. var uniforms = cache.get( light );
  14765. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14766. uniforms.direction.transformDirection( viewMatrix );
  14767. uniforms.direction.normalize();
  14768. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  14769. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  14770. state.hemi[ hemiLength ] = uniforms;
  14771. hemiLength ++;
  14772. }
  14773. }
  14774. state.ambient[ 0 ] = r;
  14775. state.ambient[ 1 ] = g;
  14776. state.ambient[ 2 ] = b;
  14777. state.directional.length = directionalLength;
  14778. state.spot.length = spotLength;
  14779. state.rectArea.length = rectAreaLength;
  14780. state.point.length = pointLength;
  14781. state.hemi.length = hemiLength;
  14782. // TODO (sam-g-steel) why aren't we using join
  14783. state.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  14784. }
  14785. return {
  14786. setup: setup,
  14787. state: state
  14788. }
  14789. }
  14790. /**
  14791. * @author mrdoob / http://mrdoob.com/
  14792. */
  14793. function WebGLObjects( geometries, infoRender ) {
  14794. var updateList = {};
  14795. function update( object ) {
  14796. var frame = infoRender.frame;
  14797. var geometry = object.geometry;
  14798. var buffergeometry = geometries.get( object, geometry );
  14799. // Update once per frame
  14800. if ( updateList[ buffergeometry.id ] !== frame ) {
  14801. if ( geometry.isGeometry ) {
  14802. buffergeometry.updateFromObject( object );
  14803. }
  14804. geometries.update( buffergeometry );
  14805. updateList[ buffergeometry.id ] = frame;
  14806. }
  14807. return buffergeometry;
  14808. }
  14809. function clear() {
  14810. updateList = {};
  14811. }
  14812. return {
  14813. update: update,
  14814. clear: clear
  14815. };
  14816. }
  14817. /**
  14818. * @author mrdoob / http://mrdoob.com/
  14819. */
  14820. function addLineNumbers( string ) {
  14821. var lines = string.split( '\n' );
  14822. for ( var i = 0; i < lines.length; i ++ ) {
  14823. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14824. }
  14825. return lines.join( '\n' );
  14826. }
  14827. function WebGLShader( gl, type, string ) {
  14828. var shader = gl.createShader( type );
  14829. gl.shaderSource( shader, string );
  14830. gl.compileShader( shader );
  14831. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14832. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14833. }
  14834. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14835. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14836. }
  14837. // --enable-privileged-webgl-extension
  14838. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14839. return shader;
  14840. }
  14841. /**
  14842. * @author mrdoob / http://mrdoob.com/
  14843. */
  14844. var programIdCount = 0;
  14845. function getEncodingComponents( encoding ) {
  14846. switch ( encoding ) {
  14847. case LinearEncoding:
  14848. return [ 'Linear','( value )' ];
  14849. case sRGBEncoding:
  14850. return [ 'sRGB','( value )' ];
  14851. case RGBEEncoding:
  14852. return [ 'RGBE','( value )' ];
  14853. case RGBM7Encoding:
  14854. return [ 'RGBM','( value, 7.0 )' ];
  14855. case RGBM16Encoding:
  14856. return [ 'RGBM','( value, 16.0 )' ];
  14857. case RGBDEncoding:
  14858. return [ 'RGBD','( value, 256.0 )' ];
  14859. case GammaEncoding:
  14860. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  14861. default:
  14862. throw new Error( 'unsupported encoding: ' + encoding );
  14863. }
  14864. }
  14865. function getTexelDecodingFunction( functionName, encoding ) {
  14866. var components = getEncodingComponents( encoding );
  14867. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  14868. }
  14869. function getTexelEncodingFunction( functionName, encoding ) {
  14870. var components = getEncodingComponents( encoding );
  14871. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  14872. }
  14873. function getToneMappingFunction( functionName, toneMapping ) {
  14874. var toneMappingName;
  14875. switch ( toneMapping ) {
  14876. case LinearToneMapping:
  14877. toneMappingName = "Linear";
  14878. break;
  14879. case ReinhardToneMapping:
  14880. toneMappingName = "Reinhard";
  14881. break;
  14882. case Uncharted2ToneMapping:
  14883. toneMappingName = "Uncharted2";
  14884. break;
  14885. case CineonToneMapping:
  14886. toneMappingName = "OptimizedCineon";
  14887. break;
  14888. default:
  14889. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  14890. }
  14891. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  14892. }
  14893. function generateExtensions( extensions, parameters, rendererExtensions ) {
  14894. extensions = extensions || {};
  14895. var chunks = [
  14896. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14897. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  14898. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  14899. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  14900. ];
  14901. return chunks.filter( filterEmptyLine ).join( '\n' );
  14902. }
  14903. function generateDefines( defines ) {
  14904. var chunks = [];
  14905. for ( var name in defines ) {
  14906. var value = defines[ name ];
  14907. if ( value === false ) continue;
  14908. chunks.push( '#define ' + name + ' ' + value );
  14909. }
  14910. return chunks.join( '\n' );
  14911. }
  14912. function fetchAttributeLocations( gl, program, identifiers ) {
  14913. var attributes = {};
  14914. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  14915. for ( var i = 0; i < n; i ++ ) {
  14916. var info = gl.getActiveAttrib( program, i );
  14917. var name = info.name;
  14918. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  14919. attributes[ name ] = gl.getAttribLocation( program, name );
  14920. }
  14921. return attributes;
  14922. }
  14923. function filterEmptyLine( string ) {
  14924. return string !== '';
  14925. }
  14926. function replaceLightNums( string, parameters ) {
  14927. return string
  14928. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  14929. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  14930. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  14931. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  14932. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  14933. }
  14934. function parseIncludes( string ) {
  14935. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  14936. function replace( match, include ) {
  14937. var replace = ShaderChunk[ include ];
  14938. if ( replace === undefined ) {
  14939. throw new Error( 'Can not resolve #include <' + include + '>' );
  14940. }
  14941. return parseIncludes( replace );
  14942. }
  14943. return string.replace( pattern, replace );
  14944. }
  14945. function unrollLoops( string ) {
  14946. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  14947. function replace( match, start, end, snippet ) {
  14948. var unroll = '';
  14949. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  14950. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  14951. }
  14952. return unroll;
  14953. }
  14954. return string.replace( pattern, replace );
  14955. }
  14956. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  14957. var gl = renderer.context;
  14958. var defines = material.defines;
  14959. var vertexShader = shader.vertexShader;
  14960. var fragmentShader = shader.fragmentShader;
  14961. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14962. if ( parameters.shadowMapType === PCFShadowMap ) {
  14963. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14964. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14965. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14966. }
  14967. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14968. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14969. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14970. if ( parameters.envMap ) {
  14971. switch ( material.envMap.mapping ) {
  14972. case CubeReflectionMapping:
  14973. case CubeRefractionMapping:
  14974. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14975. break;
  14976. case CubeUVReflectionMapping:
  14977. case CubeUVRefractionMapping:
  14978. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14979. break;
  14980. case EquirectangularReflectionMapping:
  14981. case EquirectangularRefractionMapping:
  14982. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14983. break;
  14984. case SphericalReflectionMapping:
  14985. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14986. break;
  14987. }
  14988. switch ( material.envMap.mapping ) {
  14989. case CubeRefractionMapping:
  14990. case EquirectangularRefractionMapping:
  14991. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14992. break;
  14993. }
  14994. switch ( material.combine ) {
  14995. case MultiplyOperation:
  14996. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14997. break;
  14998. case MixOperation:
  14999. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  15000. break;
  15001. case AddOperation:
  15002. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  15003. break;
  15004. }
  15005. }
  15006. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  15007. // console.log( 'building new program ' );
  15008. //
  15009. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  15010. var customDefines = generateDefines( defines );
  15011. //
  15012. var program = gl.createProgram();
  15013. var prefixVertex, prefixFragment;
  15014. if ( material.isRawShaderMaterial ) {
  15015. prefixVertex = [
  15016. customDefines,
  15017. '\n'
  15018. ].filter( filterEmptyLine ).join( '\n' );
  15019. prefixFragment = [
  15020. customExtensions,
  15021. customDefines,
  15022. '\n'
  15023. ].filter( filterEmptyLine ).join( '\n' );
  15024. } else {
  15025. prefixVertex = [
  15026. 'precision ' + parameters.precision + ' float;',
  15027. 'precision ' + parameters.precision + ' int;',
  15028. '#define SHADER_NAME ' + shader.name,
  15029. customDefines,
  15030. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  15031. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15032. '#define MAX_BONES ' + parameters.maxBones,
  15033. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15034. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15035. parameters.map ? '#define USE_MAP' : '',
  15036. parameters.envMap ? '#define USE_ENVMAP' : '',
  15037. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15038. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15039. parameters.aoMap ? '#define USE_AOMAP' : '',
  15040. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15041. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15042. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15043. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  15044. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15045. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  15046. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  15047. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15048. parameters.vertexColors ? '#define USE_COLOR' : '',
  15049. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15050. parameters.skinning ? '#define USE_SKINNING' : '',
  15051. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  15052. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  15053. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  15054. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15055. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15056. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  15057. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15058. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15059. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  15060. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15061. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15062. 'uniform mat4 modelMatrix;',
  15063. 'uniform mat4 modelViewMatrix;',
  15064. 'uniform mat4 projectionMatrix;',
  15065. 'uniform mat4 viewMatrix;',
  15066. 'uniform mat3 normalMatrix;',
  15067. 'uniform vec3 cameraPosition;',
  15068. 'attribute vec3 position;',
  15069. 'attribute vec3 normal;',
  15070. 'attribute vec2 uv;',
  15071. '#ifdef USE_COLOR',
  15072. ' attribute vec3 color;',
  15073. '#endif',
  15074. '#ifdef USE_MORPHTARGETS',
  15075. ' attribute vec3 morphTarget0;',
  15076. ' attribute vec3 morphTarget1;',
  15077. ' attribute vec3 morphTarget2;',
  15078. ' attribute vec3 morphTarget3;',
  15079. ' #ifdef USE_MORPHNORMALS',
  15080. ' attribute vec3 morphNormal0;',
  15081. ' attribute vec3 morphNormal1;',
  15082. ' attribute vec3 morphNormal2;',
  15083. ' attribute vec3 morphNormal3;',
  15084. ' #else',
  15085. ' attribute vec3 morphTarget4;',
  15086. ' attribute vec3 morphTarget5;',
  15087. ' attribute vec3 morphTarget6;',
  15088. ' attribute vec3 morphTarget7;',
  15089. ' #endif',
  15090. '#endif',
  15091. '#ifdef USE_SKINNING',
  15092. ' attribute vec4 skinIndex;',
  15093. ' attribute vec4 skinWeight;',
  15094. '#endif',
  15095. '\n'
  15096. ].filter( filterEmptyLine ).join( '\n' );
  15097. prefixFragment = [
  15098. customExtensions,
  15099. 'precision ' + parameters.precision + ' float;',
  15100. 'precision ' + parameters.precision + ' int;',
  15101. '#define SHADER_NAME ' + shader.name,
  15102. customDefines,
  15103. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  15104. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15105. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15106. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15107. parameters.map ? '#define USE_MAP' : '',
  15108. parameters.envMap ? '#define USE_ENVMAP' : '',
  15109. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  15110. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15111. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  15112. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15113. parameters.aoMap ? '#define USE_AOMAP' : '',
  15114. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15115. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15116. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15117. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15118. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  15119. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  15120. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15121. parameters.vertexColors ? '#define USE_COLOR' : '',
  15122. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  15123. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15124. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15125. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15126. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  15127. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  15128. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15129. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15130. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  15131. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  15132. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15133. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15134. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  15135. 'uniform mat4 viewMatrix;',
  15136. 'uniform vec3 cameraPosition;',
  15137. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  15138. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  15139. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  15140. parameters.dithering ? '#define DITHERING' : '',
  15141. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  15142. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  15143. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  15144. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  15145. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  15146. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  15147. '\n'
  15148. ].filter( filterEmptyLine ).join( '\n' );
  15149. }
  15150. vertexShader = parseIncludes( vertexShader );
  15151. vertexShader = replaceLightNums( vertexShader, parameters );
  15152. fragmentShader = parseIncludes( fragmentShader );
  15153. fragmentShader = replaceLightNums( fragmentShader, parameters );
  15154. if ( ! material.isShaderMaterial ) {
  15155. vertexShader = unrollLoops( vertexShader );
  15156. fragmentShader = unrollLoops( fragmentShader );
  15157. }
  15158. var vertexGlsl = prefixVertex + vertexShader;
  15159. var fragmentGlsl = prefixFragment + fragmentShader;
  15160. // console.log( '*VERTEX*', vertexGlsl );
  15161. // console.log( '*FRAGMENT*', fragmentGlsl );
  15162. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  15163. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  15164. gl.attachShader( program, glVertexShader );
  15165. gl.attachShader( program, glFragmentShader );
  15166. // Force a particular attribute to index 0.
  15167. if ( material.index0AttributeName !== undefined ) {
  15168. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  15169. } else if ( parameters.morphTargets === true ) {
  15170. // programs with morphTargets displace position out of attribute 0
  15171. gl.bindAttribLocation( program, 0, 'position' );
  15172. }
  15173. gl.linkProgram( program );
  15174. var programLog = gl.getProgramInfoLog( program );
  15175. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  15176. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  15177. var runnable = true;
  15178. var haveDiagnostics = true;
  15179. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  15180. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  15181. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  15182. runnable = false;
  15183. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  15184. } else if ( programLog !== '' ) {
  15185. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  15186. } else if ( vertexLog === '' || fragmentLog === '' ) {
  15187. haveDiagnostics = false;
  15188. }
  15189. if ( haveDiagnostics ) {
  15190. this.diagnostics = {
  15191. runnable: runnable,
  15192. material: material,
  15193. programLog: programLog,
  15194. vertexShader: {
  15195. log: vertexLog,
  15196. prefix: prefixVertex
  15197. },
  15198. fragmentShader: {
  15199. log: fragmentLog,
  15200. prefix: prefixFragment
  15201. }
  15202. };
  15203. }
  15204. // clean up
  15205. gl.deleteShader( glVertexShader );
  15206. gl.deleteShader( glFragmentShader );
  15207. // set up caching for uniform locations
  15208. var cachedUniforms;
  15209. this.getUniforms = function () {
  15210. if ( cachedUniforms === undefined ) {
  15211. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  15212. }
  15213. return cachedUniforms;
  15214. };
  15215. // set up caching for attribute locations
  15216. var cachedAttributes;
  15217. this.getAttributes = function () {
  15218. if ( cachedAttributes === undefined ) {
  15219. cachedAttributes = fetchAttributeLocations( gl, program );
  15220. }
  15221. return cachedAttributes;
  15222. };
  15223. // free resource
  15224. this.destroy = function() {
  15225. gl.deleteProgram( program );
  15226. this.program = undefined;
  15227. };
  15228. // DEPRECATED
  15229. Object.defineProperties( this, {
  15230. uniforms: {
  15231. get: function() {
  15232. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  15233. return this.getUniforms();
  15234. }
  15235. },
  15236. attributes: {
  15237. get: function() {
  15238. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  15239. return this.getAttributes();
  15240. }
  15241. }
  15242. } );
  15243. //
  15244. this.id = programIdCount ++;
  15245. this.code = code;
  15246. this.usedTimes = 1;
  15247. this.program = program;
  15248. this.vertexShader = glVertexShader;
  15249. this.fragmentShader = glFragmentShader;
  15250. return this;
  15251. }
  15252. /**
  15253. * @author mrdoob / http://mrdoob.com/
  15254. */
  15255. function WebGLPrograms( renderer, extensions, capabilities ) {
  15256. var programs = [];
  15257. var shaderIDs = {
  15258. MeshDepthMaterial: 'depth',
  15259. MeshDistanceMaterial: 'distanceRGBA',
  15260. MeshNormalMaterial: 'normal',
  15261. MeshBasicMaterial: 'basic',
  15262. MeshLambertMaterial: 'lambert',
  15263. MeshPhongMaterial: 'phong',
  15264. MeshToonMaterial: 'phong',
  15265. MeshStandardMaterial: 'physical',
  15266. MeshPhysicalMaterial: 'physical',
  15267. LineBasicMaterial: 'basic',
  15268. LineDashedMaterial: 'dashed',
  15269. PointsMaterial: 'points',
  15270. ShadowMaterial: 'shadow'
  15271. };
  15272. var parameterNames = [
  15273. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  15274. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  15275. "roughnessMap", "metalnessMap", "gradientMap",
  15276. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  15277. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  15278. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  15279. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  15280. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  15281. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  15282. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  15283. ];
  15284. function allocateBones( object ) {
  15285. var skeleton = object.skeleton;
  15286. var bones = skeleton.bones;
  15287. if ( capabilities.floatVertexTextures ) {
  15288. return 1024;
  15289. } else {
  15290. // default for when object is not specified
  15291. // ( for example when prebuilding shader to be used with multiple objects )
  15292. //
  15293. // - leave some extra space for other uniforms
  15294. // - limit here is ANGLE's 254 max uniform vectors
  15295. // (up to 54 should be safe)
  15296. var nVertexUniforms = capabilities.maxVertexUniforms;
  15297. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15298. var maxBones = Math.min( nVertexMatrices, bones.length );
  15299. if ( maxBones < bones.length ) {
  15300. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  15301. return 0;
  15302. }
  15303. return maxBones;
  15304. }
  15305. }
  15306. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  15307. var encoding;
  15308. if ( ! map ) {
  15309. encoding = LinearEncoding;
  15310. } else if ( map.isTexture ) {
  15311. encoding = map.encoding;
  15312. } else if ( map.isWebGLRenderTarget ) {
  15313. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  15314. encoding = map.texture.encoding;
  15315. }
  15316. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  15317. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  15318. encoding = GammaEncoding;
  15319. }
  15320. return encoding;
  15321. }
  15322. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  15323. var shaderID = shaderIDs[ material.type ];
  15324. // heuristics to create shader parameters according to lights in the scene
  15325. // (not to blow over maxLights budget)
  15326. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  15327. var precision = capabilities.precision;
  15328. if ( material.precision !== null ) {
  15329. precision = capabilities.getMaxPrecision( material.precision );
  15330. if ( precision !== material.precision ) {
  15331. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  15332. }
  15333. }
  15334. var currentRenderTarget = renderer.getRenderTarget();
  15335. var parameters = {
  15336. shaderID: shaderID,
  15337. precision: precision,
  15338. supportsVertexTextures: capabilities.vertexTextures,
  15339. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  15340. map: !! material.map,
  15341. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  15342. envMap: !! material.envMap,
  15343. envMapMode: material.envMap && material.envMap.mapping,
  15344. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  15345. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  15346. lightMap: !! material.lightMap,
  15347. aoMap: !! material.aoMap,
  15348. emissiveMap: !! material.emissiveMap,
  15349. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  15350. bumpMap: !! material.bumpMap,
  15351. normalMap: !! material.normalMap,
  15352. displacementMap: !! material.displacementMap,
  15353. roughnessMap: !! material.roughnessMap,
  15354. metalnessMap: !! material.metalnessMap,
  15355. specularMap: !! material.specularMap,
  15356. alphaMap: !! material.alphaMap,
  15357. gradientMap: !! material.gradientMap,
  15358. combine: material.combine,
  15359. vertexColors: material.vertexColors,
  15360. fog: !! fog,
  15361. useFog: material.fog,
  15362. fogExp: ( fog && fog.isFogExp2 ),
  15363. flatShading: material.flatShading,
  15364. sizeAttenuation: material.sizeAttenuation,
  15365. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  15366. skinning: material.skinning && maxBones > 0,
  15367. maxBones: maxBones,
  15368. useVertexTexture: capabilities.floatVertexTextures,
  15369. morphTargets: material.morphTargets,
  15370. morphNormals: material.morphNormals,
  15371. maxMorphTargets: renderer.maxMorphTargets,
  15372. maxMorphNormals: renderer.maxMorphNormals,
  15373. numDirLights: lights.directional.length,
  15374. numPointLights: lights.point.length,
  15375. numSpotLights: lights.spot.length,
  15376. numRectAreaLights: lights.rectArea.length,
  15377. numHemiLights: lights.hemi.length,
  15378. numClippingPlanes: nClipPlanes,
  15379. numClipIntersection: nClipIntersection,
  15380. dithering: material.dithering,
  15381. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  15382. shadowMapType: renderer.shadowMap.type,
  15383. toneMapping: renderer.toneMapping,
  15384. physicallyCorrectLights: renderer.physicallyCorrectLights,
  15385. premultipliedAlpha: material.premultipliedAlpha,
  15386. alphaTest: material.alphaTest,
  15387. doubleSided: material.side === DoubleSide,
  15388. flipSided: material.side === BackSide,
  15389. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  15390. };
  15391. return parameters;
  15392. };
  15393. this.getProgramCode = function ( material, parameters ) {
  15394. var array = [];
  15395. if ( parameters.shaderID ) {
  15396. array.push( parameters.shaderID );
  15397. } else {
  15398. array.push( material.fragmentShader );
  15399. array.push( material.vertexShader );
  15400. }
  15401. if ( material.defines !== undefined ) {
  15402. for ( var name in material.defines ) {
  15403. array.push( name );
  15404. array.push( material.defines[ name ] );
  15405. }
  15406. }
  15407. for ( var i = 0; i < parameterNames.length; i ++ ) {
  15408. array.push( parameters[ parameterNames[ i ] ] );
  15409. }
  15410. array.push( material.onBeforeCompile.toString() );
  15411. array.push( renderer.gammaOutput );
  15412. return array.join();
  15413. };
  15414. this.acquireProgram = function ( material, shader, parameters, code ) {
  15415. var program;
  15416. // Check if code has been already compiled
  15417. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  15418. var programInfo = programs[ p ];
  15419. if ( programInfo.code === code ) {
  15420. program = programInfo;
  15421. ++ program.usedTimes;
  15422. break;
  15423. }
  15424. }
  15425. if ( program === undefined ) {
  15426. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  15427. programs.push( program );
  15428. }
  15429. return program;
  15430. };
  15431. this.releaseProgram = function ( program ) {
  15432. if ( -- program.usedTimes === 0 ) {
  15433. // Remove from unordered set
  15434. var i = programs.indexOf( program );
  15435. programs[ i ] = programs[ programs.length - 1 ];
  15436. programs.pop();
  15437. // Free WebGL resources
  15438. program.destroy();
  15439. }
  15440. };
  15441. // Exposed for resource monitoring & error feedback via renderer.info:
  15442. this.programs = programs;
  15443. }
  15444. /**
  15445. * @author mrdoob / http://mrdoob.com/
  15446. */
  15447. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, infoMemory ) {
  15448. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  15449. //
  15450. function clampToMaxSize( image, maxSize ) {
  15451. if ( image.width > maxSize || image.height > maxSize ) {
  15452. // Warning: Scaling through the canvas will only work with images that use
  15453. // premultiplied alpha.
  15454. var scale = maxSize / Math.max( image.width, image.height );
  15455. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15456. canvas.width = Math.floor( image.width * scale );
  15457. canvas.height = Math.floor( image.height * scale );
  15458. var context = canvas.getContext( '2d' );
  15459. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  15460. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  15461. return canvas;
  15462. }
  15463. return image;
  15464. }
  15465. function isPowerOfTwo( image ) {
  15466. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  15467. }
  15468. function makePowerOfTwo( image ) {
  15469. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  15470. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15471. canvas.width = _Math.nearestPowerOfTwo( image.width );
  15472. canvas.height = _Math.nearestPowerOfTwo( image.height );
  15473. var context = canvas.getContext( '2d' );
  15474. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  15475. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  15476. return canvas;
  15477. }
  15478. return image;
  15479. }
  15480. function textureNeedsPowerOfTwo( texture ) {
  15481. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  15482. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  15483. }
  15484. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  15485. return texture.generateMipmaps && isPowerOfTwo &&
  15486. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  15487. }
  15488. // Fallback filters for non-power-of-2 textures
  15489. function filterFallback( f ) {
  15490. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  15491. return _gl.NEAREST;
  15492. }
  15493. return _gl.LINEAR;
  15494. }
  15495. //
  15496. function onTextureDispose( event ) {
  15497. var texture = event.target;
  15498. texture.removeEventListener( 'dispose', onTextureDispose );
  15499. deallocateTexture( texture );
  15500. infoMemory.textures --;
  15501. }
  15502. function onRenderTargetDispose( event ) {
  15503. var renderTarget = event.target;
  15504. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  15505. deallocateRenderTarget( renderTarget );
  15506. infoMemory.textures --;
  15507. }
  15508. //
  15509. function deallocateTexture( texture ) {
  15510. var textureProperties = properties.get( texture );
  15511. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  15512. // cube texture
  15513. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  15514. } else {
  15515. // 2D texture
  15516. if ( textureProperties.__webglInit === undefined ) return;
  15517. _gl.deleteTexture( textureProperties.__webglTexture );
  15518. }
  15519. // remove all webgl properties
  15520. properties.remove( texture );
  15521. }
  15522. function deallocateRenderTarget( renderTarget ) {
  15523. var renderTargetProperties = properties.get( renderTarget );
  15524. var textureProperties = properties.get( renderTarget.texture );
  15525. if ( ! renderTarget ) return;
  15526. if ( textureProperties.__webglTexture !== undefined ) {
  15527. _gl.deleteTexture( textureProperties.__webglTexture );
  15528. }
  15529. if ( renderTarget.depthTexture ) {
  15530. renderTarget.depthTexture.dispose();
  15531. }
  15532. if ( renderTarget.isWebGLRenderTargetCube ) {
  15533. for ( var i = 0; i < 6; i ++ ) {
  15534. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15535. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15536. }
  15537. } else {
  15538. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15539. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15540. }
  15541. properties.remove( renderTarget.texture );
  15542. properties.remove( renderTarget );
  15543. }
  15544. //
  15545. function setTexture2D( texture, slot ) {
  15546. var textureProperties = properties.get( texture );
  15547. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15548. var image = texture.image;
  15549. if ( image === undefined ) {
  15550. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  15551. } else if ( image.complete === false ) {
  15552. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  15553. } else {
  15554. uploadTexture( textureProperties, texture, slot );
  15555. return;
  15556. }
  15557. }
  15558. state.activeTexture( _gl.TEXTURE0 + slot );
  15559. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15560. }
  15561. function setTextureCube( texture, slot ) {
  15562. var textureProperties = properties.get( texture );
  15563. if ( texture.image.length === 6 ) {
  15564. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15565. if ( ! textureProperties.__image__webglTextureCube ) {
  15566. texture.addEventListener( 'dispose', onTextureDispose );
  15567. textureProperties.__image__webglTextureCube = _gl.createTexture();
  15568. infoMemory.textures ++;
  15569. }
  15570. state.activeTexture( _gl.TEXTURE0 + slot );
  15571. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15572. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15573. var isCompressed = ( texture && texture.isCompressedTexture );
  15574. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15575. var cubeImage = [];
  15576. for ( var i = 0; i < 6; i ++ ) {
  15577. if ( ! isCompressed && ! isDataTexture ) {
  15578. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  15579. } else {
  15580. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15581. }
  15582. }
  15583. var image = cubeImage[ 0 ],
  15584. isPowerOfTwoImage = isPowerOfTwo( image ),
  15585. glFormat = utils.convert( texture.format ),
  15586. glType = utils.convert( texture.type );
  15587. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  15588. for ( var i = 0; i < 6; i ++ ) {
  15589. if ( ! isCompressed ) {
  15590. if ( isDataTexture ) {
  15591. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15592. } else {
  15593. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15594. }
  15595. } else {
  15596. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15597. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15598. mipmap = mipmaps[ j ];
  15599. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15600. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15601. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15602. } else {
  15603. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15604. }
  15605. } else {
  15606. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15607. }
  15608. }
  15609. }
  15610. }
  15611. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  15612. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15613. }
  15614. textureProperties.__version = texture.version;
  15615. if ( texture.onUpdate ) texture.onUpdate( texture );
  15616. } else {
  15617. state.activeTexture( _gl.TEXTURE0 + slot );
  15618. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15619. }
  15620. }
  15621. }
  15622. function setTextureCubeDynamic( texture, slot ) {
  15623. state.activeTexture( _gl.TEXTURE0 + slot );
  15624. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  15625. }
  15626. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  15627. var extension;
  15628. if ( isPowerOfTwoImage ) {
  15629. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
  15630. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );
  15631. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
  15632. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );
  15633. } else {
  15634. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15635. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15636. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  15637. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  15638. }
  15639. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15640. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15641. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  15642. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  15643. }
  15644. }
  15645. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15646. if ( extension ) {
  15647. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  15648. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  15649. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  15650. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  15651. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  15652. }
  15653. }
  15654. }
  15655. function uploadTexture( textureProperties, texture, slot ) {
  15656. if ( textureProperties.__webglInit === undefined ) {
  15657. textureProperties.__webglInit = true;
  15658. texture.addEventListener( 'dispose', onTextureDispose );
  15659. textureProperties.__webglTexture = _gl.createTexture();
  15660. infoMemory.textures ++;
  15661. }
  15662. state.activeTexture( _gl.TEXTURE0 + slot );
  15663. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15664. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15665. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15666. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15667. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  15668. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  15669. image = makePowerOfTwo( image );
  15670. }
  15671. var isPowerOfTwoImage = isPowerOfTwo( image ),
  15672. glFormat = utils.convert( texture.format ),
  15673. glType = utils.convert( texture.type );
  15674. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  15675. var mipmap, mipmaps = texture.mipmaps;
  15676. if ( texture.isDepthTexture ) {
  15677. // populate depth texture with dummy data
  15678. var internalFormat = _gl.DEPTH_COMPONENT;
  15679. if ( texture.type === FloatType ) {
  15680. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  15681. internalFormat = _gl.DEPTH_COMPONENT32F;
  15682. } else if ( _isWebGL2 ) {
  15683. // WebGL 2.0 requires signed internalformat for glTexImage2D
  15684. internalFormat = _gl.DEPTH_COMPONENT16;
  15685. }
  15686. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  15687. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15688. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  15689. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15690. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  15691. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  15692. texture.type = UnsignedShortType;
  15693. glType = utils.convert( texture.type );
  15694. }
  15695. }
  15696. // Depth stencil textures need the DEPTH_STENCIL internal format
  15697. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15698. if ( texture.format === DepthStencilFormat ) {
  15699. internalFormat = _gl.DEPTH_STENCIL;
  15700. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15701. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  15702. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15703. if ( texture.type !== UnsignedInt248Type ) {
  15704. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  15705. texture.type = UnsignedInt248Type;
  15706. glType = utils.convert( texture.type );
  15707. }
  15708. }
  15709. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  15710. } else if ( texture.isDataTexture ) {
  15711. // use manually created mipmaps if available
  15712. // if there are no manual mipmaps
  15713. // set 0 level mipmap and then use GL to generate other mipmap levels
  15714. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  15715. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15716. mipmap = mipmaps[ i ];
  15717. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15718. }
  15719. texture.generateMipmaps = false;
  15720. } else {
  15721. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15722. }
  15723. } else if ( texture.isCompressedTexture ) {
  15724. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15725. mipmap = mipmaps[ i ];
  15726. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15727. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15728. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15729. } else {
  15730. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15731. }
  15732. } else {
  15733. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15734. }
  15735. }
  15736. } else {
  15737. // regular Texture (image, video, canvas)
  15738. // use manually created mipmaps if available
  15739. // if there are no manual mipmaps
  15740. // set 0 level mipmap and then use GL to generate other mipmap levels
  15741. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  15742. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15743. mipmap = mipmaps[ i ];
  15744. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15745. }
  15746. texture.generateMipmaps = false;
  15747. } else {
  15748. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  15749. }
  15750. }
  15751. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15752. textureProperties.__version = texture.version;
  15753. if ( texture.onUpdate ) texture.onUpdate( texture );
  15754. }
  15755. // Render targets
  15756. // Setup storage for target texture and bind it to correct framebuffer
  15757. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  15758. var glFormat = utils.convert( renderTarget.texture.format );
  15759. var glType = utils.convert( renderTarget.texture.type );
  15760. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15761. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15762. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  15763. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15764. }
  15765. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15766. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  15767. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15768. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15769. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15770. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15771. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15772. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15773. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15774. } else {
  15775. // FIXME: We don't support !depth !stencil
  15776. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15777. }
  15778. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15779. }
  15780. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15781. function setupDepthTexture( framebuffer, renderTarget ) {
  15782. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  15783. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15784. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15785. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15786. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15787. }
  15788. // upload an empty depth texture with framebuffer size
  15789. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  15790. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15791. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15792. renderTarget.depthTexture.image.width = renderTarget.width;
  15793. renderTarget.depthTexture.image.height = renderTarget.height;
  15794. renderTarget.depthTexture.needsUpdate = true;
  15795. }
  15796. setTexture2D( renderTarget.depthTexture, 0 );
  15797. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15798. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15799. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15800. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15801. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15802. } else {
  15803. throw new Error( 'Unknown depthTexture format' );
  15804. }
  15805. }
  15806. // Setup GL resources for a non-texture depth buffer
  15807. function setupDepthRenderbuffer( renderTarget ) {
  15808. var renderTargetProperties = properties.get( renderTarget );
  15809. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15810. if ( renderTarget.depthTexture ) {
  15811. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15812. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15813. } else {
  15814. if ( isCube ) {
  15815. renderTargetProperties.__webglDepthbuffer = [];
  15816. for ( var i = 0; i < 6; i ++ ) {
  15817. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15818. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15819. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  15820. }
  15821. } else {
  15822. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15823. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15824. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  15825. }
  15826. }
  15827. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15828. }
  15829. // Set up GL resources for the render target
  15830. function setupRenderTarget( renderTarget ) {
  15831. var renderTargetProperties = properties.get( renderTarget );
  15832. var textureProperties = properties.get( renderTarget.texture );
  15833. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15834. textureProperties.__webglTexture = _gl.createTexture();
  15835. infoMemory.textures ++;
  15836. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15837. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  15838. // Setup framebuffer
  15839. if ( isCube ) {
  15840. renderTargetProperties.__webglFramebuffer = [];
  15841. for ( var i = 0; i < 6; i ++ ) {
  15842. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15843. }
  15844. } else {
  15845. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15846. }
  15847. // Setup color buffer
  15848. if ( isCube ) {
  15849. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15850. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  15851. for ( var i = 0; i < 6; i ++ ) {
  15852. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15853. }
  15854. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15855. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15856. } else {
  15857. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15858. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  15859. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  15860. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15861. state.bindTexture( _gl.TEXTURE_2D, null );
  15862. }
  15863. // Setup depth and stencil buffers
  15864. if ( renderTarget.depthBuffer ) {
  15865. setupDepthRenderbuffer( renderTarget );
  15866. }
  15867. }
  15868. function updateRenderTargetMipmap( renderTarget ) {
  15869. var texture = renderTarget.texture;
  15870. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  15871. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  15872. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15873. var webglTexture = properties.get( texture ).__webglTexture;
  15874. state.bindTexture( target, webglTexture );
  15875. _gl.generateMipmap( target );
  15876. state.bindTexture( target, null );
  15877. }
  15878. }
  15879. this.setTexture2D = setTexture2D;
  15880. this.setTextureCube = setTextureCube;
  15881. this.setTextureCubeDynamic = setTextureCubeDynamic;
  15882. this.setupRenderTarget = setupRenderTarget;
  15883. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15884. }
  15885. /**
  15886. * @author fordacious / fordacious.github.io
  15887. */
  15888. function WebGLProperties() {
  15889. var properties = {};
  15890. function get( object ) {
  15891. var uuid = object.uuid;
  15892. var map = properties[ uuid ];
  15893. if ( map === undefined ) {
  15894. map = {};
  15895. properties[ uuid ] = map;
  15896. }
  15897. return map;
  15898. }
  15899. function remove( object ) {
  15900. delete properties[ object.uuid ];
  15901. }
  15902. function clear() {
  15903. properties = {};
  15904. }
  15905. return {
  15906. get: get,
  15907. remove: remove,
  15908. clear: clear
  15909. };
  15910. }
  15911. /**
  15912. * @author mrdoob / http://mrdoob.com/
  15913. */
  15914. function WebGLState( gl, extensions, utils ) {
  15915. function ColorBuffer() {
  15916. var locked = false;
  15917. var color = new Vector4();
  15918. var currentColorMask = null;
  15919. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  15920. return {
  15921. setMask: function ( colorMask ) {
  15922. if ( currentColorMask !== colorMask && ! locked ) {
  15923. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15924. currentColorMask = colorMask;
  15925. }
  15926. },
  15927. setLocked: function ( lock ) {
  15928. locked = lock;
  15929. },
  15930. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15931. if ( premultipliedAlpha === true ) {
  15932. r *= a; g *= a; b *= a;
  15933. }
  15934. color.set( r, g, b, a );
  15935. if ( currentColorClear.equals( color ) === false ) {
  15936. gl.clearColor( r, g, b, a );
  15937. currentColorClear.copy( color );
  15938. }
  15939. },
  15940. reset: function () {
  15941. locked = false;
  15942. currentColorMask = null;
  15943. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  15944. }
  15945. };
  15946. }
  15947. function DepthBuffer() {
  15948. var locked = false;
  15949. var currentDepthMask = null;
  15950. var currentDepthFunc = null;
  15951. var currentDepthClear = null;
  15952. return {
  15953. setTest: function ( depthTest ) {
  15954. if ( depthTest ) {
  15955. enable( gl.DEPTH_TEST );
  15956. } else {
  15957. disable( gl.DEPTH_TEST );
  15958. }
  15959. },
  15960. setMask: function ( depthMask ) {
  15961. if ( currentDepthMask !== depthMask && ! locked ) {
  15962. gl.depthMask( depthMask );
  15963. currentDepthMask = depthMask;
  15964. }
  15965. },
  15966. setFunc: function ( depthFunc ) {
  15967. if ( currentDepthFunc !== depthFunc ) {
  15968. if ( depthFunc ) {
  15969. switch ( depthFunc ) {
  15970. case NeverDepth:
  15971. gl.depthFunc( gl.NEVER );
  15972. break;
  15973. case AlwaysDepth:
  15974. gl.depthFunc( gl.ALWAYS );
  15975. break;
  15976. case LessDepth:
  15977. gl.depthFunc( gl.LESS );
  15978. break;
  15979. case LessEqualDepth:
  15980. gl.depthFunc( gl.LEQUAL );
  15981. break;
  15982. case EqualDepth:
  15983. gl.depthFunc( gl.EQUAL );
  15984. break;
  15985. case GreaterEqualDepth:
  15986. gl.depthFunc( gl.GEQUAL );
  15987. break;
  15988. case GreaterDepth:
  15989. gl.depthFunc( gl.GREATER );
  15990. break;
  15991. case NotEqualDepth:
  15992. gl.depthFunc( gl.NOTEQUAL );
  15993. break;
  15994. default:
  15995. gl.depthFunc( gl.LEQUAL );
  15996. }
  15997. } else {
  15998. gl.depthFunc( gl.LEQUAL );
  15999. }
  16000. currentDepthFunc = depthFunc;
  16001. }
  16002. },
  16003. setLocked: function ( lock ) {
  16004. locked = lock;
  16005. },
  16006. setClear: function ( depth ) {
  16007. if ( currentDepthClear !== depth ) {
  16008. gl.clearDepth( depth );
  16009. currentDepthClear = depth;
  16010. }
  16011. },
  16012. reset: function () {
  16013. locked = false;
  16014. currentDepthMask = null;
  16015. currentDepthFunc = null;
  16016. currentDepthClear = null;
  16017. }
  16018. };
  16019. }
  16020. function StencilBuffer() {
  16021. var locked = false;
  16022. var currentStencilMask = null;
  16023. var currentStencilFunc = null;
  16024. var currentStencilRef = null;
  16025. var currentStencilFuncMask = null;
  16026. var currentStencilFail = null;
  16027. var currentStencilZFail = null;
  16028. var currentStencilZPass = null;
  16029. var currentStencilClear = null;
  16030. return {
  16031. setTest: function ( stencilTest ) {
  16032. if ( stencilTest ) {
  16033. enable( gl.STENCIL_TEST );
  16034. } else {
  16035. disable( gl.STENCIL_TEST );
  16036. }
  16037. },
  16038. setMask: function ( stencilMask ) {
  16039. if ( currentStencilMask !== stencilMask && ! locked ) {
  16040. gl.stencilMask( stencilMask );
  16041. currentStencilMask = stencilMask;
  16042. }
  16043. },
  16044. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  16045. if ( currentStencilFunc !== stencilFunc ||
  16046. currentStencilRef !== stencilRef ||
  16047. currentStencilFuncMask !== stencilMask ) {
  16048. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  16049. currentStencilFunc = stencilFunc;
  16050. currentStencilRef = stencilRef;
  16051. currentStencilFuncMask = stencilMask;
  16052. }
  16053. },
  16054. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  16055. if ( currentStencilFail !== stencilFail ||
  16056. currentStencilZFail !== stencilZFail ||
  16057. currentStencilZPass !== stencilZPass ) {
  16058. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  16059. currentStencilFail = stencilFail;
  16060. currentStencilZFail = stencilZFail;
  16061. currentStencilZPass = stencilZPass;
  16062. }
  16063. },
  16064. setLocked: function ( lock ) {
  16065. locked = lock;
  16066. },
  16067. setClear: function ( stencil ) {
  16068. if ( currentStencilClear !== stencil ) {
  16069. gl.clearStencil( stencil );
  16070. currentStencilClear = stencil;
  16071. }
  16072. },
  16073. reset: function () {
  16074. locked = false;
  16075. currentStencilMask = null;
  16076. currentStencilFunc = null;
  16077. currentStencilRef = null;
  16078. currentStencilFuncMask = null;
  16079. currentStencilFail = null;
  16080. currentStencilZFail = null;
  16081. currentStencilZPass = null;
  16082. currentStencilClear = null;
  16083. }
  16084. };
  16085. }
  16086. //
  16087. var colorBuffer = new ColorBuffer();
  16088. var depthBuffer = new DepthBuffer();
  16089. var stencilBuffer = new StencilBuffer();
  16090. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16091. var newAttributes = new Uint8Array( maxVertexAttributes );
  16092. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  16093. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  16094. var capabilities = {};
  16095. var compressedTextureFormats = null;
  16096. var currentProgram = null;
  16097. var currentBlending = null;
  16098. var currentBlendEquation = null;
  16099. var currentBlendSrc = null;
  16100. var currentBlendDst = null;
  16101. var currentBlendEquationAlpha = null;
  16102. var currentBlendSrcAlpha = null;
  16103. var currentBlendDstAlpha = null;
  16104. var currentPremultipledAlpha = false;
  16105. var currentFlipSided = null;
  16106. var currentCullFace = null;
  16107. var currentLineWidth = null;
  16108. var currentPolygonOffsetFactor = null;
  16109. var currentPolygonOffsetUnits = null;
  16110. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  16111. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  16112. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  16113. var currentTextureSlot = null;
  16114. var currentBoundTextures = {};
  16115. var currentScissor = new Vector4();
  16116. var currentViewport = new Vector4();
  16117. function createTexture( type, target, count ) {
  16118. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  16119. var texture = gl.createTexture();
  16120. gl.bindTexture( type, texture );
  16121. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  16122. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  16123. for ( var i = 0; i < count; i ++ ) {
  16124. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  16125. }
  16126. return texture;
  16127. }
  16128. var emptyTextures = {};
  16129. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  16130. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  16131. // init
  16132. colorBuffer.setClear( 0, 0, 0, 1 );
  16133. depthBuffer.setClear( 1 );
  16134. stencilBuffer.setClear( 0 );
  16135. enable( gl.DEPTH_TEST );
  16136. depthBuffer.setFunc( LessEqualDepth );
  16137. setFlipSided( false );
  16138. setCullFace( CullFaceBack );
  16139. enable( gl.CULL_FACE );
  16140. enable( gl.BLEND );
  16141. setBlending( NormalBlending );
  16142. //
  16143. function initAttributes() {
  16144. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  16145. newAttributes[ i ] = 0;
  16146. }
  16147. }
  16148. function enableAttribute( attribute ) {
  16149. newAttributes[ attribute ] = 1;
  16150. if ( enabledAttributes[ attribute ] === 0 ) {
  16151. gl.enableVertexAttribArray( attribute );
  16152. enabledAttributes[ attribute ] = 1;
  16153. }
  16154. if ( attributeDivisors[ attribute ] !== 0 ) {
  16155. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16156. extension.vertexAttribDivisorANGLE( attribute, 0 );
  16157. attributeDivisors[ attribute ] = 0;
  16158. }
  16159. }
  16160. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  16161. newAttributes[ attribute ] = 1;
  16162. if ( enabledAttributes[ attribute ] === 0 ) {
  16163. gl.enableVertexAttribArray( attribute );
  16164. enabledAttributes[ attribute ] = 1;
  16165. }
  16166. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  16167. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16168. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  16169. attributeDivisors[ attribute ] = meshPerAttribute;
  16170. }
  16171. }
  16172. function disableUnusedAttributes() {
  16173. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  16174. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  16175. gl.disableVertexAttribArray( i );
  16176. enabledAttributes[ i ] = 0;
  16177. }
  16178. }
  16179. }
  16180. function enable( id ) {
  16181. if ( capabilities[ id ] !== true ) {
  16182. gl.enable( id );
  16183. capabilities[ id ] = true;
  16184. }
  16185. }
  16186. function disable( id ) {
  16187. if ( capabilities[ id ] !== false ) {
  16188. gl.disable( id );
  16189. capabilities[ id ] = false;
  16190. }
  16191. }
  16192. function getCompressedTextureFormats() {
  16193. if ( compressedTextureFormats === null ) {
  16194. compressedTextureFormats = [];
  16195. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  16196. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  16197. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  16198. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  16199. for ( var i = 0; i < formats.length; i ++ ) {
  16200. compressedTextureFormats.push( formats[ i ] );
  16201. }
  16202. }
  16203. }
  16204. return compressedTextureFormats;
  16205. }
  16206. function useProgram( program ) {
  16207. if ( currentProgram !== program ) {
  16208. gl.useProgram( program );
  16209. currentProgram = program;
  16210. return true;
  16211. }
  16212. return false;
  16213. }
  16214. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  16215. if ( blending !== NoBlending ) {
  16216. enable( gl.BLEND );
  16217. } else {
  16218. disable( gl.BLEND );
  16219. }
  16220. if ( blending !== CustomBlending ) {
  16221. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  16222. switch ( blending ) {
  16223. case AdditiveBlending:
  16224. if ( premultipliedAlpha ) {
  16225. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16226. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  16227. } else {
  16228. gl.blendEquation( gl.FUNC_ADD );
  16229. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  16230. }
  16231. break;
  16232. case SubtractiveBlending:
  16233. if ( premultipliedAlpha ) {
  16234. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16235. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  16236. } else {
  16237. gl.blendEquation( gl.FUNC_ADD );
  16238. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  16239. }
  16240. break;
  16241. case MultiplyBlending:
  16242. if ( premultipliedAlpha ) {
  16243. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16244. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  16245. } else {
  16246. gl.blendEquation( gl.FUNC_ADD );
  16247. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  16248. }
  16249. break;
  16250. default:
  16251. if ( premultipliedAlpha ) {
  16252. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16253. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  16254. } else {
  16255. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16256. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  16257. }
  16258. }
  16259. }
  16260. currentBlendEquation = null;
  16261. currentBlendSrc = null;
  16262. currentBlendDst = null;
  16263. currentBlendEquationAlpha = null;
  16264. currentBlendSrcAlpha = null;
  16265. currentBlendDstAlpha = null;
  16266. } else {
  16267. blendEquationAlpha = blendEquationAlpha || blendEquation;
  16268. blendSrcAlpha = blendSrcAlpha || blendSrc;
  16269. blendDstAlpha = blendDstAlpha || blendDst;
  16270. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  16271. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  16272. currentBlendEquation = blendEquation;
  16273. currentBlendEquationAlpha = blendEquationAlpha;
  16274. }
  16275. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  16276. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  16277. currentBlendSrc = blendSrc;
  16278. currentBlendDst = blendDst;
  16279. currentBlendSrcAlpha = blendSrcAlpha;
  16280. currentBlendDstAlpha = blendDstAlpha;
  16281. }
  16282. }
  16283. currentBlending = blending;
  16284. currentPremultipledAlpha = premultipliedAlpha;
  16285. }
  16286. function setMaterial( material ) {
  16287. material.side === DoubleSide
  16288. ? disable( gl.CULL_FACE )
  16289. : enable( gl.CULL_FACE );
  16290. setFlipSided( material.side === BackSide );
  16291. material.transparent === true
  16292. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  16293. : setBlending( NoBlending );
  16294. depthBuffer.setFunc( material.depthFunc );
  16295. depthBuffer.setTest( material.depthTest );
  16296. depthBuffer.setMask( material.depthWrite );
  16297. colorBuffer.setMask( material.colorWrite );
  16298. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16299. }
  16300. //
  16301. function setFlipSided( flipSided ) {
  16302. if ( currentFlipSided !== flipSided ) {
  16303. if ( flipSided ) {
  16304. gl.frontFace( gl.CW );
  16305. } else {
  16306. gl.frontFace( gl.CCW );
  16307. }
  16308. currentFlipSided = flipSided;
  16309. }
  16310. }
  16311. function setCullFace( cullFace ) {
  16312. if ( cullFace !== CullFaceNone ) {
  16313. enable( gl.CULL_FACE );
  16314. if ( cullFace !== currentCullFace ) {
  16315. if ( cullFace === CullFaceBack ) {
  16316. gl.cullFace( gl.BACK );
  16317. } else if ( cullFace === CullFaceFront ) {
  16318. gl.cullFace( gl.FRONT );
  16319. } else {
  16320. gl.cullFace( gl.FRONT_AND_BACK );
  16321. }
  16322. }
  16323. } else {
  16324. disable( gl.CULL_FACE );
  16325. }
  16326. currentCullFace = cullFace;
  16327. }
  16328. function setLineWidth( width ) {
  16329. if ( width !== currentLineWidth ) {
  16330. if ( lineWidthAvailable ) gl.lineWidth( width );
  16331. currentLineWidth = width;
  16332. }
  16333. }
  16334. function setPolygonOffset( polygonOffset, factor, units ) {
  16335. if ( polygonOffset ) {
  16336. enable( gl.POLYGON_OFFSET_FILL );
  16337. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  16338. gl.polygonOffset( factor, units );
  16339. currentPolygonOffsetFactor = factor;
  16340. currentPolygonOffsetUnits = units;
  16341. }
  16342. } else {
  16343. disable( gl.POLYGON_OFFSET_FILL );
  16344. }
  16345. }
  16346. function setScissorTest( scissorTest ) {
  16347. if ( scissorTest ) {
  16348. enable( gl.SCISSOR_TEST );
  16349. } else {
  16350. disable( gl.SCISSOR_TEST );
  16351. }
  16352. }
  16353. // texture
  16354. function activeTexture( webglSlot ) {
  16355. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  16356. if ( currentTextureSlot !== webglSlot ) {
  16357. gl.activeTexture( webglSlot );
  16358. currentTextureSlot = webglSlot;
  16359. }
  16360. }
  16361. function bindTexture( webglType, webglTexture ) {
  16362. if ( currentTextureSlot === null ) {
  16363. activeTexture();
  16364. }
  16365. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16366. if ( boundTexture === undefined ) {
  16367. boundTexture = { type: undefined, texture: undefined };
  16368. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16369. }
  16370. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16371. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  16372. boundTexture.type = webglType;
  16373. boundTexture.texture = webglTexture;
  16374. }
  16375. }
  16376. function compressedTexImage2D() {
  16377. try {
  16378. gl.compressedTexImage2D.apply( gl, arguments );
  16379. } catch ( error ) {
  16380. console.error( 'THREE.WebGLState:', error );
  16381. }
  16382. }
  16383. function texImage2D() {
  16384. try {
  16385. gl.texImage2D.apply( gl, arguments );
  16386. } catch ( error ) {
  16387. console.error( 'THREE.WebGLState:', error );
  16388. }
  16389. }
  16390. //
  16391. function scissor( scissor ) {
  16392. if ( currentScissor.equals( scissor ) === false ) {
  16393. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  16394. currentScissor.copy( scissor );
  16395. }
  16396. }
  16397. function viewport( viewport ) {
  16398. if ( currentViewport.equals( viewport ) === false ) {
  16399. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  16400. currentViewport.copy( viewport );
  16401. }
  16402. }
  16403. //
  16404. function reset() {
  16405. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16406. if ( enabledAttributes[ i ] === 1 ) {
  16407. gl.disableVertexAttribArray( i );
  16408. enabledAttributes[ i ] = 0;
  16409. }
  16410. }
  16411. capabilities = {};
  16412. compressedTextureFormats = null;
  16413. currentTextureSlot = null;
  16414. currentBoundTextures = {};
  16415. currentProgram = null;
  16416. currentBlending = null;
  16417. currentFlipSided = null;
  16418. currentCullFace = null;
  16419. colorBuffer.reset();
  16420. depthBuffer.reset();
  16421. stencilBuffer.reset();
  16422. }
  16423. return {
  16424. buffers: {
  16425. color: colorBuffer,
  16426. depth: depthBuffer,
  16427. stencil: stencilBuffer
  16428. },
  16429. initAttributes: initAttributes,
  16430. enableAttribute: enableAttribute,
  16431. enableAttributeAndDivisor: enableAttributeAndDivisor,
  16432. disableUnusedAttributes: disableUnusedAttributes,
  16433. enable: enable,
  16434. disable: disable,
  16435. getCompressedTextureFormats: getCompressedTextureFormats,
  16436. useProgram: useProgram,
  16437. setBlending: setBlending,
  16438. setMaterial: setMaterial,
  16439. setFlipSided: setFlipSided,
  16440. setCullFace: setCullFace,
  16441. setLineWidth: setLineWidth,
  16442. setPolygonOffset: setPolygonOffset,
  16443. setScissorTest: setScissorTest,
  16444. activeTexture: activeTexture,
  16445. bindTexture: bindTexture,
  16446. compressedTexImage2D: compressedTexImage2D,
  16447. texImage2D: texImage2D,
  16448. scissor: scissor,
  16449. viewport: viewport,
  16450. reset: reset
  16451. };
  16452. }
  16453. /**
  16454. * @author mrdoob / http://mrdoob.com/
  16455. */
  16456. function WebGLCapabilities( gl, extensions, parameters ) {
  16457. var maxAnisotropy;
  16458. function getMaxAnisotropy() {
  16459. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  16460. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16461. if ( extension !== null ) {
  16462. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  16463. } else {
  16464. maxAnisotropy = 0;
  16465. }
  16466. return maxAnisotropy;
  16467. }
  16468. function getMaxPrecision( precision ) {
  16469. if ( precision === 'highp' ) {
  16470. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16471. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16472. return 'highp';
  16473. }
  16474. precision = 'mediump';
  16475. }
  16476. if ( precision === 'mediump' ) {
  16477. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16478. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16479. return 'mediump';
  16480. }
  16481. }
  16482. return 'lowp';
  16483. }
  16484. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  16485. var maxPrecision = getMaxPrecision( precision );
  16486. if ( maxPrecision !== precision ) {
  16487. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  16488. precision = maxPrecision;
  16489. }
  16490. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  16491. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16492. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16493. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16494. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16495. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16496. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16497. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16498. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16499. var vertexTextures = maxVertexTextures > 0;
  16500. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16501. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  16502. return {
  16503. getMaxAnisotropy: getMaxAnisotropy,
  16504. getMaxPrecision: getMaxPrecision,
  16505. precision: precision,
  16506. logarithmicDepthBuffer: logarithmicDepthBuffer,
  16507. maxTextures: maxTextures,
  16508. maxVertexTextures: maxVertexTextures,
  16509. maxTextureSize: maxTextureSize,
  16510. maxCubemapSize: maxCubemapSize,
  16511. maxAttributes: maxAttributes,
  16512. maxVertexUniforms: maxVertexUniforms,
  16513. maxVaryings: maxVaryings,
  16514. maxFragmentUniforms: maxFragmentUniforms,
  16515. vertexTextures: vertexTextures,
  16516. floatFragmentTextures: floatFragmentTextures,
  16517. floatVertexTextures: floatVertexTextures
  16518. };
  16519. }
  16520. /**
  16521. * @author mrdoob / http://mrdoob.com/
  16522. */
  16523. function ArrayCamera( array ) {
  16524. PerspectiveCamera.call( this );
  16525. this.cameras = array || [];
  16526. }
  16527. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  16528. constructor: ArrayCamera,
  16529. isArrayCamera: true
  16530. } );
  16531. /**
  16532. * @author mrdoob / http://mrdoob.com/
  16533. */
  16534. function WebVRManager( renderer ) {
  16535. var scope = this;
  16536. var device = null;
  16537. var frameData = null;
  16538. if ( 'VRFrameData' in window ) {
  16539. frameData = new window.VRFrameData();
  16540. }
  16541. var matrixWorldInverse = new Matrix4();
  16542. var standingMatrix = new Matrix4();
  16543. var standingMatrixInverse = new Matrix4();
  16544. var cameraL = new PerspectiveCamera();
  16545. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  16546. cameraL.layers.enable( 1 );
  16547. var cameraR = new PerspectiveCamera();
  16548. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  16549. cameraR.layers.enable( 2 );
  16550. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16551. cameraVR.layers.enable( 1 );
  16552. cameraVR.layers.enable( 2 );
  16553. //
  16554. var currentSize, currentPixelRatio;
  16555. function onVRDisplayPresentChange() {
  16556. if ( device !== null && device.isPresenting ) {
  16557. var eyeParameters = device.getEyeParameters( 'left' );
  16558. var renderWidth = eyeParameters.renderWidth;
  16559. var renderHeight = eyeParameters.renderHeight;
  16560. currentPixelRatio = renderer.getPixelRatio();
  16561. currentSize = renderer.getSize();
  16562. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  16563. } else if ( scope.enabled ) {
  16564. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  16565. }
  16566. }
  16567. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  16568. //
  16569. this.enabled = false;
  16570. this.standing = false;
  16571. this.getDevice = function () {
  16572. return device;
  16573. };
  16574. this.setDevice = function ( value ) {
  16575. if ( value !== undefined ) device = value;
  16576. };
  16577. this.getCamera = function ( camera ) {
  16578. if ( device === null ) return camera;
  16579. device.depthNear = camera.near;
  16580. device.depthFar = camera.far;
  16581. device.getFrameData( frameData );
  16582. //
  16583. var pose = frameData.pose;
  16584. if ( pose.position !== null ) {
  16585. camera.position.fromArray( pose.position );
  16586. } else {
  16587. camera.position.set( 0, 0, 0 );
  16588. }
  16589. if ( pose.orientation !== null ) {
  16590. camera.quaternion.fromArray( pose.orientation );
  16591. }
  16592. camera.updateMatrixWorld();
  16593. var stageParameters = device.stageParameters;
  16594. if ( this.standing && stageParameters ) {
  16595. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  16596. standingMatrixInverse.getInverse( standingMatrix );
  16597. camera.matrixWorld.multiply( standingMatrix );
  16598. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  16599. }
  16600. if ( device.isPresenting === false ) return camera;
  16601. //
  16602. cameraL.near = camera.near;
  16603. cameraR.near = camera.near;
  16604. cameraL.far = camera.far;
  16605. cameraR.far = camera.far;
  16606. cameraVR.matrixWorld.copy( camera.matrixWorld );
  16607. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  16608. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  16609. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  16610. if ( this.standing && stageParameters ) {
  16611. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  16612. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  16613. }
  16614. var parent = camera.parent;
  16615. if ( parent !== null ) {
  16616. matrixWorldInverse.getInverse( parent.matrixWorld );
  16617. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  16618. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  16619. }
  16620. // envMap and Mirror needs camera.matrixWorld
  16621. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  16622. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  16623. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  16624. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  16625. // HACK @mrdoob
  16626. // https://github.com/w3c/webvr/issues/203
  16627. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  16628. //
  16629. var layers = device.getLayers();
  16630. if ( layers.length ) {
  16631. var layer = layers[ 0 ];
  16632. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  16633. cameraL.bounds.fromArray( layer.leftBounds );
  16634. }
  16635. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  16636. cameraR.bounds.fromArray( layer.rightBounds );
  16637. }
  16638. }
  16639. return cameraVR;
  16640. };
  16641. this.getStandingMatrix = function () {
  16642. return standingMatrix;
  16643. };
  16644. this.submitFrame = function () {
  16645. if ( device && device.isPresenting ) device.submitFrame();
  16646. };
  16647. this.dispose = function() {
  16648. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  16649. };
  16650. }
  16651. /**
  16652. * @author mrdoob / http://mrdoob.com/
  16653. */
  16654. function WebGLExtensions( gl ) {
  16655. var extensions = {};
  16656. return {
  16657. get: function ( name ) {
  16658. if ( extensions[ name ] !== undefined ) {
  16659. return extensions[ name ];
  16660. }
  16661. var extension;
  16662. switch ( name ) {
  16663. case 'WEBGL_depth_texture':
  16664. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  16665. break;
  16666. case 'EXT_texture_filter_anisotropic':
  16667. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16668. break;
  16669. case 'WEBGL_compressed_texture_s3tc':
  16670. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16671. break;
  16672. case 'WEBGL_compressed_texture_pvrtc':
  16673. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16674. break;
  16675. case 'WEBGL_compressed_texture_etc1':
  16676. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  16677. break;
  16678. default:
  16679. extension = gl.getExtension( name );
  16680. }
  16681. if ( extension === null ) {
  16682. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16683. }
  16684. extensions[ name ] = extension;
  16685. return extension;
  16686. }
  16687. };
  16688. }
  16689. /**
  16690. * @author tschw
  16691. */
  16692. function WebGLClipping() {
  16693. var scope = this,
  16694. globalState = null,
  16695. numGlobalPlanes = 0,
  16696. localClippingEnabled = false,
  16697. renderingShadows = false,
  16698. plane = new Plane(),
  16699. viewNormalMatrix = new Matrix3(),
  16700. uniform = { value: null, needsUpdate: false };
  16701. this.uniform = uniform;
  16702. this.numPlanes = 0;
  16703. this.numIntersection = 0;
  16704. this.init = function( planes, enableLocalClipping, camera ) {
  16705. var enabled =
  16706. planes.length !== 0 ||
  16707. enableLocalClipping ||
  16708. // enable state of previous frame - the clipping code has to
  16709. // run another frame in order to reset the state:
  16710. numGlobalPlanes !== 0 ||
  16711. localClippingEnabled;
  16712. localClippingEnabled = enableLocalClipping;
  16713. globalState = projectPlanes( planes, camera, 0 );
  16714. numGlobalPlanes = planes.length;
  16715. return enabled;
  16716. };
  16717. this.beginShadows = function() {
  16718. renderingShadows = true;
  16719. projectPlanes( null );
  16720. };
  16721. this.endShadows = function() {
  16722. renderingShadows = false;
  16723. resetGlobalState();
  16724. };
  16725. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  16726. if ( ! localClippingEnabled ||
  16727. planes === null || planes.length === 0 ||
  16728. renderingShadows && ! clipShadows ) {
  16729. // there's no local clipping
  16730. if ( renderingShadows ) {
  16731. // there's no global clipping
  16732. projectPlanes( null );
  16733. } else {
  16734. resetGlobalState();
  16735. }
  16736. } else {
  16737. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  16738. lGlobal = nGlobal * 4,
  16739. dstArray = cache.clippingState || null;
  16740. uniform.value = dstArray; // ensure unique state
  16741. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  16742. for ( var i = 0; i !== lGlobal; ++ i ) {
  16743. dstArray[ i ] = globalState[ i ];
  16744. }
  16745. cache.clippingState = dstArray;
  16746. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  16747. this.numPlanes += nGlobal;
  16748. }
  16749. };
  16750. function resetGlobalState() {
  16751. if ( uniform.value !== globalState ) {
  16752. uniform.value = globalState;
  16753. uniform.needsUpdate = numGlobalPlanes > 0;
  16754. }
  16755. scope.numPlanes = numGlobalPlanes;
  16756. scope.numIntersection = 0;
  16757. }
  16758. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  16759. var nPlanes = planes !== null ? planes.length : 0,
  16760. dstArray = null;
  16761. if ( nPlanes !== 0 ) {
  16762. dstArray = uniform.value;
  16763. if ( skipTransform !== true || dstArray === null ) {
  16764. var flatSize = dstOffset + nPlanes * 4,
  16765. viewMatrix = camera.matrixWorldInverse;
  16766. viewNormalMatrix.getNormalMatrix( viewMatrix );
  16767. if ( dstArray === null || dstArray.length < flatSize ) {
  16768. dstArray = new Float32Array( flatSize );
  16769. }
  16770. for ( var i = 0, i4 = dstOffset;
  16771. i !== nPlanes; ++ i, i4 += 4 ) {
  16772. plane.copy( planes[ i ] ).
  16773. applyMatrix4( viewMatrix, viewNormalMatrix );
  16774. plane.normal.toArray( dstArray, i4 );
  16775. dstArray[ i4 + 3 ] = plane.constant;
  16776. }
  16777. }
  16778. uniform.value = dstArray;
  16779. uniform.needsUpdate = true;
  16780. }
  16781. scope.numPlanes = nPlanes;
  16782. return dstArray;
  16783. }
  16784. }
  16785. /**
  16786. * @author thespite / http://www.twitter.com/thespite
  16787. */
  16788. function WebGLUtils ( gl, extensions ) {
  16789. function convert ( p ) {
  16790. var extension;
  16791. if ( p === RepeatWrapping ) return gl.REPEAT;
  16792. if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE;
  16793. if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT;
  16794. if ( p === NearestFilter ) return gl.NEAREST;
  16795. if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST;
  16796. if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR;
  16797. if ( p === LinearFilter ) return gl.LINEAR;
  16798. if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST;
  16799. if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR;
  16800. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  16801. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  16802. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  16803. if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
  16804. if ( p === ByteType ) return gl.BYTE;
  16805. if ( p === ShortType ) return gl.SHORT;
  16806. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  16807. if ( p === IntType ) return gl.INT;
  16808. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  16809. if ( p === FloatType ) return gl.FLOAT;
  16810. if ( p === HalfFloatType ) {
  16811. extension = extensions.get( 'OES_texture_half_float' );
  16812. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  16813. }
  16814. if ( p === AlphaFormat ) return gl.ALPHA;
  16815. if ( p === RGBFormat ) return gl.RGB;
  16816. if ( p === RGBAFormat ) return gl.RGBA;
  16817. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  16818. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  16819. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  16820. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  16821. if ( p === AddEquation ) return gl.FUNC_ADD;
  16822. if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT;
  16823. if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT;
  16824. if ( p === ZeroFactor ) return gl.ZERO;
  16825. if ( p === OneFactor ) return gl.ONE;
  16826. if ( p === SrcColorFactor ) return gl.SRC_COLOR;
  16827. if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR;
  16828. if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA;
  16829. if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA;
  16830. if ( p === DstAlphaFactor ) return gl.DST_ALPHA;
  16831. if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA;
  16832. if ( p === DstColorFactor ) return gl.DST_COLOR;
  16833. if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR;
  16834. if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE;
  16835. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  16836. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  16837. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16838. if ( extension !== null ) {
  16839. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16840. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16841. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16842. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16843. }
  16844. }
  16845. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  16846. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  16847. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16848. if ( extension !== null ) {
  16849. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16850. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16851. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16852. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16853. }
  16854. }
  16855. if ( p === RGB_ETC1_Format ) {
  16856. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16857. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16858. }
  16859. if ( p === MinEquation || p === MaxEquation ) {
  16860. extension = extensions.get( 'EXT_blend_minmax' );
  16861. if ( extension !== null ) {
  16862. if ( p === MinEquation ) return extension.MIN_EXT;
  16863. if ( p === MaxEquation ) return extension.MAX_EXT;
  16864. }
  16865. }
  16866. if ( p === UnsignedInt248Type ) {
  16867. extension = extensions.get( 'WEBGL_depth_texture' );
  16868. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  16869. }
  16870. return 0;
  16871. }
  16872. return { convert: convert }
  16873. }
  16874. // import { Sphere } from '../math/Sphere';
  16875. /**
  16876. * @author supereggbert / http://www.paulbrunt.co.uk/
  16877. * @author mrdoob / http://mrdoob.com/
  16878. * @author alteredq / http://alteredqualia.com/
  16879. * @author szimek / https://github.com/szimek/
  16880. * @author tschw
  16881. */
  16882. function WebGLRenderer( parameters ) {
  16883. console.log( 'THREE.WebGLRenderer', REVISION );
  16884. parameters = parameters || {};
  16885. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  16886. _context = parameters.context !== undefined ? parameters.context : null,
  16887. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  16888. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16889. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16890. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16891. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16892. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  16893. var lightsArray = [];
  16894. var shadowsArray = [];
  16895. var currentRenderList = null;
  16896. var spritesArray = [];
  16897. var flaresArray = [];
  16898. // public properties
  16899. this.domElement = _canvas;
  16900. this.context = null;
  16901. // clearing
  16902. this.autoClear = true;
  16903. this.autoClearColor = true;
  16904. this.autoClearDepth = true;
  16905. this.autoClearStencil = true;
  16906. // scene graph
  16907. this.sortObjects = true;
  16908. // user-defined clipping
  16909. this.clippingPlanes = [];
  16910. this.localClippingEnabled = false;
  16911. // physically based shading
  16912. this.gammaFactor = 2.0; // for backwards compatibility
  16913. this.gammaInput = false;
  16914. this.gammaOutput = false;
  16915. // physical lights
  16916. this.physicallyCorrectLights = false;
  16917. // tone mapping
  16918. this.toneMapping = LinearToneMapping;
  16919. this.toneMappingExposure = 1.0;
  16920. this.toneMappingWhitePoint = 1.0;
  16921. // morphs
  16922. this.maxMorphTargets = 8;
  16923. this.maxMorphNormals = 4;
  16924. // internal properties
  16925. var _this = this,
  16926. _isContextLost = false,
  16927. // internal state cache
  16928. _currentRenderTarget = null,
  16929. _currentFramebuffer = null,
  16930. _currentMaterialId = - 1,
  16931. _currentGeometryProgram = '',
  16932. _currentCamera = null,
  16933. _currentArrayCamera = null,
  16934. _currentViewport = new Vector4(),
  16935. _currentScissor = new Vector4(),
  16936. _currentScissorTest = null,
  16937. //
  16938. _usedTextureUnits = 0,
  16939. //
  16940. _width = _canvas.width,
  16941. _height = _canvas.height,
  16942. _pixelRatio = 1,
  16943. _viewport = new Vector4( 0, 0, _width, _height ),
  16944. _scissor = new Vector4( 0, 0, _width, _height ),
  16945. _scissorTest = false,
  16946. // frustum
  16947. _frustum = new Frustum(),
  16948. // clipping
  16949. _clipping = new WebGLClipping(),
  16950. _clippingEnabled = false,
  16951. _localClippingEnabled = false,
  16952. // camera matrices cache
  16953. _projScreenMatrix = new Matrix4(),
  16954. _vector3 = new Vector3(),
  16955. // info
  16956. _infoMemory = {
  16957. geometries: 0,
  16958. textures: 0
  16959. },
  16960. _infoRender = {
  16961. frame: 0,
  16962. calls: 0,
  16963. vertices: 0,
  16964. faces: 0,
  16965. points: 0
  16966. };
  16967. this.info = {
  16968. render: _infoRender,
  16969. memory: _infoMemory,
  16970. programs: null
  16971. };
  16972. function getTargetPixelRatio() {
  16973. return _currentRenderTarget === null ? _pixelRatio : 1;
  16974. }
  16975. // initialize
  16976. var _gl;
  16977. try {
  16978. var contextAttributes = {
  16979. alpha: _alpha,
  16980. depth: _depth,
  16981. stencil: _stencil,
  16982. antialias: _antialias,
  16983. premultipliedAlpha: _premultipliedAlpha,
  16984. preserveDrawingBuffer: _preserveDrawingBuffer
  16985. };
  16986. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  16987. if ( _gl === null ) {
  16988. if ( _canvas.getContext( 'webgl' ) !== null ) {
  16989. throw 'Error creating WebGL context with your selected attributes.';
  16990. } else {
  16991. throw 'Error creating WebGL context.';
  16992. }
  16993. }
  16994. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16995. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16996. _gl.getShaderPrecisionFormat = function () {
  16997. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16998. };
  16999. }
  17000. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17001. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17002. } catch ( error ) {
  17003. console.error( 'THREE.WebGLRenderer: ' + error );
  17004. }
  17005. var extensions, capabilities, state;
  17006. var properties, textures, attributes, geometries, objects, lights;
  17007. var programCache, renderLists;
  17008. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17009. var flareRenderer, spriteRenderer;
  17010. var utils;
  17011. function initGLContext() {
  17012. extensions = new WebGLExtensions( _gl );
  17013. extensions.get( 'WEBGL_depth_texture' );
  17014. extensions.get( 'OES_texture_float' );
  17015. extensions.get( 'OES_texture_float_linear' );
  17016. extensions.get( 'OES_texture_half_float' );
  17017. extensions.get( 'OES_texture_half_float_linear' );
  17018. extensions.get( 'OES_standard_derivatives' );
  17019. extensions.get( 'ANGLE_instanced_arrays' );
  17020. if ( extensions.get( 'OES_element_index_uint' ) ) {
  17021. BufferGeometry.MaxIndex = 4294967296;
  17022. }
  17023. utils = new WebGLUtils( _gl, extensions );
  17024. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  17025. state = new WebGLState( _gl, extensions, utils );
  17026. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17027. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17028. properties = new WebGLProperties();
  17029. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, _infoMemory );
  17030. attributes = new WebGLAttributes( _gl );
  17031. geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  17032. objects = new WebGLObjects( geometries, _infoRender );
  17033. morphtargets = new WebGLMorphtargets( _gl );
  17034. programCache = new WebGLPrograms( _this, extensions, capabilities );
  17035. lights = new WebGLLights();
  17036. renderLists = new WebGLRenderLists();
  17037. background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha );
  17038. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  17039. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  17040. flareRenderer = new WebGLFlareRenderer( _this, _gl, state, textures, capabilities );
  17041. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities );
  17042. _this.info.programs = programCache.programs;
  17043. _this.context = _gl;
  17044. _this.capabilities = capabilities;
  17045. _this.extensions = extensions;
  17046. _this.properties = properties;
  17047. _this.renderLists = renderLists;
  17048. _this.state = state;
  17049. }
  17050. initGLContext();
  17051. // vr
  17052. var vr = new WebVRManager( _this );
  17053. this.vr = vr;
  17054. // shadow map
  17055. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  17056. this.shadowMap = shadowMap;
  17057. // API
  17058. this.getContext = function () {
  17059. return _gl;
  17060. };
  17061. this.getContextAttributes = function () {
  17062. return _gl.getContextAttributes();
  17063. };
  17064. this.forceContextLoss = function () {
  17065. var extension = extensions.get( 'WEBGL_lose_context' );
  17066. if ( extension ) extension.loseContext();
  17067. };
  17068. this.forceContextRestore = function () {
  17069. var extension = extensions.get( 'WEBGL_lose_context' );
  17070. if ( extension ) extension.restoreContext();
  17071. };
  17072. this.getPixelRatio = function () {
  17073. return _pixelRatio;
  17074. };
  17075. this.setPixelRatio = function ( value ) {
  17076. if ( value === undefined ) return;
  17077. _pixelRatio = value;
  17078. this.setSize( _width, _height, false );
  17079. };
  17080. this.getSize = function () {
  17081. return {
  17082. width: _width,
  17083. height: _height
  17084. };
  17085. };
  17086. this.setSize = function ( width, height, updateStyle ) {
  17087. var device = vr.getDevice();
  17088. if ( device && device.isPresenting ) {
  17089. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17090. return;
  17091. }
  17092. _width = width;
  17093. _height = height;
  17094. _canvas.width = width * _pixelRatio;
  17095. _canvas.height = height * _pixelRatio;
  17096. if ( updateStyle !== false ) {
  17097. _canvas.style.width = width + 'px';
  17098. _canvas.style.height = height + 'px';
  17099. }
  17100. this.setViewport( 0, 0, width, height );
  17101. };
  17102. this.getDrawingBufferSize = function () {
  17103. return {
  17104. width: _width * _pixelRatio,
  17105. height: _height * _pixelRatio
  17106. };
  17107. };
  17108. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17109. _width = width;
  17110. _height = height;
  17111. _pixelRatio = pixelRatio;
  17112. _canvas.width = width * pixelRatio;
  17113. _canvas.height = height * pixelRatio;
  17114. this.setViewport( 0, 0, width, height );
  17115. };
  17116. this.setViewport = function ( x, y, width, height ) {
  17117. _viewport.set( x, _height - y - height, width, height );
  17118. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17119. };
  17120. this.setScissor = function ( x, y, width, height ) {
  17121. _scissor.set( x, _height - y - height, width, height );
  17122. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17123. };
  17124. this.setScissorTest = function ( boolean ) {
  17125. state.setScissorTest( _scissorTest = boolean );
  17126. };
  17127. // Clearing
  17128. this.getClearColor = background.getClearColor;
  17129. this.setClearColor = background.setClearColor;
  17130. this.getClearAlpha = background.getClearAlpha;
  17131. this.setClearAlpha = background.setClearAlpha;
  17132. this.clear = function ( color, depth, stencil ) {
  17133. var bits = 0;
  17134. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  17135. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17136. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  17137. _gl.clear( bits );
  17138. };
  17139. this.clearColor = function () {
  17140. this.clear( true, false, false );
  17141. };
  17142. this.clearDepth = function () {
  17143. this.clear( false, true, false );
  17144. };
  17145. this.clearStencil = function () {
  17146. this.clear( false, false, true );
  17147. };
  17148. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  17149. this.setRenderTarget( renderTarget );
  17150. this.clear( color, depth, stencil );
  17151. };
  17152. //
  17153. this.dispose = function () {
  17154. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17155. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17156. renderLists.dispose();
  17157. vr.dispose();
  17158. };
  17159. // Events
  17160. function onContextLost( event ) {
  17161. event.preventDefault();
  17162. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17163. _isContextLost = true;
  17164. }
  17165. function onContextRestore( event ) {
  17166. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17167. _isContextLost = false;
  17168. initGLContext();
  17169. }
  17170. function onMaterialDispose( event ) {
  17171. var material = event.target;
  17172. material.removeEventListener( 'dispose', onMaterialDispose );
  17173. deallocateMaterial( material );
  17174. }
  17175. // Buffer deallocation
  17176. function deallocateMaterial( material ) {
  17177. releaseMaterialProgramReference( material );
  17178. properties.remove( material );
  17179. }
  17180. function releaseMaterialProgramReference( material ) {
  17181. var programInfo = properties.get( material ).program;
  17182. material.program = undefined;
  17183. if ( programInfo !== undefined ) {
  17184. programCache.releaseProgram( programInfo );
  17185. }
  17186. }
  17187. // Buffer rendering
  17188. function renderObjectImmediate( object, program, material ) {
  17189. object.render( function ( object ) {
  17190. _this.renderBufferImmediate( object, program, material );
  17191. } );
  17192. }
  17193. this.renderBufferImmediate = function ( object, program, material ) {
  17194. state.initAttributes();
  17195. var buffers = properties.get( object );
  17196. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  17197. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  17198. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  17199. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  17200. var programAttributes = program.getAttributes();
  17201. if ( object.hasPositions ) {
  17202. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  17203. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  17204. state.enableAttribute( programAttributes.position );
  17205. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  17206. }
  17207. if ( object.hasNormals ) {
  17208. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  17209. if ( ! material.isMeshPhongMaterial &&
  17210. ! material.isMeshStandardMaterial &&
  17211. ! material.isMeshNormalMaterial &&
  17212. material.flatShading === true ) {
  17213. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  17214. var array = object.normalArray;
  17215. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  17216. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  17217. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  17218. array[ i + 0 ] = nx;
  17219. array[ i + 1 ] = ny;
  17220. array[ i + 2 ] = nz;
  17221. array[ i + 3 ] = nx;
  17222. array[ i + 4 ] = ny;
  17223. array[ i + 5 ] = nz;
  17224. array[ i + 6 ] = nx;
  17225. array[ i + 7 ] = ny;
  17226. array[ i + 8 ] = nz;
  17227. }
  17228. }
  17229. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  17230. state.enableAttribute( programAttributes.normal );
  17231. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  17232. }
  17233. if ( object.hasUvs && material.map ) {
  17234. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  17235. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  17236. state.enableAttribute( programAttributes.uv );
  17237. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  17238. }
  17239. if ( object.hasColors && material.vertexColors !== NoColors ) {
  17240. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  17241. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  17242. state.enableAttribute( programAttributes.color );
  17243. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  17244. }
  17245. state.disableUnusedAttributes();
  17246. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  17247. object.count = 0;
  17248. };
  17249. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  17250. state.setMaterial( material );
  17251. var program = setProgram( camera, fog, material, object );
  17252. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  17253. var updateBuffers = false;
  17254. if ( geometryProgram !== _currentGeometryProgram ) {
  17255. _currentGeometryProgram = geometryProgram;
  17256. updateBuffers = true;
  17257. }
  17258. if ( object.morphTargetInfluences ) {
  17259. morphtargets.update( object, geometry, material, program );
  17260. updateBuffers = true;
  17261. }
  17262. //
  17263. var index = geometry.index;
  17264. var position = geometry.attributes.position;
  17265. var rangeFactor = 1;
  17266. if ( material.wireframe === true ) {
  17267. index = geometries.getWireframeAttribute( geometry );
  17268. rangeFactor = 2;
  17269. }
  17270. var attribute;
  17271. var renderer = bufferRenderer;
  17272. if ( index !== null ) {
  17273. attribute = attributes.get( index );
  17274. renderer = indexedBufferRenderer;
  17275. renderer.setIndex( attribute );
  17276. }
  17277. if ( updateBuffers ) {
  17278. setupVertexAttributes( material, program, geometry );
  17279. if ( index !== null ) {
  17280. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  17281. }
  17282. }
  17283. //
  17284. var dataCount = 0;
  17285. if ( index !== null ) {
  17286. dataCount = index.count;
  17287. } else if ( position !== undefined ) {
  17288. dataCount = position.count;
  17289. }
  17290. var rangeStart = geometry.drawRange.start * rangeFactor;
  17291. var rangeCount = geometry.drawRange.count * rangeFactor;
  17292. var groupStart = group !== null ? group.start * rangeFactor : 0;
  17293. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  17294. var drawStart = Math.max( rangeStart, groupStart );
  17295. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  17296. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  17297. if ( drawCount === 0 ) return;
  17298. //
  17299. if ( object.isMesh ) {
  17300. if ( material.wireframe === true ) {
  17301. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17302. renderer.setMode( _gl.LINES );
  17303. } else {
  17304. switch ( object.drawMode ) {
  17305. case TrianglesDrawMode:
  17306. renderer.setMode( _gl.TRIANGLES );
  17307. break;
  17308. case TriangleStripDrawMode:
  17309. renderer.setMode( _gl.TRIANGLE_STRIP );
  17310. break;
  17311. case TriangleFanDrawMode:
  17312. renderer.setMode( _gl.TRIANGLE_FAN );
  17313. break;
  17314. }
  17315. }
  17316. } else if ( object.isLine ) {
  17317. var lineWidth = material.linewidth;
  17318. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17319. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17320. if ( object.isLineSegments ) {
  17321. renderer.setMode( _gl.LINES );
  17322. } else if ( object.isLineLoop ) {
  17323. renderer.setMode( _gl.LINE_LOOP );
  17324. } else {
  17325. renderer.setMode( _gl.LINE_STRIP );
  17326. }
  17327. } else if ( object.isPoints ) {
  17328. renderer.setMode( _gl.POINTS );
  17329. }
  17330. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17331. if ( geometry.maxInstancedCount > 0 ) {
  17332. renderer.renderInstances( geometry, drawStart, drawCount );
  17333. }
  17334. } else {
  17335. renderer.render( drawStart, drawCount );
  17336. }
  17337. };
  17338. function setupVertexAttributes( material, program, geometry, startIndex ) {
  17339. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17340. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  17341. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  17342. return;
  17343. }
  17344. }
  17345. if ( startIndex === undefined ) startIndex = 0;
  17346. state.initAttributes();
  17347. var geometryAttributes = geometry.attributes;
  17348. var programAttributes = program.getAttributes();
  17349. var materialDefaultAttributeValues = material.defaultAttributeValues;
  17350. for ( var name in programAttributes ) {
  17351. var programAttribute = programAttributes[ name ];
  17352. if ( programAttribute >= 0 ) {
  17353. var geometryAttribute = geometryAttributes[ name ];
  17354. if ( geometryAttribute !== undefined ) {
  17355. var normalized = geometryAttribute.normalized;
  17356. var size = geometryAttribute.itemSize;
  17357. var attribute = attributes.get( geometryAttribute );
  17358. // TODO Attribute may not be available on context restore
  17359. if ( attribute === undefined ) continue;
  17360. var buffer = attribute.buffer;
  17361. var type = attribute.type;
  17362. var bytesPerElement = attribute.bytesPerElement;
  17363. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  17364. var data = geometryAttribute.data;
  17365. var stride = data.stride;
  17366. var offset = geometryAttribute.offset;
  17367. if ( data && data.isInstancedInterleavedBuffer ) {
  17368. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  17369. if ( geometry.maxInstancedCount === undefined ) {
  17370. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  17371. }
  17372. } else {
  17373. state.enableAttribute( programAttribute );
  17374. }
  17375. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17376. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  17377. } else {
  17378. if ( geometryAttribute.isInstancedBufferAttribute ) {
  17379. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  17380. if ( geometry.maxInstancedCount === undefined ) {
  17381. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  17382. }
  17383. } else {
  17384. state.enableAttribute( programAttribute );
  17385. }
  17386. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17387. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  17388. }
  17389. } else if ( materialDefaultAttributeValues !== undefined ) {
  17390. var value = materialDefaultAttributeValues[ name ];
  17391. if ( value !== undefined ) {
  17392. switch ( value.length ) {
  17393. case 2:
  17394. _gl.vertexAttrib2fv( programAttribute, value );
  17395. break;
  17396. case 3:
  17397. _gl.vertexAttrib3fv( programAttribute, value );
  17398. break;
  17399. case 4:
  17400. _gl.vertexAttrib4fv( programAttribute, value );
  17401. break;
  17402. default:
  17403. _gl.vertexAttrib1fv( programAttribute, value );
  17404. }
  17405. }
  17406. }
  17407. }
  17408. }
  17409. state.disableUnusedAttributes();
  17410. }
  17411. // Compile
  17412. this.compile = function ( scene, camera ) {
  17413. lightsArray.length = 0;
  17414. shadowsArray.length = 0;
  17415. scene.traverse( function ( object ) {
  17416. if ( object.isLight ) {
  17417. lightsArray.push( object );
  17418. if ( object.castShadow ) {
  17419. shadowsArray.push( object );
  17420. }
  17421. }
  17422. } );
  17423. lights.setup( lightsArray, shadowsArray, camera );
  17424. scene.traverse( function ( object ) {
  17425. if ( object.material ) {
  17426. if ( Array.isArray( object.material ) ) {
  17427. for ( var i = 0; i < object.material.length; i ++ ) {
  17428. initMaterial( object.material[ i ], scene.fog, object );
  17429. }
  17430. } else {
  17431. initMaterial( object.material, scene.fog, object );
  17432. }
  17433. }
  17434. } );
  17435. };
  17436. // Animation Loop
  17437. var isAnimating = false;
  17438. var onAnimationFrame = null;
  17439. function start() {
  17440. if ( isAnimating ) return;
  17441. ( vr.getDevice() || window ).requestAnimationFrame( loop );
  17442. isAnimating = true;
  17443. }
  17444. function loop( time ) {
  17445. if ( onAnimationFrame !== null ) onAnimationFrame( time );
  17446. ( vr.getDevice() || window ).requestAnimationFrame( loop );
  17447. }
  17448. this.animate = function ( callback ) {
  17449. onAnimationFrame = callback;
  17450. start();
  17451. };
  17452. // Rendering
  17453. this.render = function ( scene, camera, renderTarget, forceClear ) {
  17454. if ( ! ( camera && camera.isCamera ) ) {
  17455. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17456. return;
  17457. }
  17458. if ( _isContextLost ) return;
  17459. // reset caching for this frame
  17460. _currentGeometryProgram = '';
  17461. _currentMaterialId = - 1;
  17462. _currentCamera = null;
  17463. // update scene graph
  17464. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  17465. // update camera matrices and frustum
  17466. if ( camera.parent === null ) camera.updateMatrixWorld();
  17467. if ( vr.enabled ) {
  17468. camera = vr.getCamera( camera );
  17469. }
  17470. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17471. _frustum.setFromMatrix( _projScreenMatrix );
  17472. lightsArray.length = 0;
  17473. shadowsArray.length = 0;
  17474. spritesArray.length = 0;
  17475. flaresArray.length = 0;
  17476. _localClippingEnabled = this.localClippingEnabled;
  17477. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  17478. currentRenderList = renderLists.get( scene, camera );
  17479. currentRenderList.init();
  17480. projectObject( scene, camera, _this.sortObjects );
  17481. if ( _this.sortObjects === true ) {
  17482. currentRenderList.sort();
  17483. }
  17484. //
  17485. if ( _clippingEnabled ) _clipping.beginShadows();
  17486. shadowMap.render( shadowsArray, scene, camera );
  17487. lights.setup( lightsArray, shadowsArray, camera );
  17488. if ( _clippingEnabled ) _clipping.endShadows();
  17489. //
  17490. _infoRender.frame ++;
  17491. _infoRender.calls = 0;
  17492. _infoRender.vertices = 0;
  17493. _infoRender.faces = 0;
  17494. _infoRender.points = 0;
  17495. if ( renderTarget === undefined ) {
  17496. renderTarget = null;
  17497. }
  17498. this.setRenderTarget( renderTarget );
  17499. //
  17500. background.render( currentRenderList, scene, camera, forceClear );
  17501. // render scene
  17502. var opaqueObjects = currentRenderList.opaque;
  17503. var transparentObjects = currentRenderList.transparent;
  17504. if ( scene.overrideMaterial ) {
  17505. var overrideMaterial = scene.overrideMaterial;
  17506. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  17507. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  17508. } else {
  17509. // opaque pass (front-to-back order)
  17510. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  17511. // transparent pass (back-to-front order)
  17512. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  17513. }
  17514. // custom renderers
  17515. spriteRenderer.render( spritesArray, scene, camera );
  17516. flareRenderer.render( flaresArray, scene, camera, _currentViewport );
  17517. // Generate mipmap if we're using any kind of mipmap filtering
  17518. if ( renderTarget ) {
  17519. textures.updateRenderTargetMipmap( renderTarget );
  17520. }
  17521. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17522. state.buffers.depth.setTest( true );
  17523. state.buffers.depth.setMask( true );
  17524. state.buffers.color.setMask( true );
  17525. state.setPolygonOffset( false );
  17526. if ( vr.enabled ) {
  17527. vr.submitFrame();
  17528. }
  17529. // _gl.finish();
  17530. };
  17531. /*
  17532. // TODO Duplicated code (Frustum)
  17533. var _sphere = new Sphere();
  17534. function isObjectViewable( object ) {
  17535. var geometry = object.geometry;
  17536. if ( geometry.boundingSphere === null )
  17537. geometry.computeBoundingSphere();
  17538. _sphere.copy( geometry.boundingSphere ).
  17539. applyMatrix4( object.matrixWorld );
  17540. return isSphereViewable( _sphere );
  17541. }
  17542. function isSpriteViewable( sprite ) {
  17543. _sphere.center.set( 0, 0, 0 );
  17544. _sphere.radius = 0.7071067811865476;
  17545. _sphere.applyMatrix4( sprite.matrixWorld );
  17546. return isSphereViewable( _sphere );
  17547. }
  17548. function isSphereViewable( sphere ) {
  17549. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  17550. var numPlanes = _clipping.numPlanes;
  17551. if ( numPlanes === 0 ) return true;
  17552. var planes = _this.clippingPlanes,
  17553. center = sphere.center,
  17554. negRad = - sphere.radius,
  17555. i = 0;
  17556. do {
  17557. // out when deeper than radius in the negative halfspace
  17558. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  17559. } while ( ++ i !== numPlanes );
  17560. return true;
  17561. }
  17562. */
  17563. function projectObject( object, camera, sortObjects ) {
  17564. if ( ! object.visible ) return;
  17565. var visible = object.layers.test( camera.layers );
  17566. if ( visible ) {
  17567. if ( object.isLight ) {
  17568. lightsArray.push( object );
  17569. if ( object.castShadow ) {
  17570. shadowsArray.push( object );
  17571. }
  17572. } else if ( object.isSprite ) {
  17573. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17574. spritesArray.push( object );
  17575. }
  17576. } else if ( object.isLensFlare ) {
  17577. flaresArray.push( object );
  17578. } else if ( object.isImmediateRenderObject ) {
  17579. if ( sortObjects ) {
  17580. _vector3.setFromMatrixPosition( object.matrixWorld )
  17581. .applyMatrix4( _projScreenMatrix );
  17582. }
  17583. currentRenderList.push( object, null, object.material, _vector3.z, null );
  17584. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17585. if ( object.isSkinnedMesh ) {
  17586. object.skeleton.update();
  17587. }
  17588. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17589. if ( sortObjects ) {
  17590. _vector3.setFromMatrixPosition( object.matrixWorld )
  17591. .applyMatrix4( _projScreenMatrix );
  17592. }
  17593. var geometry = objects.update( object );
  17594. var material = object.material;
  17595. if ( Array.isArray( material ) ) {
  17596. var groups = geometry.groups;
  17597. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  17598. var group = groups[ i ];
  17599. var groupMaterial = material[ group.materialIndex ];
  17600. if ( groupMaterial && groupMaterial.visible ) {
  17601. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  17602. }
  17603. }
  17604. } else if ( material.visible ) {
  17605. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17606. }
  17607. }
  17608. }
  17609. }
  17610. var children = object.children;
  17611. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17612. projectObject( children[ i ], camera, sortObjects );
  17613. }
  17614. }
  17615. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  17616. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  17617. var renderItem = renderList[ i ];
  17618. var object = renderItem.object;
  17619. var geometry = renderItem.geometry;
  17620. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  17621. var group = renderItem.group;
  17622. if ( camera.isArrayCamera ) {
  17623. _currentArrayCamera = camera;
  17624. var cameras = camera.cameras;
  17625. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  17626. var camera2 = cameras[ j ];
  17627. if ( object.layers.test( camera2.layers ) ) {
  17628. var bounds = camera2.bounds;
  17629. var x = bounds.x * _width;
  17630. var y = bounds.y * _height;
  17631. var width = bounds.z * _width;
  17632. var height = bounds.w * _height;
  17633. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  17634. renderObject( object, scene, camera2, geometry, material, group );
  17635. }
  17636. }
  17637. } else {
  17638. _currentArrayCamera = null;
  17639. renderObject( object, scene, camera, geometry, material, group );
  17640. }
  17641. }
  17642. }
  17643. function renderObject( object, scene, camera, geometry, material, group ) {
  17644. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17645. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17646. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17647. if ( object.isImmediateRenderObject ) {
  17648. state.setMaterial( material );
  17649. var program = setProgram( camera, scene.fog, material, object );
  17650. _currentGeometryProgram = '';
  17651. renderObjectImmediate( object, program, material );
  17652. } else {
  17653. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  17654. }
  17655. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17656. }
  17657. function initMaterial( material, fog, object ) {
  17658. var materialProperties = properties.get( material );
  17659. var parameters = programCache.getParameters(
  17660. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  17661. var code = programCache.getProgramCode( material, parameters );
  17662. var program = materialProperties.program;
  17663. var programChange = true;
  17664. if ( program === undefined ) {
  17665. // new material
  17666. material.addEventListener( 'dispose', onMaterialDispose );
  17667. } else if ( program.code !== code ) {
  17668. // changed glsl or parameters
  17669. releaseMaterialProgramReference( material );
  17670. } else if ( parameters.shaderID !== undefined ) {
  17671. // same glsl and uniform list
  17672. return;
  17673. } else {
  17674. // only rebuild uniform list
  17675. programChange = false;
  17676. }
  17677. if ( programChange ) {
  17678. if ( parameters.shaderID ) {
  17679. var shader = ShaderLib[ parameters.shaderID ];
  17680. materialProperties.shader = {
  17681. name: material.type,
  17682. uniforms: UniformsUtils.clone( shader.uniforms ),
  17683. vertexShader: shader.vertexShader,
  17684. fragmentShader: shader.fragmentShader
  17685. };
  17686. } else {
  17687. materialProperties.shader = {
  17688. name: material.type,
  17689. uniforms: material.uniforms,
  17690. vertexShader: material.vertexShader,
  17691. fragmentShader: material.fragmentShader
  17692. };
  17693. }
  17694. material.onBeforeCompile( materialProperties.shader );
  17695. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  17696. materialProperties.program = program;
  17697. material.program = program;
  17698. }
  17699. var programAttributes = program.getAttributes();
  17700. if ( material.morphTargets ) {
  17701. material.numSupportedMorphTargets = 0;
  17702. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  17703. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  17704. material.numSupportedMorphTargets ++;
  17705. }
  17706. }
  17707. }
  17708. if ( material.morphNormals ) {
  17709. material.numSupportedMorphNormals = 0;
  17710. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  17711. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  17712. material.numSupportedMorphNormals ++;
  17713. }
  17714. }
  17715. }
  17716. var uniforms = materialProperties.shader.uniforms;
  17717. if ( ! material.isShaderMaterial &&
  17718. ! material.isRawShaderMaterial ||
  17719. material.clipping === true ) {
  17720. materialProperties.numClippingPlanes = _clipping.numPlanes;
  17721. materialProperties.numIntersection = _clipping.numIntersection;
  17722. uniforms.clippingPlanes = _clipping.uniform;
  17723. }
  17724. materialProperties.fog = fog;
  17725. // store the light setup it was created for
  17726. materialProperties.lightsHash = lights.state.hash;
  17727. if ( material.lights ) {
  17728. // wire up the material to this renderer's lighting state
  17729. uniforms.ambientLightColor.value = lights.state.ambient;
  17730. uniforms.directionalLights.value = lights.state.directional;
  17731. uniforms.spotLights.value = lights.state.spot;
  17732. uniforms.rectAreaLights.value = lights.state.rectArea;
  17733. uniforms.pointLights.value = lights.state.point;
  17734. uniforms.hemisphereLights.value = lights.state.hemi;
  17735. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17736. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17737. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17738. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  17739. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17740. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17741. // TODO (abelnation): add area lights shadow info to uniforms
  17742. }
  17743. var progUniforms = materialProperties.program.getUniforms(),
  17744. uniformsList =
  17745. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17746. materialProperties.uniformsList = uniformsList;
  17747. }
  17748. function setProgram( camera, fog, material, object ) {
  17749. _usedTextureUnits = 0;
  17750. var materialProperties = properties.get( material );
  17751. if ( _clippingEnabled ) {
  17752. if ( _localClippingEnabled || camera !== _currentCamera ) {
  17753. var useCache =
  17754. camera === _currentCamera &&
  17755. material.id === _currentMaterialId;
  17756. // we might want to call this function with some ClippingGroup
  17757. // object instead of the material, once it becomes feasible
  17758. // (#8465, #8379)
  17759. _clipping.setState(
  17760. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  17761. camera, materialProperties, useCache );
  17762. }
  17763. }
  17764. if ( material.needsUpdate === false ) {
  17765. if ( materialProperties.program === undefined ) {
  17766. material.needsUpdate = true;
  17767. } else if ( material.fog && materialProperties.fog !== fog ) {
  17768. material.needsUpdate = true;
  17769. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  17770. material.needsUpdate = true;
  17771. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17772. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  17773. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  17774. material.needsUpdate = true;
  17775. }
  17776. }
  17777. if ( material.needsUpdate ) {
  17778. initMaterial( material, fog, object );
  17779. material.needsUpdate = false;
  17780. }
  17781. var refreshProgram = false;
  17782. var refreshMaterial = false;
  17783. var refreshLights = false;
  17784. var program = materialProperties.program,
  17785. p_uniforms = program.getUniforms(),
  17786. m_uniforms = materialProperties.shader.uniforms;
  17787. if ( state.useProgram( program.program ) ) {
  17788. refreshProgram = true;
  17789. refreshMaterial = true;
  17790. refreshLights = true;
  17791. }
  17792. if ( material.id !== _currentMaterialId ) {
  17793. _currentMaterialId = material.id;
  17794. refreshMaterial = true;
  17795. }
  17796. if ( refreshProgram || camera !== _currentCamera ) {
  17797. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17798. if ( capabilities.logarithmicDepthBuffer ) {
  17799. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17800. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17801. }
  17802. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  17803. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  17804. _currentCamera = ( _currentArrayCamera || camera );
  17805. // lighting uniforms depend on the camera so enforce an update
  17806. // now, in case this material supports lights - or later, when
  17807. // the next material that does gets activated:
  17808. refreshMaterial = true; // set to true on material change
  17809. refreshLights = true; // remains set until update done
  17810. }
  17811. // load material specific uniforms
  17812. // (shader material also gets them for the sake of genericity)
  17813. if ( material.isShaderMaterial ||
  17814. material.isMeshPhongMaterial ||
  17815. material.isMeshStandardMaterial ||
  17816. material.envMap ) {
  17817. var uCamPos = p_uniforms.map.cameraPosition;
  17818. if ( uCamPos !== undefined ) {
  17819. uCamPos.setValue( _gl,
  17820. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17821. }
  17822. }
  17823. if ( material.isMeshPhongMaterial ||
  17824. material.isMeshLambertMaterial ||
  17825. material.isMeshBasicMaterial ||
  17826. material.isMeshStandardMaterial ||
  17827. material.isShaderMaterial ||
  17828. material.skinning ) {
  17829. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17830. }
  17831. }
  17832. // skinning uniforms must be set even if material didn't change
  17833. // auto-setting of texture unit for bone texture must go before other textures
  17834. // not sure why, but otherwise weird things happen
  17835. if ( material.skinning ) {
  17836. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17837. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17838. var skeleton = object.skeleton;
  17839. if ( skeleton ) {
  17840. var bones = skeleton.bones;
  17841. if ( capabilities.floatVertexTextures ) {
  17842. if ( skeleton.boneTexture === undefined ) {
  17843. // layout (1 matrix = 4 pixels)
  17844. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17845. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17846. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17847. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17848. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17849. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  17850. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  17851. size = Math.max( size, 4 );
  17852. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17853. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  17854. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17855. skeleton.boneMatrices = boneMatrices;
  17856. skeleton.boneTexture = boneTexture;
  17857. skeleton.boneTextureSize = size;
  17858. }
  17859. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  17860. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17861. } else {
  17862. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  17863. }
  17864. }
  17865. }
  17866. if ( refreshMaterial ) {
  17867. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17868. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  17869. if ( material.lights ) {
  17870. // the current material requires lighting info
  17871. // note: all lighting uniforms are always set correctly
  17872. // they simply reference the renderer's state for their
  17873. // values
  17874. //
  17875. // use the current material's .needsUpdate flags to set
  17876. // the GL state when required
  17877. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17878. }
  17879. // refresh uniforms common to several materials
  17880. if ( fog && material.fog ) {
  17881. refreshUniformsFog( m_uniforms, fog );
  17882. }
  17883. if ( material.isMeshBasicMaterial ) {
  17884. refreshUniformsCommon( m_uniforms, material );
  17885. } else if ( material.isMeshLambertMaterial ) {
  17886. refreshUniformsCommon( m_uniforms, material );
  17887. refreshUniformsLambert( m_uniforms, material );
  17888. } else if ( material.isMeshPhongMaterial ) {
  17889. refreshUniformsCommon( m_uniforms, material );
  17890. if ( material.isMeshToonMaterial ) {
  17891. refreshUniformsToon( m_uniforms, material );
  17892. } else {
  17893. refreshUniformsPhong( m_uniforms, material );
  17894. }
  17895. } else if ( material.isMeshStandardMaterial ) {
  17896. refreshUniformsCommon( m_uniforms, material );
  17897. if ( material.isMeshPhysicalMaterial ) {
  17898. refreshUniformsPhysical( m_uniforms, material );
  17899. } else {
  17900. refreshUniformsStandard( m_uniforms, material );
  17901. }
  17902. } else if ( material.isMeshDepthMaterial ) {
  17903. refreshUniformsCommon( m_uniforms, material );
  17904. refreshUniformsDepth( m_uniforms, material );
  17905. } else if ( material.isMeshDistanceMaterial ) {
  17906. refreshUniformsCommon( m_uniforms, material );
  17907. refreshUniformsDistance( m_uniforms, material );
  17908. } else if ( material.isMeshNormalMaterial ) {
  17909. refreshUniformsCommon( m_uniforms, material );
  17910. refreshUniformsNormal( m_uniforms, material );
  17911. } else if ( material.isLineBasicMaterial ) {
  17912. refreshUniformsLine( m_uniforms, material );
  17913. if ( material.isLineDashedMaterial ) {
  17914. refreshUniformsDash( m_uniforms, material );
  17915. }
  17916. } else if ( material.isPointsMaterial ) {
  17917. refreshUniformsPoints( m_uniforms, material );
  17918. } else if ( material.isShadowMaterial ) {
  17919. m_uniforms.color.value = material.color;
  17920. m_uniforms.opacity.value = material.opacity;
  17921. }
  17922. // RectAreaLight Texture
  17923. // TODO (mrdoob): Find a nicer implementation
  17924. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  17925. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  17926. WebGLUniforms.upload(
  17927. _gl, materialProperties.uniformsList, m_uniforms, _this );
  17928. }
  17929. // common matrices
  17930. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17931. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17932. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17933. return program;
  17934. }
  17935. // Uniforms (refresh uniforms objects)
  17936. function refreshUniformsCommon( uniforms, material ) {
  17937. uniforms.opacity.value = material.opacity;
  17938. if ( material.color ) {
  17939. uniforms.diffuse.value = material.color;
  17940. }
  17941. if ( material.emissive ) {
  17942. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  17943. }
  17944. if ( material.map ) {
  17945. uniforms.map.value = material.map;
  17946. }
  17947. if ( material.alphaMap ) {
  17948. uniforms.alphaMap.value = material.alphaMap;
  17949. }
  17950. if ( material.specularMap ) {
  17951. uniforms.specularMap.value = material.specularMap;
  17952. }
  17953. if ( material.envMap ) {
  17954. uniforms.envMap.value = material.envMap;
  17955. // don't flip CubeTexture envMaps, flip everything else:
  17956. // WebGLRenderTargetCube will be flipped for backwards compatibility
  17957. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  17958. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  17959. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  17960. uniforms.reflectivity.value = material.reflectivity;
  17961. uniforms.refractionRatio.value = material.refractionRatio;
  17962. }
  17963. if ( material.lightMap ) {
  17964. uniforms.lightMap.value = material.lightMap;
  17965. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  17966. }
  17967. if ( material.aoMap ) {
  17968. uniforms.aoMap.value = material.aoMap;
  17969. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  17970. }
  17971. // uv repeat and offset setting priorities
  17972. // 1. color map
  17973. // 2. specular map
  17974. // 3. normal map
  17975. // 4. bump map
  17976. // 5. alpha map
  17977. // 6. emissive map
  17978. var uvScaleMap;
  17979. if ( material.map ) {
  17980. uvScaleMap = material.map;
  17981. } else if ( material.specularMap ) {
  17982. uvScaleMap = material.specularMap;
  17983. } else if ( material.displacementMap ) {
  17984. uvScaleMap = material.displacementMap;
  17985. } else if ( material.normalMap ) {
  17986. uvScaleMap = material.normalMap;
  17987. } else if ( material.bumpMap ) {
  17988. uvScaleMap = material.bumpMap;
  17989. } else if ( material.roughnessMap ) {
  17990. uvScaleMap = material.roughnessMap;
  17991. } else if ( material.metalnessMap ) {
  17992. uvScaleMap = material.metalnessMap;
  17993. } else if ( material.alphaMap ) {
  17994. uvScaleMap = material.alphaMap;
  17995. } else if ( material.emissiveMap ) {
  17996. uvScaleMap = material.emissiveMap;
  17997. }
  17998. if ( uvScaleMap !== undefined ) {
  17999. // backwards compatibility
  18000. if ( uvScaleMap.isWebGLRenderTarget ) {
  18001. uvScaleMap = uvScaleMap.texture;
  18002. }
  18003. var offset = uvScaleMap.offset;
  18004. var repeat = uvScaleMap.repeat;
  18005. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  18006. }
  18007. }
  18008. function refreshUniformsLine( uniforms, material ) {
  18009. uniforms.diffuse.value = material.color;
  18010. uniforms.opacity.value = material.opacity;
  18011. }
  18012. function refreshUniformsDash( uniforms, material ) {
  18013. uniforms.dashSize.value = material.dashSize;
  18014. uniforms.totalSize.value = material.dashSize + material.gapSize;
  18015. uniforms.scale.value = material.scale;
  18016. }
  18017. function refreshUniformsPoints( uniforms, material ) {
  18018. uniforms.diffuse.value = material.color;
  18019. uniforms.opacity.value = material.opacity;
  18020. uniforms.size.value = material.size * _pixelRatio;
  18021. uniforms.scale.value = _height * 0.5;
  18022. uniforms.map.value = material.map;
  18023. if ( material.map !== null ) {
  18024. var offset = material.map.offset;
  18025. var repeat = material.map.repeat;
  18026. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  18027. }
  18028. }
  18029. function refreshUniformsFog( uniforms, fog ) {
  18030. uniforms.fogColor.value = fog.color;
  18031. if ( fog.isFog ) {
  18032. uniforms.fogNear.value = fog.near;
  18033. uniforms.fogFar.value = fog.far;
  18034. } else if ( fog.isFogExp2 ) {
  18035. uniforms.fogDensity.value = fog.density;
  18036. }
  18037. }
  18038. function refreshUniformsLambert( uniforms, material ) {
  18039. if ( material.emissiveMap ) {
  18040. uniforms.emissiveMap.value = material.emissiveMap;
  18041. }
  18042. }
  18043. function refreshUniformsPhong( uniforms, material ) {
  18044. uniforms.specular.value = material.specular;
  18045. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  18046. if ( material.emissiveMap ) {
  18047. uniforms.emissiveMap.value = material.emissiveMap;
  18048. }
  18049. if ( material.bumpMap ) {
  18050. uniforms.bumpMap.value = material.bumpMap;
  18051. uniforms.bumpScale.value = material.bumpScale;
  18052. }
  18053. if ( material.normalMap ) {
  18054. uniforms.normalMap.value = material.normalMap;
  18055. uniforms.normalScale.value.copy( material.normalScale );
  18056. }
  18057. if ( material.displacementMap ) {
  18058. uniforms.displacementMap.value = material.displacementMap;
  18059. uniforms.displacementScale.value = material.displacementScale;
  18060. uniforms.displacementBias.value = material.displacementBias;
  18061. }
  18062. }
  18063. function refreshUniformsToon( uniforms, material ) {
  18064. refreshUniformsPhong( uniforms, material );
  18065. if ( material.gradientMap ) {
  18066. uniforms.gradientMap.value = material.gradientMap;
  18067. }
  18068. }
  18069. function refreshUniformsStandard( uniforms, material ) {
  18070. uniforms.roughness.value = material.roughness;
  18071. uniforms.metalness.value = material.metalness;
  18072. if ( material.roughnessMap ) {
  18073. uniforms.roughnessMap.value = material.roughnessMap;
  18074. }
  18075. if ( material.metalnessMap ) {
  18076. uniforms.metalnessMap.value = material.metalnessMap;
  18077. }
  18078. if ( material.emissiveMap ) {
  18079. uniforms.emissiveMap.value = material.emissiveMap;
  18080. }
  18081. if ( material.bumpMap ) {
  18082. uniforms.bumpMap.value = material.bumpMap;
  18083. uniforms.bumpScale.value = material.bumpScale;
  18084. }
  18085. if ( material.normalMap ) {
  18086. uniforms.normalMap.value = material.normalMap;
  18087. uniforms.normalScale.value.copy( material.normalScale );
  18088. }
  18089. if ( material.displacementMap ) {
  18090. uniforms.displacementMap.value = material.displacementMap;
  18091. uniforms.displacementScale.value = material.displacementScale;
  18092. uniforms.displacementBias.value = material.displacementBias;
  18093. }
  18094. if ( material.envMap ) {
  18095. //uniforms.envMap.value = material.envMap; // part of uniforms common
  18096. uniforms.envMapIntensity.value = material.envMapIntensity;
  18097. }
  18098. }
  18099. function refreshUniformsPhysical( uniforms, material ) {
  18100. uniforms.clearCoat.value = material.clearCoat;
  18101. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  18102. refreshUniformsStandard( uniforms, material );
  18103. }
  18104. function refreshUniformsDepth( uniforms, material ) {
  18105. if ( material.displacementMap ) {
  18106. uniforms.displacementMap.value = material.displacementMap;
  18107. uniforms.displacementScale.value = material.displacementScale;
  18108. uniforms.displacementBias.value = material.displacementBias;
  18109. }
  18110. }
  18111. function refreshUniformsDistance( uniforms, material ) {
  18112. if ( material.displacementMap ) {
  18113. uniforms.displacementMap.value = material.displacementMap;
  18114. uniforms.displacementScale.value = material.displacementScale;
  18115. uniforms.displacementBias.value = material.displacementBias;
  18116. }
  18117. uniforms.referencePosition.value.copy( material.referencePosition );
  18118. uniforms.nearDistance.value = material.nearDistance;
  18119. uniforms.farDistance.value = material.farDistance;
  18120. }
  18121. function refreshUniformsNormal( uniforms, material ) {
  18122. if ( material.bumpMap ) {
  18123. uniforms.bumpMap.value = material.bumpMap;
  18124. uniforms.bumpScale.value = material.bumpScale;
  18125. }
  18126. if ( material.normalMap ) {
  18127. uniforms.normalMap.value = material.normalMap;
  18128. uniforms.normalScale.value.copy( material.normalScale );
  18129. }
  18130. if ( material.displacementMap ) {
  18131. uniforms.displacementMap.value = material.displacementMap;
  18132. uniforms.displacementScale.value = material.displacementScale;
  18133. uniforms.displacementBias.value = material.displacementBias;
  18134. }
  18135. }
  18136. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18137. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18138. uniforms.ambientLightColor.needsUpdate = value;
  18139. uniforms.directionalLights.needsUpdate = value;
  18140. uniforms.pointLights.needsUpdate = value;
  18141. uniforms.spotLights.needsUpdate = value;
  18142. uniforms.rectAreaLights.needsUpdate = value;
  18143. uniforms.hemisphereLights.needsUpdate = value;
  18144. }
  18145. // GL state setting
  18146. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  18147. state.setCullFace( cullFace );
  18148. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  18149. };
  18150. // Textures
  18151. function allocTextureUnit() {
  18152. var textureUnit = _usedTextureUnits;
  18153. if ( textureUnit >= capabilities.maxTextures ) {
  18154. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  18155. }
  18156. _usedTextureUnits += 1;
  18157. return textureUnit;
  18158. }
  18159. this.allocTextureUnit = allocTextureUnit;
  18160. // this.setTexture2D = setTexture2D;
  18161. this.setTexture2D = ( function () {
  18162. var warned = false;
  18163. // backwards compatibility: peel texture.texture
  18164. return function setTexture2D( texture, slot ) {
  18165. if ( texture && texture.isWebGLRenderTarget ) {
  18166. if ( ! warned ) {
  18167. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  18168. warned = true;
  18169. }
  18170. texture = texture.texture;
  18171. }
  18172. textures.setTexture2D( texture, slot );
  18173. };
  18174. }() );
  18175. this.setTexture = ( function () {
  18176. var warned = false;
  18177. return function setTexture( texture, slot ) {
  18178. if ( ! warned ) {
  18179. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  18180. warned = true;
  18181. }
  18182. textures.setTexture2D( texture, slot );
  18183. };
  18184. }() );
  18185. this.setTextureCube = ( function () {
  18186. var warned = false;
  18187. return function setTextureCube( texture, slot ) {
  18188. // backwards compatibility: peel texture.texture
  18189. if ( texture && texture.isWebGLRenderTargetCube ) {
  18190. if ( ! warned ) {
  18191. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  18192. warned = true;
  18193. }
  18194. texture = texture.texture;
  18195. }
  18196. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  18197. // TODO: unify these code paths
  18198. if ( ( texture && texture.isCubeTexture ) ||
  18199. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  18200. // CompressedTexture can have Array in image :/
  18201. // this function alone should take care of cube textures
  18202. textures.setTextureCube( texture, slot );
  18203. } else {
  18204. // assumed: texture property of THREE.WebGLRenderTargetCube
  18205. textures.setTextureCubeDynamic( texture, slot );
  18206. }
  18207. };
  18208. }() );
  18209. this.getRenderTarget = function () {
  18210. return _currentRenderTarget;
  18211. };
  18212. this.setRenderTarget = function ( renderTarget ) {
  18213. _currentRenderTarget = renderTarget;
  18214. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  18215. textures.setupRenderTarget( renderTarget );
  18216. }
  18217. var framebuffer = null;
  18218. var isCube = false;
  18219. if ( renderTarget ) {
  18220. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18221. if ( renderTarget.isWebGLRenderTargetCube ) {
  18222. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  18223. isCube = true;
  18224. } else {
  18225. framebuffer = __webglFramebuffer;
  18226. }
  18227. _currentViewport.copy( renderTarget.viewport );
  18228. _currentScissor.copy( renderTarget.scissor );
  18229. _currentScissorTest = renderTarget.scissorTest;
  18230. } else {
  18231. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  18232. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  18233. _currentScissorTest = _scissorTest;
  18234. }
  18235. if ( _currentFramebuffer !== framebuffer ) {
  18236. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18237. _currentFramebuffer = framebuffer;
  18238. }
  18239. state.viewport( _currentViewport );
  18240. state.scissor( _currentScissor );
  18241. state.setScissorTest( _currentScissorTest );
  18242. if ( isCube ) {
  18243. var textureProperties = properties.get( renderTarget.texture );
  18244. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  18245. }
  18246. };
  18247. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  18248. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18249. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18250. return;
  18251. }
  18252. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18253. if ( framebuffer ) {
  18254. var restore = false;
  18255. if ( framebuffer !== _currentFramebuffer ) {
  18256. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18257. restore = true;
  18258. }
  18259. try {
  18260. var texture = renderTarget.texture;
  18261. var textureFormat = texture.format;
  18262. var textureType = texture.type;
  18263. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18264. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18265. return;
  18266. }
  18267. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  18268. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18269. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  18270. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18271. return;
  18272. }
  18273. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  18274. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18275. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18276. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18277. }
  18278. } else {
  18279. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  18280. }
  18281. } finally {
  18282. if ( restore ) {
  18283. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  18284. }
  18285. }
  18286. }
  18287. };
  18288. }
  18289. /**
  18290. * @author mrdoob / http://mrdoob.com/
  18291. * @author alteredq / http://alteredqualia.com/
  18292. */
  18293. function FogExp2 ( color, density ) {
  18294. this.name = '';
  18295. this.color = new Color( color );
  18296. this.density = ( density !== undefined ) ? density : 0.00025;
  18297. }
  18298. FogExp2.prototype.isFogExp2 = true;
  18299. FogExp2.prototype.clone = function () {
  18300. return new FogExp2( this.color.getHex(), this.density );
  18301. };
  18302. FogExp2.prototype.toJSON = function ( meta ) {
  18303. return {
  18304. type: 'FogExp2',
  18305. color: this.color.getHex(),
  18306. density: this.density
  18307. };
  18308. };
  18309. /**
  18310. * @author mrdoob / http://mrdoob.com/
  18311. * @author alteredq / http://alteredqualia.com/
  18312. */
  18313. function Fog ( color, near, far ) {
  18314. this.name = '';
  18315. this.color = new Color( color );
  18316. this.near = ( near !== undefined ) ? near : 1;
  18317. this.far = ( far !== undefined ) ? far : 1000;
  18318. }
  18319. Fog.prototype.isFog = true;
  18320. Fog.prototype.clone = function () {
  18321. return new Fog( this.color.getHex(), this.near, this.far );
  18322. };
  18323. Fog.prototype.toJSON = function ( meta ) {
  18324. return {
  18325. type: 'Fog',
  18326. color: this.color.getHex(),
  18327. near: this.near,
  18328. far: this.far
  18329. };
  18330. };
  18331. /**
  18332. * @author mrdoob / http://mrdoob.com/
  18333. */
  18334. function Scene () {
  18335. Object3D.call( this );
  18336. this.type = 'Scene';
  18337. this.background = null;
  18338. this.fog = null;
  18339. this.overrideMaterial = null;
  18340. this.autoUpdate = true; // checked by the renderer
  18341. }
  18342. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18343. constructor: Scene,
  18344. copy: function ( source, recursive ) {
  18345. Object3D.prototype.copy.call( this, source, recursive );
  18346. if ( source.background !== null ) this.background = source.background.clone();
  18347. if ( source.fog !== null ) this.fog = source.fog.clone();
  18348. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18349. this.autoUpdate = source.autoUpdate;
  18350. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18351. return this;
  18352. },
  18353. toJSON: function ( meta ) {
  18354. var data = Object3D.prototype.toJSON.call( this, meta );
  18355. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  18356. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18357. return data;
  18358. }
  18359. } );
  18360. /**
  18361. * @author mikael emtinger / http://gomo.se/
  18362. * @author alteredq / http://alteredqualia.com/
  18363. */
  18364. function LensFlare( texture, size, distance, blending, color ) {
  18365. Object3D.call( this );
  18366. this.lensFlares = [];
  18367. this.positionScreen = new Vector3();
  18368. this.customUpdateCallback = undefined;
  18369. if ( texture !== undefined ) {
  18370. this.add( texture, size, distance, blending, color );
  18371. }
  18372. }
  18373. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18374. constructor: LensFlare,
  18375. isLensFlare: true,
  18376. copy: function ( source ) {
  18377. Object3D.prototype.copy.call( this, source );
  18378. this.positionScreen.copy( source.positionScreen );
  18379. this.customUpdateCallback = source.customUpdateCallback;
  18380. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  18381. this.lensFlares.push( source.lensFlares[ i ] );
  18382. }
  18383. return this;
  18384. },
  18385. add: function ( texture, size, distance, blending, color, opacity ) {
  18386. if ( size === undefined ) size = - 1;
  18387. if ( distance === undefined ) distance = 0;
  18388. if ( opacity === undefined ) opacity = 1;
  18389. if ( color === undefined ) color = new Color( 0xffffff );
  18390. if ( blending === undefined ) blending = NormalBlending;
  18391. distance = Math.min( distance, Math.max( 0, distance ) );
  18392. this.lensFlares.push( {
  18393. texture: texture, // THREE.Texture
  18394. size: size, // size in pixels (-1 = use texture.width)
  18395. distance: distance, // distance (0-1) from light source (0=at light source)
  18396. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  18397. scale: 1, // scale
  18398. rotation: 0, // rotation
  18399. opacity: opacity, // opacity
  18400. color: color, // color
  18401. blending: blending // blending
  18402. } );
  18403. },
  18404. /*
  18405. * Update lens flares update positions on all flares based on the screen position
  18406. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  18407. */
  18408. updateLensFlares: function () {
  18409. var f, fl = this.lensFlares.length;
  18410. var flare;
  18411. var vecX = - this.positionScreen.x * 2;
  18412. var vecY = - this.positionScreen.y * 2;
  18413. for ( f = 0; f < fl; f ++ ) {
  18414. flare = this.lensFlares[ f ];
  18415. flare.x = this.positionScreen.x + vecX * flare.distance;
  18416. flare.y = this.positionScreen.y + vecY * flare.distance;
  18417. flare.wantedRotation = flare.x * Math.PI * 0.25;
  18418. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  18419. }
  18420. }
  18421. } );
  18422. /**
  18423. * @author alteredq / http://alteredqualia.com/
  18424. *
  18425. * parameters = {
  18426. * color: <hex>,
  18427. * opacity: <float>,
  18428. * map: new THREE.Texture( <Image> ),
  18429. *
  18430. * uvOffset: new THREE.Vector2(),
  18431. * uvScale: new THREE.Vector2()
  18432. * }
  18433. */
  18434. function SpriteMaterial( parameters ) {
  18435. Material.call( this );
  18436. this.type = 'SpriteMaterial';
  18437. this.color = new Color( 0xffffff );
  18438. this.map = null;
  18439. this.rotation = 0;
  18440. this.fog = false;
  18441. this.lights = false;
  18442. this.setValues( parameters );
  18443. }
  18444. SpriteMaterial.prototype = Object.create( Material.prototype );
  18445. SpriteMaterial.prototype.constructor = SpriteMaterial;
  18446. SpriteMaterial.prototype.isSpriteMaterial = true;
  18447. SpriteMaterial.prototype.copy = function ( source ) {
  18448. Material.prototype.copy.call( this, source );
  18449. this.color.copy( source.color );
  18450. this.map = source.map;
  18451. this.rotation = source.rotation;
  18452. return this;
  18453. };
  18454. /**
  18455. * @author mikael emtinger / http://gomo.se/
  18456. * @author alteredq / http://alteredqualia.com/
  18457. */
  18458. function Sprite( material ) {
  18459. Object3D.call( this );
  18460. this.type = 'Sprite';
  18461. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18462. }
  18463. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18464. constructor: Sprite,
  18465. isSprite: true,
  18466. raycast: ( function () {
  18467. var intersectPoint = new Vector3();
  18468. var worldPosition = new Vector3();
  18469. var worldScale = new Vector3();
  18470. return function raycast( raycaster, intersects ) {
  18471. worldPosition.setFromMatrixPosition( this.matrixWorld );
  18472. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  18473. worldScale.setFromMatrixScale( this.matrixWorld );
  18474. var guessSizeSq = worldScale.x * worldScale.y / 4;
  18475. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  18476. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18477. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18478. intersects.push( {
  18479. distance: distance,
  18480. point: intersectPoint.clone(),
  18481. face: null,
  18482. object: this
  18483. } );
  18484. };
  18485. }() ),
  18486. clone: function () {
  18487. return new this.constructor( this.material ).copy( this );
  18488. }
  18489. } );
  18490. /**
  18491. * @author mikael emtinger / http://gomo.se/
  18492. * @author alteredq / http://alteredqualia.com/
  18493. * @author mrdoob / http://mrdoob.com/
  18494. */
  18495. function LOD() {
  18496. Object3D.call( this );
  18497. this.type = 'LOD';
  18498. Object.defineProperties( this, {
  18499. levels: {
  18500. enumerable: true,
  18501. value: []
  18502. }
  18503. } );
  18504. }
  18505. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18506. constructor: LOD,
  18507. copy: function ( source ) {
  18508. Object3D.prototype.copy.call( this, source, false );
  18509. var levels = source.levels;
  18510. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18511. var level = levels[ i ];
  18512. this.addLevel( level.object.clone(), level.distance );
  18513. }
  18514. return this;
  18515. },
  18516. addLevel: function ( object, distance ) {
  18517. if ( distance === undefined ) distance = 0;
  18518. distance = Math.abs( distance );
  18519. var levels = this.levels;
  18520. for ( var l = 0; l < levels.length; l ++ ) {
  18521. if ( distance < levels[ l ].distance ) {
  18522. break;
  18523. }
  18524. }
  18525. levels.splice( l, 0, { distance: distance, object: object } );
  18526. this.add( object );
  18527. },
  18528. getObjectForDistance: function ( distance ) {
  18529. var levels = this.levels;
  18530. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18531. if ( distance < levels[ i ].distance ) {
  18532. break;
  18533. }
  18534. }
  18535. return levels[ i - 1 ].object;
  18536. },
  18537. raycast: ( function () {
  18538. var matrixPosition = new Vector3();
  18539. return function raycast( raycaster, intersects ) {
  18540. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18541. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  18542. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18543. };
  18544. }() ),
  18545. update: function () {
  18546. var v1 = new Vector3();
  18547. var v2 = new Vector3();
  18548. return function update( camera ) {
  18549. var levels = this.levels;
  18550. if ( levels.length > 1 ) {
  18551. v1.setFromMatrixPosition( camera.matrixWorld );
  18552. v2.setFromMatrixPosition( this.matrixWorld );
  18553. var distance = v1.distanceTo( v2 );
  18554. levels[ 0 ].object.visible = true;
  18555. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18556. if ( distance >= levels[ i ].distance ) {
  18557. levels[ i - 1 ].object.visible = false;
  18558. levels[ i ].object.visible = true;
  18559. } else {
  18560. break;
  18561. }
  18562. }
  18563. for ( ; i < l; i ++ ) {
  18564. levels[ i ].object.visible = false;
  18565. }
  18566. }
  18567. };
  18568. }(),
  18569. toJSON: function ( meta ) {
  18570. var data = Object3D.prototype.toJSON.call( this, meta );
  18571. data.object.levels = [];
  18572. var levels = this.levels;
  18573. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18574. var level = levels[ i ];
  18575. data.object.levels.push( {
  18576. object: level.object.uuid,
  18577. distance: level.distance
  18578. } );
  18579. }
  18580. return data;
  18581. }
  18582. } );
  18583. /**
  18584. * @author mikael emtinger / http://gomo.se/
  18585. * @author alteredq / http://alteredqualia.com/
  18586. * @author michael guerrero / http://realitymeltdown.com
  18587. * @author ikerr / http://verold.com
  18588. */
  18589. function Skeleton( bones, boneInverses ) {
  18590. // copy the bone array
  18591. bones = bones || [];
  18592. this.bones = bones.slice( 0 );
  18593. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  18594. // use the supplied bone inverses or calculate the inverses
  18595. if ( boneInverses === undefined ) {
  18596. this.calculateInverses();
  18597. } else {
  18598. if ( this.bones.length === boneInverses.length ) {
  18599. this.boneInverses = boneInverses.slice( 0 );
  18600. } else {
  18601. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  18602. this.boneInverses = [];
  18603. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18604. this.boneInverses.push( new Matrix4() );
  18605. }
  18606. }
  18607. }
  18608. }
  18609. Object.assign( Skeleton.prototype, {
  18610. calculateInverses: function () {
  18611. this.boneInverses = [];
  18612. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18613. var inverse = new Matrix4();
  18614. if ( this.bones[ i ] ) {
  18615. inverse.getInverse( this.bones[ i ].matrixWorld );
  18616. }
  18617. this.boneInverses.push( inverse );
  18618. }
  18619. },
  18620. pose: function () {
  18621. var bone, i, il;
  18622. // recover the bind-time world matrices
  18623. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18624. bone = this.bones[ i ];
  18625. if ( bone ) {
  18626. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  18627. }
  18628. }
  18629. // compute the local matrices, positions, rotations and scales
  18630. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18631. bone = this.bones[ i ];
  18632. if ( bone ) {
  18633. if ( bone.parent && bone.parent.isBone ) {
  18634. bone.matrix.getInverse( bone.parent.matrixWorld );
  18635. bone.matrix.multiply( bone.matrixWorld );
  18636. } else {
  18637. bone.matrix.copy( bone.matrixWorld );
  18638. }
  18639. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18640. }
  18641. }
  18642. },
  18643. update: ( function () {
  18644. var offsetMatrix = new Matrix4();
  18645. var identityMatrix = new Matrix4();
  18646. return function update() {
  18647. var bones = this.bones;
  18648. var boneInverses = this.boneInverses;
  18649. var boneMatrices = this.boneMatrices;
  18650. var boneTexture = this.boneTexture;
  18651. // flatten bone matrices to array
  18652. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  18653. // compute the offset between the current and the original transform
  18654. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  18655. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18656. offsetMatrix.toArray( boneMatrices, i * 16 );
  18657. }
  18658. if ( boneTexture !== undefined ) {
  18659. boneTexture.needsUpdate = true;
  18660. }
  18661. };
  18662. } )(),
  18663. clone: function () {
  18664. return new Skeleton( this.bones, this.boneInverses );
  18665. }
  18666. } );
  18667. /**
  18668. * @author mikael emtinger / http://gomo.se/
  18669. * @author alteredq / http://alteredqualia.com/
  18670. * @author ikerr / http://verold.com
  18671. */
  18672. function Bone() {
  18673. Object3D.call( this );
  18674. this.type = 'Bone';
  18675. }
  18676. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18677. constructor: Bone,
  18678. isBone: true
  18679. } );
  18680. /**
  18681. * @author mikael emtinger / http://gomo.se/
  18682. * @author alteredq / http://alteredqualia.com/
  18683. * @author ikerr / http://verold.com
  18684. */
  18685. function SkinnedMesh( geometry, material ) {
  18686. Mesh.call( this, geometry, material );
  18687. this.type = 'SkinnedMesh';
  18688. this.bindMode = 'attached';
  18689. this.bindMatrix = new Matrix4();
  18690. this.bindMatrixInverse = new Matrix4();
  18691. var bones = this.initBones();
  18692. var skeleton = new Skeleton( bones );
  18693. this.bind( skeleton, this.matrixWorld );
  18694. this.normalizeSkinWeights();
  18695. }
  18696. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18697. constructor: SkinnedMesh,
  18698. isSkinnedMesh: true,
  18699. initBones: function () {
  18700. var bones = [], bone, gbone;
  18701. var i, il;
  18702. if ( this.geometry && this.geometry.bones !== undefined ) {
  18703. // first, create array of 'Bone' objects from geometry data
  18704. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18705. gbone = this.geometry.bones[ i ];
  18706. // create new 'Bone' object
  18707. bone = new Bone();
  18708. bones.push( bone );
  18709. // apply values
  18710. bone.name = gbone.name;
  18711. bone.position.fromArray( gbone.pos );
  18712. bone.quaternion.fromArray( gbone.rotq );
  18713. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  18714. }
  18715. // second, create bone hierarchy
  18716. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18717. gbone = this.geometry.bones[ i ];
  18718. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  18719. // subsequent bones in the hierarchy
  18720. bones[ gbone.parent ].add( bones[ i ] );
  18721. } else {
  18722. // topmost bone, immediate child of the skinned mesh
  18723. this.add( bones[ i ] );
  18724. }
  18725. }
  18726. }
  18727. // now the bones are part of the scene graph and children of the skinned mesh.
  18728. // let's update the corresponding matrices
  18729. this.updateMatrixWorld( true );
  18730. return bones;
  18731. },
  18732. bind: function ( skeleton, bindMatrix ) {
  18733. this.skeleton = skeleton;
  18734. if ( bindMatrix === undefined ) {
  18735. this.updateMatrixWorld( true );
  18736. this.skeleton.calculateInverses();
  18737. bindMatrix = this.matrixWorld;
  18738. }
  18739. this.bindMatrix.copy( bindMatrix );
  18740. this.bindMatrixInverse.getInverse( bindMatrix );
  18741. },
  18742. pose: function () {
  18743. this.skeleton.pose();
  18744. },
  18745. normalizeSkinWeights: function () {
  18746. var scale, i;
  18747. if ( this.geometry && this.geometry.isGeometry ) {
  18748. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  18749. var sw = this.geometry.skinWeights[ i ];
  18750. scale = 1.0 / sw.lengthManhattan();
  18751. if ( scale !== Infinity ) {
  18752. sw.multiplyScalar( scale );
  18753. } else {
  18754. sw.set( 1, 0, 0, 0 ); // do something reasonable
  18755. }
  18756. }
  18757. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  18758. var vec = new Vector4();
  18759. var skinWeight = this.geometry.attributes.skinWeight;
  18760. for ( i = 0; i < skinWeight.count; i ++ ) {
  18761. vec.x = skinWeight.getX( i );
  18762. vec.y = skinWeight.getY( i );
  18763. vec.z = skinWeight.getZ( i );
  18764. vec.w = skinWeight.getW( i );
  18765. scale = 1.0 / vec.lengthManhattan();
  18766. if ( scale !== Infinity ) {
  18767. vec.multiplyScalar( scale );
  18768. } else {
  18769. vec.set( 1, 0, 0, 0 ); // do something reasonable
  18770. }
  18771. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  18772. }
  18773. }
  18774. },
  18775. updateMatrixWorld: function ( force ) {
  18776. Mesh.prototype.updateMatrixWorld.call( this, force );
  18777. if ( this.bindMode === 'attached' ) {
  18778. this.bindMatrixInverse.getInverse( this.matrixWorld );
  18779. } else if ( this.bindMode === 'detached' ) {
  18780. this.bindMatrixInverse.getInverse( this.bindMatrix );
  18781. } else {
  18782. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18783. }
  18784. },
  18785. clone: function () {
  18786. return new this.constructor( this.geometry, this.material ).copy( this );
  18787. }
  18788. } );
  18789. /**
  18790. * @author mrdoob / http://mrdoob.com/
  18791. * @author alteredq / http://alteredqualia.com/
  18792. *
  18793. * parameters = {
  18794. * color: <hex>,
  18795. * opacity: <float>,
  18796. *
  18797. * linewidth: <float>,
  18798. * linecap: "round",
  18799. * linejoin: "round"
  18800. * }
  18801. */
  18802. function LineBasicMaterial( parameters ) {
  18803. Material.call( this );
  18804. this.type = 'LineBasicMaterial';
  18805. this.color = new Color( 0xffffff );
  18806. this.linewidth = 1;
  18807. this.linecap = 'round';
  18808. this.linejoin = 'round';
  18809. this.lights = false;
  18810. this.setValues( parameters );
  18811. }
  18812. LineBasicMaterial.prototype = Object.create( Material.prototype );
  18813. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  18814. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  18815. LineBasicMaterial.prototype.copy = function ( source ) {
  18816. Material.prototype.copy.call( this, source );
  18817. this.color.copy( source.color );
  18818. this.linewidth = source.linewidth;
  18819. this.linecap = source.linecap;
  18820. this.linejoin = source.linejoin;
  18821. return this;
  18822. };
  18823. /**
  18824. * @author mrdoob / http://mrdoob.com/
  18825. */
  18826. function Line( geometry, material, mode ) {
  18827. if ( mode === 1 ) {
  18828. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  18829. return new LineSegments( geometry, material );
  18830. }
  18831. Object3D.call( this );
  18832. this.type = 'Line';
  18833. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18834. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  18835. }
  18836. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18837. constructor: Line,
  18838. isLine: true,
  18839. raycast: ( function () {
  18840. var inverseMatrix = new Matrix4();
  18841. var ray = new Ray();
  18842. var sphere = new Sphere();
  18843. return function raycast( raycaster, intersects ) {
  18844. var precision = raycaster.linePrecision;
  18845. var precisionSq = precision * precision;
  18846. var geometry = this.geometry;
  18847. var matrixWorld = this.matrixWorld;
  18848. // Checking boundingSphere distance to ray
  18849. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18850. sphere.copy( geometry.boundingSphere );
  18851. sphere.applyMatrix4( matrixWorld );
  18852. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18853. //
  18854. inverseMatrix.getInverse( matrixWorld );
  18855. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18856. var vStart = new Vector3();
  18857. var vEnd = new Vector3();
  18858. var interSegment = new Vector3();
  18859. var interRay = new Vector3();
  18860. var step = (this && this.isLineSegments) ? 2 : 1;
  18861. if ( geometry.isBufferGeometry ) {
  18862. var index = geometry.index;
  18863. var attributes = geometry.attributes;
  18864. var positions = attributes.position.array;
  18865. if ( index !== null ) {
  18866. var indices = index.array;
  18867. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  18868. var a = indices[ i ];
  18869. var b = indices[ i + 1 ];
  18870. vStart.fromArray( positions, a * 3 );
  18871. vEnd.fromArray( positions, b * 3 );
  18872. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18873. if ( distSq > precisionSq ) continue;
  18874. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18875. var distance = raycaster.ray.origin.distanceTo( interRay );
  18876. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18877. intersects.push( {
  18878. distance: distance,
  18879. // What do we want? intersection point on the ray or on the segment??
  18880. // point: raycaster.ray.at( distance ),
  18881. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18882. index: i,
  18883. face: null,
  18884. faceIndex: null,
  18885. object: this
  18886. } );
  18887. }
  18888. } else {
  18889. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  18890. vStart.fromArray( positions, 3 * i );
  18891. vEnd.fromArray( positions, 3 * i + 3 );
  18892. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18893. if ( distSq > precisionSq ) continue;
  18894. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18895. var distance = raycaster.ray.origin.distanceTo( interRay );
  18896. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18897. intersects.push( {
  18898. distance: distance,
  18899. // What do we want? intersection point on the ray or on the segment??
  18900. // point: raycaster.ray.at( distance ),
  18901. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18902. index: i,
  18903. face: null,
  18904. faceIndex: null,
  18905. object: this
  18906. } );
  18907. }
  18908. }
  18909. } else if ( geometry.isGeometry ) {
  18910. var vertices = geometry.vertices;
  18911. var nbVertices = vertices.length;
  18912. for ( var i = 0; i < nbVertices - 1; i += step ) {
  18913. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  18914. if ( distSq > precisionSq ) continue;
  18915. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18916. var distance = raycaster.ray.origin.distanceTo( interRay );
  18917. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18918. intersects.push( {
  18919. distance: distance,
  18920. // What do we want? intersection point on the ray or on the segment??
  18921. // point: raycaster.ray.at( distance ),
  18922. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18923. index: i,
  18924. face: null,
  18925. faceIndex: null,
  18926. object: this
  18927. } );
  18928. }
  18929. }
  18930. };
  18931. }() ),
  18932. clone: function () {
  18933. return new this.constructor( this.geometry, this.material ).copy( this );
  18934. }
  18935. } );
  18936. /**
  18937. * @author mrdoob / http://mrdoob.com/
  18938. */
  18939. function LineSegments( geometry, material ) {
  18940. Line.call( this, geometry, material );
  18941. this.type = 'LineSegments';
  18942. }
  18943. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  18944. constructor: LineSegments,
  18945. isLineSegments: true
  18946. } );
  18947. /**
  18948. * @author mgreter / http://github.com/mgreter
  18949. */
  18950. function LineLoop( geometry, material ) {
  18951. Line.call( this, geometry, material );
  18952. this.type = 'LineLoop';
  18953. }
  18954. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  18955. constructor: LineLoop,
  18956. isLineLoop: true,
  18957. } );
  18958. /**
  18959. * @author mrdoob / http://mrdoob.com/
  18960. * @author alteredq / http://alteredqualia.com/
  18961. *
  18962. * parameters = {
  18963. * color: <hex>,
  18964. * opacity: <float>,
  18965. * map: new THREE.Texture( <Image> ),
  18966. *
  18967. * size: <float>,
  18968. * sizeAttenuation: <bool>
  18969. * }
  18970. */
  18971. function PointsMaterial( parameters ) {
  18972. Material.call( this );
  18973. this.type = 'PointsMaterial';
  18974. this.color = new Color( 0xffffff );
  18975. this.map = null;
  18976. this.size = 1;
  18977. this.sizeAttenuation = true;
  18978. this.lights = false;
  18979. this.setValues( parameters );
  18980. }
  18981. PointsMaterial.prototype = Object.create( Material.prototype );
  18982. PointsMaterial.prototype.constructor = PointsMaterial;
  18983. PointsMaterial.prototype.isPointsMaterial = true;
  18984. PointsMaterial.prototype.copy = function ( source ) {
  18985. Material.prototype.copy.call( this, source );
  18986. this.color.copy( source.color );
  18987. this.map = source.map;
  18988. this.size = source.size;
  18989. this.sizeAttenuation = source.sizeAttenuation;
  18990. return this;
  18991. };
  18992. /**
  18993. * @author alteredq / http://alteredqualia.com/
  18994. */
  18995. function Points( geometry, material ) {
  18996. Object3D.call( this );
  18997. this.type = 'Points';
  18998. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18999. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  19000. }
  19001. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19002. constructor: Points,
  19003. isPoints: true,
  19004. raycast: ( function () {
  19005. var inverseMatrix = new Matrix4();
  19006. var ray = new Ray();
  19007. var sphere = new Sphere();
  19008. return function raycast( raycaster, intersects ) {
  19009. var object = this;
  19010. var geometry = this.geometry;
  19011. var matrixWorld = this.matrixWorld;
  19012. var threshold = raycaster.params.Points.threshold;
  19013. // Checking boundingSphere distance to ray
  19014. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19015. sphere.copy( geometry.boundingSphere );
  19016. sphere.applyMatrix4( matrixWorld );
  19017. sphere.radius += threshold;
  19018. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19019. //
  19020. inverseMatrix.getInverse( matrixWorld );
  19021. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19022. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19023. var localThresholdSq = localThreshold * localThreshold;
  19024. var position = new Vector3();
  19025. function testPoint( point, index ) {
  19026. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  19027. if ( rayPointDistanceSq < localThresholdSq ) {
  19028. var intersectPoint = ray.closestPointToPoint( point );
  19029. intersectPoint.applyMatrix4( matrixWorld );
  19030. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19031. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19032. intersects.push( {
  19033. distance: distance,
  19034. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19035. point: intersectPoint.clone(),
  19036. index: index,
  19037. face: null,
  19038. object: object
  19039. } );
  19040. }
  19041. }
  19042. if ( geometry.isBufferGeometry ) {
  19043. var index = geometry.index;
  19044. var attributes = geometry.attributes;
  19045. var positions = attributes.position.array;
  19046. if ( index !== null ) {
  19047. var indices = index.array;
  19048. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  19049. var a = indices[ i ];
  19050. position.fromArray( positions, a * 3 );
  19051. testPoint( position, a );
  19052. }
  19053. } else {
  19054. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  19055. position.fromArray( positions, i * 3 );
  19056. testPoint( position, i );
  19057. }
  19058. }
  19059. } else {
  19060. var vertices = geometry.vertices;
  19061. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19062. testPoint( vertices[ i ], i );
  19063. }
  19064. }
  19065. };
  19066. }() ),
  19067. clone: function () {
  19068. return new this.constructor( this.geometry, this.material ).copy( this );
  19069. }
  19070. } );
  19071. /**
  19072. * @author mrdoob / http://mrdoob.com/
  19073. */
  19074. function Group() {
  19075. Object3D.call( this );
  19076. this.type = 'Group';
  19077. }
  19078. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19079. constructor: Group
  19080. } );
  19081. /**
  19082. * @author mrdoob / http://mrdoob.com/
  19083. */
  19084. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19085. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19086. this.generateMipmaps = false;
  19087. var scope = this;
  19088. function update() {
  19089. requestAnimationFrame( update );
  19090. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  19091. scope.needsUpdate = true;
  19092. }
  19093. }
  19094. update();
  19095. }
  19096. VideoTexture.prototype = Object.create( Texture.prototype );
  19097. VideoTexture.prototype.constructor = VideoTexture;
  19098. /**
  19099. * @author alteredq / http://alteredqualia.com/
  19100. */
  19101. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19102. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19103. this.image = { width: width, height: height };
  19104. this.mipmaps = mipmaps;
  19105. // no flipping for cube textures
  19106. // (also flipping doesn't work for compressed textures )
  19107. this.flipY = false;
  19108. // can't generate mipmaps for compressed textures
  19109. // mips must be embedded in DDS files
  19110. this.generateMipmaps = false;
  19111. }
  19112. CompressedTexture.prototype = Object.create( Texture.prototype );
  19113. CompressedTexture.prototype.constructor = CompressedTexture;
  19114. CompressedTexture.prototype.isCompressedTexture = true;
  19115. /**
  19116. * @author Matt DesLauriers / @mattdesl
  19117. * @author atix / arthursilber.de
  19118. */
  19119. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  19120. format = format !== undefined ? format : DepthFormat;
  19121. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  19122. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  19123. }
  19124. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  19125. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  19126. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19127. this.image = { width: width, height: height };
  19128. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  19129. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  19130. this.flipY = false;
  19131. this.generateMipmaps = false;
  19132. }
  19133. DepthTexture.prototype = Object.create( Texture.prototype );
  19134. DepthTexture.prototype.constructor = DepthTexture;
  19135. DepthTexture.prototype.isDepthTexture = true;
  19136. /**
  19137. * @author mrdoob / http://mrdoob.com/
  19138. * @author Mugen87 / https://github.com/Mugen87
  19139. */
  19140. function WireframeGeometry( geometry ) {
  19141. BufferGeometry.call( this );
  19142. this.type = 'WireframeGeometry';
  19143. // buffer
  19144. var vertices = [];
  19145. // helper variables
  19146. var i, j, l, o, ol;
  19147. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  19148. var key, keys = [ 'a', 'b', 'c' ];
  19149. var vertex;
  19150. // different logic for Geometry and BufferGeometry
  19151. if ( geometry && geometry.isGeometry ) {
  19152. // create a data structure that contains all edges without duplicates
  19153. var faces = geometry.faces;
  19154. for ( i = 0, l = faces.length; i < l; i ++ ) {
  19155. var face = faces[ i ];
  19156. for ( j = 0; j < 3; j ++ ) {
  19157. edge1 = face[ keys[ j ] ];
  19158. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  19159. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19160. edge[ 1 ] = Math.max( edge1, edge2 );
  19161. key = edge[ 0 ] + ',' + edge[ 1 ];
  19162. if ( edges[ key ] === undefined ) {
  19163. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19164. }
  19165. }
  19166. }
  19167. // generate vertices
  19168. for ( key in edges ) {
  19169. e = edges[ key ];
  19170. vertex = geometry.vertices[ e.index1 ];
  19171. vertices.push( vertex.x, vertex.y, vertex.z );
  19172. vertex = geometry.vertices[ e.index2 ];
  19173. vertices.push( vertex.x, vertex.y, vertex.z );
  19174. }
  19175. } else if ( geometry && geometry.isBufferGeometry ) {
  19176. var position, indices, groups;
  19177. var group, start, count;
  19178. var index1, index2;
  19179. vertex = new Vector3();
  19180. if ( geometry.index !== null ) {
  19181. // indexed BufferGeometry
  19182. position = geometry.attributes.position;
  19183. indices = geometry.index;
  19184. groups = geometry.groups;
  19185. if ( groups.length === 0 ) {
  19186. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  19187. }
  19188. // create a data structure that contains all eges without duplicates
  19189. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  19190. group = groups[ o ];
  19191. start = group.start;
  19192. count = group.count;
  19193. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  19194. for ( j = 0; j < 3; j ++ ) {
  19195. edge1 = indices.getX( i + j );
  19196. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  19197. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19198. edge[ 1 ] = Math.max( edge1, edge2 );
  19199. key = edge[ 0 ] + ',' + edge[ 1 ];
  19200. if ( edges[ key ] === undefined ) {
  19201. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19202. }
  19203. }
  19204. }
  19205. }
  19206. // generate vertices
  19207. for ( key in edges ) {
  19208. e = edges[ key ];
  19209. vertex.fromBufferAttribute( position, e.index1 );
  19210. vertices.push( vertex.x, vertex.y, vertex.z );
  19211. vertex.fromBufferAttribute( position, e.index2 );
  19212. vertices.push( vertex.x, vertex.y, vertex.z );
  19213. }
  19214. } else {
  19215. // non-indexed BufferGeometry
  19216. position = geometry.attributes.position;
  19217. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  19218. for ( j = 0; j < 3; j ++ ) {
  19219. // three edges per triangle, an edge is represented as (index1, index2)
  19220. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19221. index1 = 3 * i + j;
  19222. vertex.fromBufferAttribute( position, index1 );
  19223. vertices.push( vertex.x, vertex.y, vertex.z );
  19224. index2 = 3 * i + ( ( j + 1 ) % 3 );
  19225. vertex.fromBufferAttribute( position, index2 );
  19226. vertices.push( vertex.x, vertex.y, vertex.z );
  19227. }
  19228. }
  19229. }
  19230. }
  19231. // build geometry
  19232. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19233. }
  19234. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  19235. WireframeGeometry.prototype.constructor = WireframeGeometry;
  19236. /**
  19237. * @author zz85 / https://github.com/zz85
  19238. * @author Mugen87 / https://github.com/Mugen87
  19239. *
  19240. * Parametric Surfaces Geometry
  19241. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19242. */
  19243. // ParametricGeometry
  19244. function ParametricGeometry( func, slices, stacks ) {
  19245. Geometry.call( this );
  19246. this.type = 'ParametricGeometry';
  19247. this.parameters = {
  19248. func: func,
  19249. slices: slices,
  19250. stacks: stacks
  19251. };
  19252. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19253. this.mergeVertices();
  19254. }
  19255. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19256. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19257. // ParametricBufferGeometry
  19258. function ParametricBufferGeometry( func, slices, stacks ) {
  19259. BufferGeometry.call( this );
  19260. this.type = 'ParametricBufferGeometry';
  19261. this.parameters = {
  19262. func: func,
  19263. slices: slices,
  19264. stacks: stacks
  19265. };
  19266. // buffers
  19267. var indices = [];
  19268. var vertices = [];
  19269. var normals = [];
  19270. var uvs = [];
  19271. var EPS = 0.00001;
  19272. var normal = new Vector3();
  19273. var p0 = new Vector3(), p1 = new Vector3();
  19274. var pu = new Vector3(), pv = new Vector3();
  19275. var i, j;
  19276. // generate vertices, normals and uvs
  19277. var sliceCount = slices + 1;
  19278. for ( i = 0; i <= stacks; i ++ ) {
  19279. var v = i / stacks;
  19280. for ( j = 0; j <= slices; j ++ ) {
  19281. var u = j / slices;
  19282. // vertex
  19283. p0 = func( u, v, p0 );
  19284. vertices.push( p0.x, p0.y, p0.z );
  19285. // normal
  19286. // approximate tangent vectors via finite differences
  19287. if ( u - EPS >= 0 ) {
  19288. p1 = func( u - EPS, v, p1 );
  19289. pu.subVectors( p0, p1 );
  19290. } else {
  19291. p1 = func( u + EPS, v, p1 );
  19292. pu.subVectors( p1, p0 );
  19293. }
  19294. if ( v - EPS >= 0 ) {
  19295. p1 = func( u, v - EPS, p1 );
  19296. pv.subVectors( p0, p1 );
  19297. } else {
  19298. p1 = func( u, v + EPS, p1 );
  19299. pv.subVectors( p1, p0 );
  19300. }
  19301. // cross product of tangent vectors returns surface normal
  19302. normal.crossVectors( pu, pv ).normalize();
  19303. normals.push( normal.x, normal.y, normal.z );
  19304. // uv
  19305. uvs.push( u, v );
  19306. }
  19307. }
  19308. // generate indices
  19309. for ( i = 0; i < stacks; i ++ ) {
  19310. for ( j = 0; j < slices; j ++ ) {
  19311. var a = i * sliceCount + j;
  19312. var b = i * sliceCount + j + 1;
  19313. var c = ( i + 1 ) * sliceCount + j + 1;
  19314. var d = ( i + 1 ) * sliceCount + j;
  19315. // faces one and two
  19316. indices.push( a, b, d );
  19317. indices.push( b, c, d );
  19318. }
  19319. }
  19320. // build geometry
  19321. this.setIndex( indices );
  19322. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19323. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19324. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19325. }
  19326. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19327. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19328. /**
  19329. * @author clockworkgeek / https://github.com/clockworkgeek
  19330. * @author timothypratley / https://github.com/timothypratley
  19331. * @author WestLangley / http://github.com/WestLangley
  19332. * @author Mugen87 / https://github.com/Mugen87
  19333. */
  19334. // PolyhedronGeometry
  19335. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  19336. Geometry.call( this );
  19337. this.type = 'PolyhedronGeometry';
  19338. this.parameters = {
  19339. vertices: vertices,
  19340. indices: indices,
  19341. radius: radius,
  19342. detail: detail
  19343. };
  19344. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19345. this.mergeVertices();
  19346. }
  19347. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  19348. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  19349. // PolyhedronBufferGeometry
  19350. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  19351. BufferGeometry.call( this );
  19352. this.type = 'PolyhedronBufferGeometry';
  19353. this.parameters = {
  19354. vertices: vertices,
  19355. indices: indices,
  19356. radius: radius,
  19357. detail: detail
  19358. };
  19359. radius = radius || 1;
  19360. detail = detail || 0;
  19361. // default buffer data
  19362. var vertexBuffer = [];
  19363. var uvBuffer = [];
  19364. // the subdivision creates the vertex buffer data
  19365. subdivide( detail );
  19366. // all vertices should lie on a conceptual sphere with a given radius
  19367. appplyRadius( radius );
  19368. // finally, create the uv data
  19369. generateUVs();
  19370. // build non-indexed geometry
  19371. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19372. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19373. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19374. if ( detail === 0 ) {
  19375. this.computeVertexNormals(); // flat normals
  19376. } else {
  19377. this.normalizeNormals(); // smooth normals
  19378. }
  19379. // helper functions
  19380. function subdivide( detail ) {
  19381. var a = new Vector3();
  19382. var b = new Vector3();
  19383. var c = new Vector3();
  19384. // iterate over all faces and apply a subdivison with the given detail value
  19385. for ( var i = 0; i < indices.length; i += 3 ) {
  19386. // get the vertices of the face
  19387. getVertexByIndex( indices[ i + 0 ], a );
  19388. getVertexByIndex( indices[ i + 1 ], b );
  19389. getVertexByIndex( indices[ i + 2 ], c );
  19390. // perform subdivision
  19391. subdivideFace( a, b, c, detail );
  19392. }
  19393. }
  19394. function subdivideFace( a, b, c, detail ) {
  19395. var cols = Math.pow( 2, detail );
  19396. // we use this multidimensional array as a data structure for creating the subdivision
  19397. var v = [];
  19398. var i, j;
  19399. // construct all of the vertices for this subdivision
  19400. for ( i = 0; i <= cols; i ++ ) {
  19401. v[ i ] = [];
  19402. var aj = a.clone().lerp( c, i / cols );
  19403. var bj = b.clone().lerp( c, i / cols );
  19404. var rows = cols - i;
  19405. for ( j = 0; j <= rows; j ++ ) {
  19406. if ( j === 0 && i === cols ) {
  19407. v[ i ][ j ] = aj;
  19408. } else {
  19409. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19410. }
  19411. }
  19412. }
  19413. // construct all of the faces
  19414. for ( i = 0; i < cols; i ++ ) {
  19415. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19416. var k = Math.floor( j / 2 );
  19417. if ( j % 2 === 0 ) {
  19418. pushVertex( v[ i ][ k + 1 ] );
  19419. pushVertex( v[ i + 1 ][ k ] );
  19420. pushVertex( v[ i ][ k ] );
  19421. } else {
  19422. pushVertex( v[ i ][ k + 1 ] );
  19423. pushVertex( v[ i + 1 ][ k + 1 ] );
  19424. pushVertex( v[ i + 1 ][ k ] );
  19425. }
  19426. }
  19427. }
  19428. }
  19429. function appplyRadius( radius ) {
  19430. var vertex = new Vector3();
  19431. // iterate over the entire buffer and apply the radius to each vertex
  19432. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19433. vertex.x = vertexBuffer[ i + 0 ];
  19434. vertex.y = vertexBuffer[ i + 1 ];
  19435. vertex.z = vertexBuffer[ i + 2 ];
  19436. vertex.normalize().multiplyScalar( radius );
  19437. vertexBuffer[ i + 0 ] = vertex.x;
  19438. vertexBuffer[ i + 1 ] = vertex.y;
  19439. vertexBuffer[ i + 2 ] = vertex.z;
  19440. }
  19441. }
  19442. function generateUVs() {
  19443. var vertex = new Vector3();
  19444. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19445. vertex.x = vertexBuffer[ i + 0 ];
  19446. vertex.y = vertexBuffer[ i + 1 ];
  19447. vertex.z = vertexBuffer[ i + 2 ];
  19448. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19449. var v = inclination( vertex ) / Math.PI + 0.5;
  19450. uvBuffer.push( u, 1 - v );
  19451. }
  19452. correctUVs();
  19453. correctSeam();
  19454. }
  19455. function correctSeam() {
  19456. // handle case when face straddles the seam, see #3269
  19457. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  19458. // uv data of a single face
  19459. var x0 = uvBuffer[ i + 0 ];
  19460. var x1 = uvBuffer[ i + 2 ];
  19461. var x2 = uvBuffer[ i + 4 ];
  19462. var max = Math.max( x0, x1, x2 );
  19463. var min = Math.min( x0, x1, x2 );
  19464. // 0.9 is somewhat arbitrary
  19465. if ( max > 0.9 && min < 0.1 ) {
  19466. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19467. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19468. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19469. }
  19470. }
  19471. }
  19472. function pushVertex( vertex ) {
  19473. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19474. }
  19475. function getVertexByIndex( index, vertex ) {
  19476. var stride = index * 3;
  19477. vertex.x = vertices[ stride + 0 ];
  19478. vertex.y = vertices[ stride + 1 ];
  19479. vertex.z = vertices[ stride + 2 ];
  19480. }
  19481. function correctUVs() {
  19482. var a = new Vector3();
  19483. var b = new Vector3();
  19484. var c = new Vector3();
  19485. var centroid = new Vector3();
  19486. var uvA = new Vector2();
  19487. var uvB = new Vector2();
  19488. var uvC = new Vector2();
  19489. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19490. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19491. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19492. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19493. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19494. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19495. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19496. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19497. var azi = azimuth( centroid );
  19498. correctUV( uvA, j + 0, a, azi );
  19499. correctUV( uvB, j + 2, b, azi );
  19500. correctUV( uvC, j + 4, c, azi );
  19501. }
  19502. }
  19503. function correctUV( uv, stride, vector, azimuth ) {
  19504. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19505. uvBuffer[ stride ] = uv.x - 1;
  19506. }
  19507. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19508. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19509. }
  19510. }
  19511. // Angle around the Y axis, counter-clockwise when looking from above.
  19512. function azimuth( vector ) {
  19513. return Math.atan2( vector.z, - vector.x );
  19514. }
  19515. // Angle above the XZ plane.
  19516. function inclination( vector ) {
  19517. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19518. }
  19519. }
  19520. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19521. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  19522. /**
  19523. * @author timothypratley / https://github.com/timothypratley
  19524. * @author Mugen87 / https://github.com/Mugen87
  19525. */
  19526. // TetrahedronGeometry
  19527. function TetrahedronGeometry( radius, detail ) {
  19528. Geometry.call( this );
  19529. this.type = 'TetrahedronGeometry';
  19530. this.parameters = {
  19531. radius: radius,
  19532. detail: detail
  19533. };
  19534. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19535. this.mergeVertices();
  19536. }
  19537. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  19538. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  19539. // TetrahedronBufferGeometry
  19540. function TetrahedronBufferGeometry( radius, detail ) {
  19541. var vertices = [
  19542. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19543. ];
  19544. var indices = [
  19545. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19546. ];
  19547. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19548. this.type = 'TetrahedronBufferGeometry';
  19549. this.parameters = {
  19550. radius: radius,
  19551. detail: detail
  19552. };
  19553. }
  19554. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19555. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  19556. /**
  19557. * @author timothypratley / https://github.com/timothypratley
  19558. * @author Mugen87 / https://github.com/Mugen87
  19559. */
  19560. // OctahedronGeometry
  19561. function OctahedronGeometry( radius, detail ) {
  19562. Geometry.call( this );
  19563. this.type = 'OctahedronGeometry';
  19564. this.parameters = {
  19565. radius: radius,
  19566. detail: detail
  19567. };
  19568. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19569. this.mergeVertices();
  19570. }
  19571. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  19572. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  19573. // OctahedronBufferGeometry
  19574. function OctahedronBufferGeometry( radius, detail ) {
  19575. var vertices = [
  19576. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19577. ];
  19578. var indices = [
  19579. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19580. ];
  19581. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19582. this.type = 'OctahedronBufferGeometry';
  19583. this.parameters = {
  19584. radius: radius,
  19585. detail: detail
  19586. };
  19587. }
  19588. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19589. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  19590. /**
  19591. * @author timothypratley / https://github.com/timothypratley
  19592. * @author Mugen87 / https://github.com/Mugen87
  19593. */
  19594. // IcosahedronGeometry
  19595. function IcosahedronGeometry( radius, detail ) {
  19596. Geometry.call( this );
  19597. this.type = 'IcosahedronGeometry';
  19598. this.parameters = {
  19599. radius: radius,
  19600. detail: detail
  19601. };
  19602. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19603. this.mergeVertices();
  19604. }
  19605. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  19606. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  19607. // IcosahedronBufferGeometry
  19608. function IcosahedronBufferGeometry( radius, detail ) {
  19609. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19610. var vertices = [
  19611. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19612. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19613. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19614. ];
  19615. var indices = [
  19616. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19617. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19618. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19619. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19620. ];
  19621. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19622. this.type = 'IcosahedronBufferGeometry';
  19623. this.parameters = {
  19624. radius: radius,
  19625. detail: detail
  19626. };
  19627. }
  19628. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19629. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  19630. /**
  19631. * @author Abe Pazos / https://hamoid.com
  19632. * @author Mugen87 / https://github.com/Mugen87
  19633. */
  19634. // DodecahedronGeometry
  19635. function DodecahedronGeometry( radius, detail ) {
  19636. Geometry.call( this );
  19637. this.type = 'DodecahedronGeometry';
  19638. this.parameters = {
  19639. radius: radius,
  19640. detail: detail
  19641. };
  19642. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  19643. this.mergeVertices();
  19644. }
  19645. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  19646. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  19647. // DodecahedronBufferGeometry
  19648. function DodecahedronBufferGeometry( radius, detail ) {
  19649. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19650. var r = 1 / t;
  19651. var vertices = [
  19652. // (±1, ±1, ±1)
  19653. - 1, - 1, - 1, - 1, - 1, 1,
  19654. - 1, 1, - 1, - 1, 1, 1,
  19655. 1, - 1, - 1, 1, - 1, 1,
  19656. 1, 1, - 1, 1, 1, 1,
  19657. // (0, ±1/φ, ±φ)
  19658. 0, - r, - t, 0, - r, t,
  19659. 0, r, - t, 0, r, t,
  19660. // (±1/φ, ±φ, 0)
  19661. - r, - t, 0, - r, t, 0,
  19662. r, - t, 0, r, t, 0,
  19663. // (±φ, 0, ±1/φ)
  19664. - t, 0, - r, t, 0, - r,
  19665. - t, 0, r, t, 0, r
  19666. ];
  19667. var indices = [
  19668. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19669. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19670. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19671. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19672. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19673. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19674. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19675. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19676. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19677. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19678. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19679. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19680. ];
  19681. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19682. this.type = 'DodecahedronBufferGeometry';
  19683. this.parameters = {
  19684. radius: radius,
  19685. detail: detail
  19686. };
  19687. }
  19688. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19689. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  19690. /**
  19691. * @author oosmoxiecode / https://github.com/oosmoxiecode
  19692. * @author WestLangley / https://github.com/WestLangley
  19693. * @author zz85 / https://github.com/zz85
  19694. * @author miningold / https://github.com/miningold
  19695. * @author jonobr1 / https://github.com/jonobr1
  19696. * @author Mugen87 / https://github.com/Mugen87
  19697. *
  19698. */
  19699. // TubeGeometry
  19700. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19701. Geometry.call( this );
  19702. this.type = 'TubeGeometry';
  19703. this.parameters = {
  19704. path: path,
  19705. tubularSegments: tubularSegments,
  19706. radius: radius,
  19707. radialSegments: radialSegments,
  19708. closed: closed
  19709. };
  19710. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19711. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19712. // expose internals
  19713. this.tangents = bufferGeometry.tangents;
  19714. this.normals = bufferGeometry.normals;
  19715. this.binormals = bufferGeometry.binormals;
  19716. // create geometry
  19717. this.fromBufferGeometry( bufferGeometry );
  19718. this.mergeVertices();
  19719. }
  19720. TubeGeometry.prototype = Object.create( Geometry.prototype );
  19721. TubeGeometry.prototype.constructor = TubeGeometry;
  19722. // TubeBufferGeometry
  19723. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  19724. BufferGeometry.call( this );
  19725. this.type = 'TubeBufferGeometry';
  19726. this.parameters = {
  19727. path: path,
  19728. tubularSegments: tubularSegments,
  19729. radius: radius,
  19730. radialSegments: radialSegments,
  19731. closed: closed
  19732. };
  19733. tubularSegments = tubularSegments || 64;
  19734. radius = radius || 1;
  19735. radialSegments = radialSegments || 8;
  19736. closed = closed || false;
  19737. var frames = path.computeFrenetFrames( tubularSegments, closed );
  19738. // expose internals
  19739. this.tangents = frames.tangents;
  19740. this.normals = frames.normals;
  19741. this.binormals = frames.binormals;
  19742. // helper variables
  19743. var vertex = new Vector3();
  19744. var normal = new Vector3();
  19745. var uv = new Vector2();
  19746. var i, j;
  19747. // buffer
  19748. var vertices = [];
  19749. var normals = [];
  19750. var uvs = [];
  19751. var indices = [];
  19752. // create buffer data
  19753. generateBufferData();
  19754. // build geometry
  19755. this.setIndex( indices );
  19756. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19757. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19758. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19759. // functions
  19760. function generateBufferData() {
  19761. for ( i = 0; i < tubularSegments; i ++ ) {
  19762. generateSegment( i );
  19763. }
  19764. // if the geometry is not closed, generate the last row of vertices and normals
  19765. // at the regular position on the given path
  19766. //
  19767. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19768. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  19769. // uvs are generated in a separate function.
  19770. // this makes it easy compute correct values for closed geometries
  19771. generateUVs();
  19772. // finally create faces
  19773. generateIndices();
  19774. }
  19775. function generateSegment( i ) {
  19776. // we use getPointAt to sample evenly distributed points from the given path
  19777. var P = path.getPointAt( i / tubularSegments );
  19778. // retrieve corresponding normal and binormal
  19779. var N = frames.normals[ i ];
  19780. var B = frames.binormals[ i ];
  19781. // generate normals and vertices for the current segment
  19782. for ( j = 0; j <= radialSegments; j ++ ) {
  19783. var v = j / radialSegments * Math.PI * 2;
  19784. var sin = Math.sin( v );
  19785. var cos = - Math.cos( v );
  19786. // normal
  19787. normal.x = ( cos * N.x + sin * B.x );
  19788. normal.y = ( cos * N.y + sin * B.y );
  19789. normal.z = ( cos * N.z + sin * B.z );
  19790. normal.normalize();
  19791. normals.push( normal.x, normal.y, normal.z );
  19792. // vertex
  19793. vertex.x = P.x + radius * normal.x;
  19794. vertex.y = P.y + radius * normal.y;
  19795. vertex.z = P.z + radius * normal.z;
  19796. vertices.push( vertex.x, vertex.y, vertex.z );
  19797. }
  19798. }
  19799. function generateIndices() {
  19800. for ( j = 1; j <= tubularSegments; j ++ ) {
  19801. for ( i = 1; i <= radialSegments; i ++ ) {
  19802. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19803. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19804. var c = ( radialSegments + 1 ) * j + i;
  19805. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19806. // faces
  19807. indices.push( a, b, d );
  19808. indices.push( b, c, d );
  19809. }
  19810. }
  19811. }
  19812. function generateUVs() {
  19813. for ( i = 0; i <= tubularSegments; i ++ ) {
  19814. for ( j = 0; j <= radialSegments; j ++ ) {
  19815. uv.x = i / tubularSegments;
  19816. uv.y = j / radialSegments;
  19817. uvs.push( uv.x, uv.y );
  19818. }
  19819. }
  19820. }
  19821. }
  19822. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19823. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  19824. /**
  19825. * @author oosmoxiecode
  19826. * @author Mugen87 / https://github.com/Mugen87
  19827. *
  19828. * based on http://www.blackpawn.com/texts/pqtorus/
  19829. */
  19830. // TorusKnotGeometry
  19831. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  19832. Geometry.call( this );
  19833. this.type = 'TorusKnotGeometry';
  19834. this.parameters = {
  19835. radius: radius,
  19836. tube: tube,
  19837. tubularSegments: tubularSegments,
  19838. radialSegments: radialSegments,
  19839. p: p,
  19840. q: q
  19841. };
  19842. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  19843. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  19844. this.mergeVertices();
  19845. }
  19846. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  19847. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  19848. // TorusKnotBufferGeometry
  19849. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  19850. BufferGeometry.call( this );
  19851. this.type = 'TorusKnotBufferGeometry';
  19852. this.parameters = {
  19853. radius: radius,
  19854. tube: tube,
  19855. tubularSegments: tubularSegments,
  19856. radialSegments: radialSegments,
  19857. p: p,
  19858. q: q
  19859. };
  19860. radius = radius || 100;
  19861. tube = tube || 40;
  19862. tubularSegments = Math.floor( tubularSegments ) || 64;
  19863. radialSegments = Math.floor( radialSegments ) || 8;
  19864. p = p || 2;
  19865. q = q || 3;
  19866. // buffers
  19867. var indices = [];
  19868. var vertices = [];
  19869. var normals = [];
  19870. var uvs = [];
  19871. // helper variables
  19872. var i, j;
  19873. var vertex = new Vector3();
  19874. var normal = new Vector3();
  19875. var P1 = new Vector3();
  19876. var P2 = new Vector3();
  19877. var B = new Vector3();
  19878. var T = new Vector3();
  19879. var N = new Vector3();
  19880. // generate vertices, normals and uvs
  19881. for ( i = 0; i <= tubularSegments; ++ i ) {
  19882. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19883. var u = i / tubularSegments * p * Math.PI * 2;
  19884. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19885. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19886. calculatePositionOnCurve( u, p, q, radius, P1 );
  19887. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  19888. // calculate orthonormal basis
  19889. T.subVectors( P2, P1 );
  19890. N.addVectors( P2, P1 );
  19891. B.crossVectors( T, N );
  19892. N.crossVectors( B, T );
  19893. // normalize B, N. T can be ignored, we don't use it
  19894. B.normalize();
  19895. N.normalize();
  19896. for ( j = 0; j <= radialSegments; ++ j ) {
  19897. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19898. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19899. var v = j / radialSegments * Math.PI * 2;
  19900. var cx = - tube * Math.cos( v );
  19901. var cy = tube * Math.sin( v );
  19902. // now calculate the final vertex position.
  19903. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19904. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  19905. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  19906. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  19907. vertices.push( vertex.x, vertex.y, vertex.z );
  19908. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19909. normal.subVectors( vertex, P1 ).normalize();
  19910. normals.push( normal.x, normal.y, normal.z );
  19911. // uv
  19912. uvs.push( i / tubularSegments );
  19913. uvs.push( j / radialSegments );
  19914. }
  19915. }
  19916. // generate indices
  19917. for ( j = 1; j <= tubularSegments; j ++ ) {
  19918. for ( i = 1; i <= radialSegments; i ++ ) {
  19919. // indices
  19920. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19921. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19922. var c = ( radialSegments + 1 ) * j + i;
  19923. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19924. // faces
  19925. indices.push( a, b, d );
  19926. indices.push( b, c, d );
  19927. }
  19928. }
  19929. // build geometry
  19930. this.setIndex( indices );
  19931. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19932. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19933. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19934. // this function calculates the current position on the torus curve
  19935. function calculatePositionOnCurve( u, p, q, radius, position ) {
  19936. var cu = Math.cos( u );
  19937. var su = Math.sin( u );
  19938. var quOverP = q / p * u;
  19939. var cs = Math.cos( quOverP );
  19940. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  19941. position.y = radius * ( 2 + cs ) * su * 0.5;
  19942. position.z = radius * Math.sin( quOverP ) * 0.5;
  19943. }
  19944. }
  19945. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19946. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  19947. /**
  19948. * @author oosmoxiecode
  19949. * @author mrdoob / http://mrdoob.com/
  19950. * @author Mugen87 / https://github.com/Mugen87
  19951. */
  19952. // TorusGeometry
  19953. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19954. Geometry.call( this );
  19955. this.type = 'TorusGeometry';
  19956. this.parameters = {
  19957. radius: radius,
  19958. tube: tube,
  19959. radialSegments: radialSegments,
  19960. tubularSegments: tubularSegments,
  19961. arc: arc
  19962. };
  19963. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  19964. this.mergeVertices();
  19965. }
  19966. TorusGeometry.prototype = Object.create( Geometry.prototype );
  19967. TorusGeometry.prototype.constructor = TorusGeometry;
  19968. // TorusBufferGeometry
  19969. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19970. BufferGeometry.call( this );
  19971. this.type = 'TorusBufferGeometry';
  19972. this.parameters = {
  19973. radius: radius,
  19974. tube: tube,
  19975. radialSegments: radialSegments,
  19976. tubularSegments: tubularSegments,
  19977. arc: arc
  19978. };
  19979. radius = radius || 100;
  19980. tube = tube || 40;
  19981. radialSegments = Math.floor( radialSegments ) || 8;
  19982. tubularSegments = Math.floor( tubularSegments ) || 6;
  19983. arc = arc || Math.PI * 2;
  19984. // buffers
  19985. var indices = [];
  19986. var vertices = [];
  19987. var normals = [];
  19988. var uvs = [];
  19989. // helper variables
  19990. var center = new Vector3();
  19991. var vertex = new Vector3();
  19992. var normal = new Vector3();
  19993. var j, i;
  19994. // generate vertices, normals and uvs
  19995. for ( j = 0; j <= radialSegments; j ++ ) {
  19996. for ( i = 0; i <= tubularSegments; i ++ ) {
  19997. var u = i / tubularSegments * arc;
  19998. var v = j / radialSegments * Math.PI * 2;
  19999. // vertex
  20000. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20001. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20002. vertex.z = tube * Math.sin( v );
  20003. vertices.push( vertex.x, vertex.y, vertex.z );
  20004. // normal
  20005. center.x = radius * Math.cos( u );
  20006. center.y = radius * Math.sin( u );
  20007. normal.subVectors( vertex, center ).normalize();
  20008. normals.push( normal.x, normal.y, normal.z );
  20009. // uv
  20010. uvs.push( i / tubularSegments );
  20011. uvs.push( j / radialSegments );
  20012. }
  20013. }
  20014. // generate indices
  20015. for ( j = 1; j <= radialSegments; j ++ ) {
  20016. for ( i = 1; i <= tubularSegments; i ++ ) {
  20017. // indices
  20018. var a = ( tubularSegments + 1 ) * j + i - 1;
  20019. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20020. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20021. var d = ( tubularSegments + 1 ) * j + i;
  20022. // faces
  20023. indices.push( a, b, d );
  20024. indices.push( b, c, d );
  20025. }
  20026. }
  20027. // build geometry
  20028. this.setIndex( indices );
  20029. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20030. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20031. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20032. }
  20033. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20034. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  20035. /**
  20036. * @author zz85 / http://www.lab4games.net/zz85/blog
  20037. */
  20038. var ShapeUtils = {
  20039. // calculate area of the contour polygon
  20040. area: function ( contour ) {
  20041. var n = contour.length;
  20042. var a = 0.0;
  20043. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  20044. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20045. }
  20046. return a * 0.5;
  20047. },
  20048. triangulate: ( function () {
  20049. /**
  20050. * This code is a quick port of code written in C++ which was submitted to
  20051. * flipcode.com by John W. Ratcliff // July 22, 2000
  20052. * See original code and more information here:
  20053. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  20054. *
  20055. * ported to actionscript by Zevan Rosser
  20056. * www.actionsnippet.com
  20057. *
  20058. * ported to javascript by Joshua Koo
  20059. * http://www.lab4games.net/zz85/blog
  20060. *
  20061. */
  20062. function snip( contour, u, v, w, n, verts ) {
  20063. var p;
  20064. var ax, ay, bx, by;
  20065. var cx, cy, px, py;
  20066. ax = contour[ verts[ u ] ].x;
  20067. ay = contour[ verts[ u ] ].y;
  20068. bx = contour[ verts[ v ] ].x;
  20069. by = contour[ verts[ v ] ].y;
  20070. cx = contour[ verts[ w ] ].x;
  20071. cy = contour[ verts[ w ] ].y;
  20072. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  20073. var aX, aY, bX, bY, cX, cY;
  20074. var apx, apy, bpx, bpy, cpx, cpy;
  20075. var cCROSSap, bCROSScp, aCROSSbp;
  20076. aX = cx - bx; aY = cy - by;
  20077. bX = ax - cx; bY = ay - cy;
  20078. cX = bx - ax; cY = by - ay;
  20079. for ( p = 0; p < n; p ++ ) {
  20080. px = contour[ verts[ p ] ].x;
  20081. py = contour[ verts[ p ] ].y;
  20082. if ( ( ( px === ax ) && ( py === ay ) ) ||
  20083. ( ( px === bx ) && ( py === by ) ) ||
  20084. ( ( px === cx ) && ( py === cy ) ) ) continue;
  20085. apx = px - ax; apy = py - ay;
  20086. bpx = px - bx; bpy = py - by;
  20087. cpx = px - cx; cpy = py - cy;
  20088. // see if p is inside triangle abc
  20089. aCROSSbp = aX * bpy - aY * bpx;
  20090. cCROSSap = cX * apy - cY * apx;
  20091. bCROSScp = bX * cpy - bY * cpx;
  20092. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  20093. }
  20094. return true;
  20095. }
  20096. // takes in an contour array and returns
  20097. return function triangulate( contour, indices ) {
  20098. var n = contour.length;
  20099. if ( n < 3 ) return null;
  20100. var result = [],
  20101. verts = [],
  20102. vertIndices = [];
  20103. /* we want a counter-clockwise polygon in verts */
  20104. var u, v, w;
  20105. if ( ShapeUtils.area( contour ) > 0.0 ) {
  20106. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  20107. } else {
  20108. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  20109. }
  20110. var nv = n;
  20111. /* remove nv - 2 vertices, creating 1 triangle every time */
  20112. var count = 2 * nv; /* error detection */
  20113. for ( v = nv - 1; nv > 2; ) {
  20114. /* if we loop, it is probably a non-simple polygon */
  20115. if ( ( count -- ) <= 0 ) {
  20116. //** Triangulate: ERROR - probable bad polygon!
  20117. //throw ( "Warning, unable to triangulate polygon!" );
  20118. //return null;
  20119. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  20120. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  20121. if ( indices ) return vertIndices;
  20122. return result;
  20123. }
  20124. /* three consecutive vertices in current polygon, <u,v,w> */
  20125. u = v; if ( nv <= u ) u = 0; /* previous */
  20126. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  20127. w = v + 1; if ( nv <= w ) w = 0; /* next */
  20128. if ( snip( contour, u, v, w, nv, verts ) ) {
  20129. var a, b, c, s, t;
  20130. /* true names of the vertices */
  20131. a = verts[ u ];
  20132. b = verts[ v ];
  20133. c = verts[ w ];
  20134. /* output Triangle */
  20135. result.push( [ contour[ a ],
  20136. contour[ b ],
  20137. contour[ c ] ] );
  20138. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  20139. /* remove v from the remaining polygon */
  20140. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  20141. verts[ s ] = verts[ t ];
  20142. }
  20143. nv --;
  20144. /* reset error detection counter */
  20145. count = 2 * nv;
  20146. }
  20147. }
  20148. if ( indices ) return vertIndices;
  20149. return result;
  20150. };
  20151. } )(),
  20152. triangulateShape: function ( contour, holes ) {
  20153. function removeDupEndPts(points) {
  20154. var l = points.length;
  20155. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20156. points.pop();
  20157. }
  20158. }
  20159. removeDupEndPts( contour );
  20160. holes.forEach( removeDupEndPts );
  20161. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  20162. // inOtherPt needs to be collinear to the inSegment
  20163. if ( inSegPt1.x !== inSegPt2.x ) {
  20164. if ( inSegPt1.x < inSegPt2.x ) {
  20165. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  20166. } else {
  20167. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  20168. }
  20169. } else {
  20170. if ( inSegPt1.y < inSegPt2.y ) {
  20171. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  20172. } else {
  20173. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  20174. }
  20175. }
  20176. }
  20177. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  20178. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  20179. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  20180. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  20181. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  20182. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  20183. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  20184. if ( Math.abs( limit ) > Number.EPSILON ) {
  20185. // not parallel
  20186. var perpSeg2;
  20187. if ( limit > 0 ) {
  20188. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  20189. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  20190. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  20191. } else {
  20192. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  20193. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  20194. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  20195. }
  20196. // i.e. to reduce rounding errors
  20197. // intersection at endpoint of segment#1?
  20198. if ( perpSeg2 === 0 ) {
  20199. if ( ( inExcludeAdjacentSegs ) &&
  20200. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  20201. return [ inSeg1Pt1 ];
  20202. }
  20203. if ( perpSeg2 === limit ) {
  20204. if ( ( inExcludeAdjacentSegs ) &&
  20205. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  20206. return [ inSeg1Pt2 ];
  20207. }
  20208. // intersection at endpoint of segment#2?
  20209. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  20210. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  20211. // return real intersection point
  20212. var factorSeg1 = perpSeg2 / limit;
  20213. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  20214. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  20215. } else {
  20216. // parallel or collinear
  20217. if ( ( perpSeg1 !== 0 ) ||
  20218. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  20219. // they are collinear or degenerate
  20220. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  20221. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  20222. // both segments are points
  20223. if ( seg1Pt && seg2Pt ) {
  20224. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  20225. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  20226. return [ inSeg1Pt1 ]; // they are the same point
  20227. }
  20228. // segment#1 is a single point
  20229. if ( seg1Pt ) {
  20230. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  20231. return [ inSeg1Pt1 ];
  20232. }
  20233. // segment#2 is a single point
  20234. if ( seg2Pt ) {
  20235. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  20236. return [ inSeg2Pt1 ];
  20237. }
  20238. // they are collinear segments, which might overlap
  20239. var seg1min, seg1max, seg1minVal, seg1maxVal;
  20240. var seg2min, seg2max, seg2minVal, seg2maxVal;
  20241. if ( seg1dx !== 0 ) {
  20242. // the segments are NOT on a vertical line
  20243. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  20244. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  20245. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  20246. } else {
  20247. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  20248. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  20249. }
  20250. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  20251. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  20252. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  20253. } else {
  20254. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  20255. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  20256. }
  20257. } else {
  20258. // the segments are on a vertical line
  20259. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  20260. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  20261. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  20262. } else {
  20263. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  20264. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  20265. }
  20266. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  20267. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  20268. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  20269. } else {
  20270. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  20271. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  20272. }
  20273. }
  20274. if ( seg1minVal <= seg2minVal ) {
  20275. if ( seg1maxVal < seg2minVal ) return [];
  20276. if ( seg1maxVal === seg2minVal ) {
  20277. if ( inExcludeAdjacentSegs ) return [];
  20278. return [ seg2min ];
  20279. }
  20280. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  20281. return [ seg2min, seg2max ];
  20282. } else {
  20283. if ( seg1minVal > seg2maxVal ) return [];
  20284. if ( seg1minVal === seg2maxVal ) {
  20285. if ( inExcludeAdjacentSegs ) return [];
  20286. return [ seg1min ];
  20287. }
  20288. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  20289. return [ seg1min, seg2max ];
  20290. }
  20291. }
  20292. }
  20293. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  20294. // The order of legs is important
  20295. // translation of all points, so that Vertex is at (0,0)
  20296. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  20297. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  20298. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  20299. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  20300. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  20301. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  20302. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  20303. // angle != 180 deg.
  20304. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  20305. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  20306. if ( from2toAngle > 0 ) {
  20307. // main angle < 180 deg.
  20308. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  20309. } else {
  20310. // main angle > 180 deg.
  20311. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  20312. }
  20313. } else {
  20314. // angle == 180 deg.
  20315. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  20316. return ( from2otherAngle > 0 );
  20317. }
  20318. }
  20319. function removeHoles( contour, holes ) {
  20320. var shape = contour.concat(); // work on this shape
  20321. var hole;
  20322. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  20323. // Check if hole point lies within angle around shape point
  20324. var lastShapeIdx = shape.length - 1;
  20325. var prevShapeIdx = inShapeIdx - 1;
  20326. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  20327. var nextShapeIdx = inShapeIdx + 1;
  20328. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  20329. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  20330. if ( ! insideAngle ) {
  20331. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  20332. return false;
  20333. }
  20334. // Check if shape point lies within angle around hole point
  20335. var lastHoleIdx = hole.length - 1;
  20336. var prevHoleIdx = inHoleIdx - 1;
  20337. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  20338. var nextHoleIdx = inHoleIdx + 1;
  20339. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  20340. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  20341. if ( ! insideAngle ) {
  20342. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  20343. return false;
  20344. }
  20345. return true;
  20346. }
  20347. function intersectsShapeEdge( inShapePt, inHolePt ) {
  20348. // checks for intersections with shape edges
  20349. var sIdx, nextIdx, intersection;
  20350. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  20351. nextIdx = sIdx + 1; nextIdx %= shape.length;
  20352. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  20353. if ( intersection.length > 0 ) return true;
  20354. }
  20355. return false;
  20356. }
  20357. var indepHoles = [];
  20358. function intersectsHoleEdge( inShapePt, inHolePt ) {
  20359. // checks for intersections with hole edges
  20360. var ihIdx, chkHole,
  20361. hIdx, nextIdx, intersection;
  20362. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  20363. chkHole = holes[ indepHoles[ ihIdx ] ];
  20364. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  20365. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  20366. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  20367. if ( intersection.length > 0 ) return true;
  20368. }
  20369. }
  20370. return false;
  20371. }
  20372. var holeIndex, shapeIndex,
  20373. shapePt, holePt,
  20374. holeIdx, cutKey, failedCuts = [],
  20375. tmpShape1, tmpShape2,
  20376. tmpHole1, tmpHole2;
  20377. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20378. indepHoles.push( h );
  20379. }
  20380. var minShapeIndex = 0;
  20381. var counter = indepHoles.length * 2;
  20382. while ( indepHoles.length > 0 ) {
  20383. counter --;
  20384. if ( counter < 0 ) {
  20385. console.log( 'THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!' );
  20386. break;
  20387. }
  20388. // search for shape-vertex and hole-vertex,
  20389. // which can be connected without intersections
  20390. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  20391. shapePt = shape[ shapeIndex ];
  20392. holeIndex = - 1;
  20393. // search for hole which can be reached without intersections
  20394. for ( var h = 0; h < indepHoles.length; h ++ ) {
  20395. holeIdx = indepHoles[ h ];
  20396. // prevent multiple checks
  20397. cutKey = shapePt.x + ':' + shapePt.y + ':' + holeIdx;
  20398. if ( failedCuts[ cutKey ] !== undefined ) continue;
  20399. hole = holes[ holeIdx ];
  20400. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  20401. holePt = hole[ h2 ];
  20402. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  20403. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  20404. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  20405. holeIndex = h2;
  20406. indepHoles.splice( h, 1 );
  20407. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  20408. tmpShape2 = shape.slice( shapeIndex );
  20409. tmpHole1 = hole.slice( holeIndex );
  20410. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  20411. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  20412. minShapeIndex = shapeIndex;
  20413. // Debug only, to show the selected cuts
  20414. // glob_CutLines.push( [ shapePt, holePt ] );
  20415. break;
  20416. }
  20417. if ( holeIndex >= 0 ) break; // hole-vertex found
  20418. failedCuts[ cutKey ] = true; // remember failure
  20419. }
  20420. if ( holeIndex >= 0 ) break; // hole-vertex found
  20421. }
  20422. }
  20423. return shape; /* shape with no holes */
  20424. }
  20425. var i, il, f, face,
  20426. key, index,
  20427. allPointsMap = {};
  20428. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  20429. var allpoints = contour.concat();
  20430. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20431. Array.prototype.push.apply( allpoints, holes[ h ] );
  20432. }
  20433. //console.log( "allpoints",allpoints, allpoints.length );
  20434. // prepare all points map
  20435. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  20436. key = allpoints[ i ].x + ':' + allpoints[ i ].y;
  20437. if ( allPointsMap[ key ] !== undefined ) {
  20438. console.warn( 'THREE.ShapeUtils: Duplicate point', key, i );
  20439. }
  20440. allPointsMap[ key ] = i;
  20441. }
  20442. // remove holes by cutting paths to holes and adding them to the shape
  20443. var shapeWithoutHoles = removeHoles( contour, holes );
  20444. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  20445. //console.log( "triangles",triangles, triangles.length );
  20446. // check all face vertices against all points map
  20447. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  20448. face = triangles[ i ];
  20449. for ( f = 0; f < 3; f ++ ) {
  20450. key = face[ f ].x + ':' + face[ f ].y;
  20451. index = allPointsMap[ key ];
  20452. if ( index !== undefined ) {
  20453. face[ f ] = index;
  20454. }
  20455. }
  20456. }
  20457. return triangles.concat();
  20458. },
  20459. isClockWise: function ( pts ) {
  20460. return ShapeUtils.area( pts ) < 0;
  20461. }
  20462. };
  20463. /**
  20464. * @author zz85 / http://www.lab4games.net/zz85/blog
  20465. *
  20466. * Creates extruded geometry from a path shape.
  20467. *
  20468. * parameters = {
  20469. *
  20470. * curveSegments: <int>, // number of points on the curves
  20471. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20472. * amount: <int>, // Depth to extrude the shape
  20473. *
  20474. * bevelEnabled: <bool>, // turn on bevel
  20475. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20476. * bevelSize: <float>, // how far from shape outline is bevel
  20477. * bevelSegments: <int>, // number of bevel layers
  20478. *
  20479. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20480. * frames: <Object> // containing arrays of tangents, normals, binormals
  20481. *
  20482. * UVGenerator: <Object> // object that provides UV generator functions
  20483. *
  20484. * }
  20485. */
  20486. // ExtrudeGeometry
  20487. function ExtrudeGeometry( shapes, options ) {
  20488. Geometry.call( this );
  20489. this.type = 'ExtrudeGeometry';
  20490. this.parameters = {
  20491. shapes: shapes,
  20492. options: options
  20493. };
  20494. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  20495. this.mergeVertices();
  20496. }
  20497. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  20498. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  20499. // ExtrudeBufferGeometry
  20500. function ExtrudeBufferGeometry( shapes, options ) {
  20501. if ( typeof ( shapes ) === "undefined" ) {
  20502. return;
  20503. }
  20504. BufferGeometry.call( this );
  20505. this.type = 'ExtrudeBufferGeometry';
  20506. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20507. this.addShapeList( shapes, options );
  20508. this.computeVertexNormals();
  20509. // can't really use automatic vertex normals
  20510. // as then front and back sides get smoothed too
  20511. // should do separate smoothing just for sides
  20512. //this.computeVertexNormals();
  20513. //console.log( "took", ( Date.now() - startTime ) );
  20514. }
  20515. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20516. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  20517. ExtrudeBufferGeometry.prototype.getArrays = function () {
  20518. var positionAttribute = this.getAttribute( "position" );
  20519. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  20520. var uvAttribute = this.getAttribute( "uv" );
  20521. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  20522. var IndexAttribute = this.index;
  20523. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  20524. return {
  20525. position: verticesArray,
  20526. uv: uvArray,
  20527. index: indicesArray
  20528. };
  20529. };
  20530. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  20531. var sl = shapes.length;
  20532. options.arrays = this.getArrays();
  20533. for ( var s = 0; s < sl; s ++ ) {
  20534. var shape = shapes[ s ];
  20535. this.addShape( shape, options );
  20536. }
  20537. this.setIndex( options.arrays.index );
  20538. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  20539. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  20540. };
  20541. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  20542. var arrays = options.arrays ? options.arrays : this.getArrays();
  20543. var verticesArray = arrays.position;
  20544. var indicesArray = arrays.index;
  20545. var uvArray = arrays.uv;
  20546. var placeholder = [];
  20547. var amount = options.amount !== undefined ? options.amount : 100;
  20548. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  20549. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  20550. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20551. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  20552. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20553. var steps = options.steps !== undefined ? options.steps : 1;
  20554. var extrudePath = options.extrudePath;
  20555. var extrudePts, extrudeByPath = false;
  20556. // Use default WorldUVGenerator if no UV generators are specified.
  20557. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  20558. var splineTube, binormal, normal, position2;
  20559. if ( extrudePath ) {
  20560. extrudePts = extrudePath.getSpacedPoints( steps );
  20561. extrudeByPath = true;
  20562. bevelEnabled = false; // bevels not supported for path extrusion
  20563. // SETUP TNB variables
  20564. // TODO1 - have a .isClosed in spline?
  20565. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  20566. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20567. binormal = new Vector3();
  20568. normal = new Vector3();
  20569. position2 = new Vector3();
  20570. }
  20571. // Safeguards if bevels are not enabled
  20572. if ( ! bevelEnabled ) {
  20573. bevelSegments = 0;
  20574. bevelThickness = 0;
  20575. bevelSize = 0;
  20576. }
  20577. // Variables initialization
  20578. var ahole, h, hl; // looping of holes
  20579. var scope = this;
  20580. var shapePoints = shape.extractPoints( curveSegments );
  20581. var vertices = shapePoints.shape;
  20582. var holes = shapePoints.holes;
  20583. var reverse = ! ShapeUtils.isClockWise( vertices );
  20584. if ( reverse ) {
  20585. vertices = vertices.reverse();
  20586. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20587. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20588. ahole = holes[ h ];
  20589. if ( ShapeUtils.isClockWise( ahole ) ) {
  20590. holes[ h ] = ahole.reverse();
  20591. }
  20592. }
  20593. }
  20594. var faces = ShapeUtils.triangulateShape( vertices, holes );
  20595. /* Vertices */
  20596. var contour = vertices; // vertices has all points but contour has only points of circumference
  20597. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20598. ahole = holes[ h ];
  20599. vertices = vertices.concat( ahole );
  20600. }
  20601. function scalePt2( pt, vec, size ) {
  20602. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  20603. return vec.clone().multiplyScalar( size ).add( pt );
  20604. }
  20605. var b, bs, t, z,
  20606. vert, vlen = vertices.length,
  20607. face, flen = faces.length;
  20608. // Find directions for point movement
  20609. function getBevelVec( inPt, inPrev, inNext ) {
  20610. // computes for inPt the corresponding point inPt' on a new contour
  20611. // shifted by 1 unit (length of normalized vector) to the left
  20612. // if we walk along contour clockwise, this new contour is outside the old one
  20613. //
  20614. // inPt' is the intersection of the two lines parallel to the two
  20615. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20616. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20617. // good reading for geometry algorithms (here: line-line intersection)
  20618. // http://geomalgorithms.com/a05-_intersect-1.html
  20619. var v_prev_x = inPt.x - inPrev.x,
  20620. v_prev_y = inPt.y - inPrev.y;
  20621. var v_next_x = inNext.x - inPt.x,
  20622. v_next_y = inNext.y - inPt.y;
  20623. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20624. // check for collinear edges
  20625. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20626. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20627. // not collinear
  20628. // length of vectors for normalizing
  20629. var v_prev_len = Math.sqrt( v_prev_lensq );
  20630. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20631. // shift adjacent points by unit vectors to the left
  20632. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20633. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20634. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20635. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20636. // scaling factor for v_prev to intersection point
  20637. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20638. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20639. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20640. // vector from inPt to intersection point
  20641. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20642. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20643. // Don't normalize!, otherwise sharp corners become ugly
  20644. // but prevent crazy spikes
  20645. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20646. if ( v_trans_lensq <= 2 ) {
  20647. return new Vector2( v_trans_x, v_trans_y );
  20648. } else {
  20649. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20650. }
  20651. } else {
  20652. // handle special case of collinear edges
  20653. var direction_eq = false; // assumes: opposite
  20654. if ( v_prev_x > Number.EPSILON ) {
  20655. if ( v_next_x > Number.EPSILON ) {
  20656. direction_eq = true;
  20657. }
  20658. } else {
  20659. if ( v_prev_x < - Number.EPSILON ) {
  20660. if ( v_next_x < - Number.EPSILON ) {
  20661. direction_eq = true;
  20662. }
  20663. } else {
  20664. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20665. direction_eq = true;
  20666. }
  20667. }
  20668. }
  20669. if ( direction_eq ) {
  20670. // console.log("Warning: lines are a straight sequence");
  20671. v_trans_x = - v_prev_y;
  20672. v_trans_y = v_prev_x;
  20673. shrink_by = Math.sqrt( v_prev_lensq );
  20674. } else {
  20675. // console.log("Warning: lines are a straight spike");
  20676. v_trans_x = v_prev_x;
  20677. v_trans_y = v_prev_y;
  20678. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20679. }
  20680. }
  20681. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20682. }
  20683. var contourMovements = [];
  20684. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20685. if ( j === il ) j = 0;
  20686. if ( k === il ) k = 0;
  20687. // (j)---(i)---(k)
  20688. // console.log('i,j,k', i, j , k)
  20689. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20690. }
  20691. var holesMovements = [],
  20692. oneHoleMovements, verticesMovements = contourMovements.concat();
  20693. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20694. ahole = holes[ h ];
  20695. oneHoleMovements = [];
  20696. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20697. if ( j === il ) j = 0;
  20698. if ( k === il ) k = 0;
  20699. // (j)---(i)---(k)
  20700. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20701. }
  20702. holesMovements.push( oneHoleMovements );
  20703. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20704. }
  20705. // Loop bevelSegments, 1 for the front, 1 for the back
  20706. for ( b = 0; b < bevelSegments; b ++ ) {
  20707. //for ( b = bevelSegments; b > 0; b -- ) {
  20708. t = b / bevelSegments;
  20709. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20710. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  20711. // contract shape
  20712. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20713. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20714. v( vert.x, vert.y, - z );
  20715. }
  20716. // expand holes
  20717. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20718. ahole = holes[ h ];
  20719. oneHoleMovements = holesMovements[ h ];
  20720. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20721. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20722. v( vert.x, vert.y, - z );
  20723. }
  20724. }
  20725. }
  20726. bs = bevelSize;
  20727. // Back facing vertices
  20728. for ( i = 0; i < vlen; i ++ ) {
  20729. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20730. if ( ! extrudeByPath ) {
  20731. v( vert.x, vert.y, 0 );
  20732. } else {
  20733. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20734. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20735. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20736. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20737. v( position2.x, position2.y, position2.z );
  20738. }
  20739. }
  20740. // Add stepped vertices...
  20741. // Including front facing vertices
  20742. var s;
  20743. for ( s = 1; s <= steps; s ++ ) {
  20744. for ( i = 0; i < vlen; i ++ ) {
  20745. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20746. if ( ! extrudeByPath ) {
  20747. v( vert.x, vert.y, amount / steps * s );
  20748. } else {
  20749. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20750. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20751. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20752. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20753. v( position2.x, position2.y, position2.z );
  20754. }
  20755. }
  20756. }
  20757. // Add bevel segments planes
  20758. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20759. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  20760. t = b / bevelSegments;
  20761. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20762. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  20763. // contract shape
  20764. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20765. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20766. v( vert.x, vert.y, amount + z );
  20767. }
  20768. // expand holes
  20769. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20770. ahole = holes[ h ];
  20771. oneHoleMovements = holesMovements[ h ];
  20772. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20773. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20774. if ( ! extrudeByPath ) {
  20775. v( vert.x, vert.y, amount + z );
  20776. } else {
  20777. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20778. }
  20779. }
  20780. }
  20781. }
  20782. /* Faces */
  20783. // Top and bottom faces
  20784. buildLidFaces();
  20785. // Sides faces
  20786. buildSideFaces();
  20787. ///// Internal functions
  20788. function buildLidFaces() {
  20789. var start = verticesArray.length/3;
  20790. if ( bevelEnabled ) {
  20791. var layer = 0; // steps + 1
  20792. var offset = vlen * layer;
  20793. // Bottom faces
  20794. for ( i = 0; i < flen; i ++ ) {
  20795. face = faces[ i ];
  20796. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20797. }
  20798. layer = steps + bevelSegments * 2;
  20799. offset = vlen * layer;
  20800. // Top faces
  20801. for ( i = 0; i < flen; i ++ ) {
  20802. face = faces[ i ];
  20803. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20804. }
  20805. } else {
  20806. // Bottom faces
  20807. for ( i = 0; i < flen; i ++ ) {
  20808. face = faces[ i ];
  20809. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20810. }
  20811. // Top faces
  20812. for ( i = 0; i < flen; i ++ ) {
  20813. face = faces[ i ];
  20814. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20815. }
  20816. }
  20817. scope.addGroup( start, verticesArray.length/3 -start, options.material !== undefined ? options.material : 0);
  20818. }
  20819. // Create faces for the z-sides of the shape
  20820. function buildSideFaces() {
  20821. var start = verticesArray.length/3;
  20822. var layeroffset = 0;
  20823. sidewalls( contour, layeroffset );
  20824. layeroffset += contour.length;
  20825. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20826. ahole = holes[ h ];
  20827. sidewalls( ahole, layeroffset );
  20828. //, true
  20829. layeroffset += ahole.length;
  20830. }
  20831. scope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);
  20832. }
  20833. function sidewalls( contour, layeroffset ) {
  20834. var j, k;
  20835. i = contour.length;
  20836. while ( -- i >= 0 ) {
  20837. j = i;
  20838. k = i - 1;
  20839. if ( k < 0 ) k = contour.length - 1;
  20840. //console.log('b', i,j, i-1, k,vertices.length);
  20841. var s = 0,
  20842. sl = steps + bevelSegments * 2;
  20843. for ( s = 0; s < sl; s ++ ) {
  20844. var slen1 = vlen * s;
  20845. var slen2 = vlen * ( s + 1 );
  20846. var a = layeroffset + j + slen1,
  20847. b = layeroffset + k + slen1,
  20848. c = layeroffset + k + slen2,
  20849. d = layeroffset + j + slen2;
  20850. f4( a, b, c, d, contour, s, sl, j, k );
  20851. }
  20852. }
  20853. }
  20854. function v( x, y, z ) {
  20855. placeholder.push( x );
  20856. placeholder.push( y );
  20857. placeholder.push( z );
  20858. }
  20859. function f3( a, b, c ) {
  20860. addVertex( a );
  20861. addVertex( b );
  20862. addVertex( c );
  20863. var nextIndex = verticesArray.length / 3;
  20864. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20865. addUV( uvs[ 0 ] );
  20866. addUV( uvs[ 1 ] );
  20867. addUV( uvs[ 2 ] );
  20868. }
  20869. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  20870. addVertex( a );
  20871. addVertex( b );
  20872. addVertex( d );
  20873. addVertex( b );
  20874. addVertex( c );
  20875. addVertex( d );
  20876. var nextIndex = verticesArray.length / 3;
  20877. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  20878. addUV( uvs[ 0 ] );
  20879. addUV( uvs[ 1 ] );
  20880. addUV( uvs[ 3 ] );
  20881. addUV( uvs[ 1 ] );
  20882. addUV( uvs[ 2 ] );
  20883. addUV( uvs[ 3 ] );
  20884. }
  20885. function addVertex( index ) {
  20886. indicesArray.push( verticesArray.length / 3 );
  20887. verticesArray.push( placeholder[ index * 3 + 0 ] );
  20888. verticesArray.push( placeholder[ index * 3 + 1 ] );
  20889. verticesArray.push( placeholder[ index * 3 + 2 ] );
  20890. }
  20891. function addUV( vector2 ) {
  20892. uvArray.push( vector2.x );
  20893. uvArray.push( vector2.y );
  20894. }
  20895. if ( ! options.arrays ) {
  20896. this.setIndex( indicesArray );
  20897. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20898. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  20899. }
  20900. };
  20901. ExtrudeGeometry.WorldUVGenerator = {
  20902. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  20903. var a_x = vertices[ indexA * 3 ];
  20904. var a_y = vertices[ indexA * 3 + 1 ];
  20905. var b_x = vertices[ indexB * 3 ];
  20906. var b_y = vertices[ indexB * 3 + 1 ];
  20907. var c_x = vertices[ indexC * 3 ];
  20908. var c_y = vertices[ indexC * 3 + 1 ];
  20909. return [
  20910. new Vector2( a_x, a_y ),
  20911. new Vector2( b_x, b_y ),
  20912. new Vector2( c_x, c_y )
  20913. ];
  20914. },
  20915. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  20916. var a_x = vertices[ indexA * 3 ];
  20917. var a_y = vertices[ indexA * 3 + 1 ];
  20918. var a_z = vertices[ indexA * 3 + 2 ];
  20919. var b_x = vertices[ indexB * 3 ];
  20920. var b_y = vertices[ indexB * 3 + 1 ];
  20921. var b_z = vertices[ indexB * 3 + 2 ];
  20922. var c_x = vertices[ indexC * 3 ];
  20923. var c_y = vertices[ indexC * 3 + 1 ];
  20924. var c_z = vertices[ indexC * 3 + 2 ];
  20925. var d_x = vertices[ indexD * 3 ];
  20926. var d_y = vertices[ indexD * 3 + 1 ];
  20927. var d_z = vertices[ indexD * 3 + 2 ];
  20928. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  20929. return [
  20930. new Vector2( a_x, 1 - a_z ),
  20931. new Vector2( b_x, 1 - b_z ),
  20932. new Vector2( c_x, 1 - c_z ),
  20933. new Vector2( d_x, 1 - d_z )
  20934. ];
  20935. } else {
  20936. return [
  20937. new Vector2( a_y, 1 - a_z ),
  20938. new Vector2( b_y, 1 - b_z ),
  20939. new Vector2( c_y, 1 - c_z ),
  20940. new Vector2( d_y, 1 - d_z )
  20941. ];
  20942. }
  20943. }
  20944. };
  20945. /**
  20946. * @author zz85 / http://www.lab4games.net/zz85/blog
  20947. * @author alteredq / http://alteredqualia.com/
  20948. *
  20949. * Text = 3D Text
  20950. *
  20951. * parameters = {
  20952. * font: <THREE.Font>, // font
  20953. *
  20954. * size: <float>, // size of the text
  20955. * height: <float>, // thickness to extrude text
  20956. * curveSegments: <int>, // number of points on the curves
  20957. *
  20958. * bevelEnabled: <bool>, // turn on bevel
  20959. * bevelThickness: <float>, // how deep into text bevel goes
  20960. * bevelSize: <float> // how far from text outline is bevel
  20961. * }
  20962. */
  20963. // TextGeometry
  20964. function TextGeometry( text, parameters ) {
  20965. Geometry.call( this );
  20966. this.type = 'TextGeometry';
  20967. this.parameters = {
  20968. text: text,
  20969. parameters: parameters
  20970. };
  20971. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  20972. this.mergeVertices();
  20973. }
  20974. TextGeometry.prototype = Object.create( Geometry.prototype );
  20975. TextGeometry.prototype.constructor = TextGeometry;
  20976. // TextBufferGeometry
  20977. function TextBufferGeometry( text, parameters ) {
  20978. parameters = parameters || {};
  20979. var font = parameters.font;
  20980. if ( ! ( font && font.isFont ) ) {
  20981. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20982. return new Geometry();
  20983. }
  20984. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  20985. // translate parameters to ExtrudeGeometry API
  20986. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20987. // defaults
  20988. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20989. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20990. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20991. ExtrudeBufferGeometry.call( this, shapes, parameters );
  20992. this.type = 'TextBufferGeometry';
  20993. }
  20994. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  20995. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  20996. /**
  20997. * @author mrdoob / http://mrdoob.com/
  20998. * @author benaadams / https://twitter.com/ben_a_adams
  20999. * @author Mugen87 / https://github.com/Mugen87
  21000. */
  21001. // SphereGeometry
  21002. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21003. Geometry.call( this );
  21004. this.type = 'SphereGeometry';
  21005. this.parameters = {
  21006. radius: radius,
  21007. widthSegments: widthSegments,
  21008. heightSegments: heightSegments,
  21009. phiStart: phiStart,
  21010. phiLength: phiLength,
  21011. thetaStart: thetaStart,
  21012. thetaLength: thetaLength
  21013. };
  21014. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21015. this.mergeVertices();
  21016. }
  21017. SphereGeometry.prototype = Object.create( Geometry.prototype );
  21018. SphereGeometry.prototype.constructor = SphereGeometry;
  21019. // SphereBufferGeometry
  21020. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21021. BufferGeometry.call( this );
  21022. this.type = 'SphereBufferGeometry';
  21023. this.parameters = {
  21024. radius: radius,
  21025. widthSegments: widthSegments,
  21026. heightSegments: heightSegments,
  21027. phiStart: phiStart,
  21028. phiLength: phiLength,
  21029. thetaStart: thetaStart,
  21030. thetaLength: thetaLength
  21031. };
  21032. radius = radius || 50;
  21033. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21034. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21035. phiStart = phiStart !== undefined ? phiStart : 0;
  21036. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21037. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21038. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21039. var thetaEnd = thetaStart + thetaLength;
  21040. var ix, iy;
  21041. var index = 0;
  21042. var grid = [];
  21043. var vertex = new Vector3();
  21044. var normal = new Vector3();
  21045. // buffers
  21046. var indices = [];
  21047. var vertices = [];
  21048. var normals = [];
  21049. var uvs = [];
  21050. // generate vertices, normals and uvs
  21051. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  21052. var verticesRow = [];
  21053. var v = iy / heightSegments;
  21054. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  21055. var u = ix / widthSegments;
  21056. // vertex
  21057. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21058. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21059. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21060. vertices.push( vertex.x, vertex.y, vertex.z );
  21061. // normal
  21062. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  21063. normals.push( normal.x, normal.y, normal.z );
  21064. // uv
  21065. uvs.push( u, 1 - v );
  21066. verticesRow.push( index ++ );
  21067. }
  21068. grid.push( verticesRow );
  21069. }
  21070. // indices
  21071. for ( iy = 0; iy < heightSegments; iy ++ ) {
  21072. for ( ix = 0; ix < widthSegments; ix ++ ) {
  21073. var a = grid[ iy ][ ix + 1 ];
  21074. var b = grid[ iy ][ ix ];
  21075. var c = grid[ iy + 1 ][ ix ];
  21076. var d = grid[ iy + 1 ][ ix + 1 ];
  21077. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21078. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21079. }
  21080. }
  21081. // build geometry
  21082. this.setIndex( indices );
  21083. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21084. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21085. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21086. }
  21087. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21088. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  21089. /**
  21090. * @author Kaleb Murphy
  21091. * @author Mugen87 / https://github.com/Mugen87
  21092. */
  21093. // RingGeometry
  21094. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21095. Geometry.call( this );
  21096. this.type = 'RingGeometry';
  21097. this.parameters = {
  21098. innerRadius: innerRadius,
  21099. outerRadius: outerRadius,
  21100. thetaSegments: thetaSegments,
  21101. phiSegments: phiSegments,
  21102. thetaStart: thetaStart,
  21103. thetaLength: thetaLength
  21104. };
  21105. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  21106. this.mergeVertices();
  21107. }
  21108. RingGeometry.prototype = Object.create( Geometry.prototype );
  21109. RingGeometry.prototype.constructor = RingGeometry;
  21110. // RingBufferGeometry
  21111. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21112. BufferGeometry.call( this );
  21113. this.type = 'RingBufferGeometry';
  21114. this.parameters = {
  21115. innerRadius: innerRadius,
  21116. outerRadius: outerRadius,
  21117. thetaSegments: thetaSegments,
  21118. phiSegments: phiSegments,
  21119. thetaStart: thetaStart,
  21120. thetaLength: thetaLength
  21121. };
  21122. innerRadius = innerRadius || 20;
  21123. outerRadius = outerRadius || 50;
  21124. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21125. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21126. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  21127. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  21128. // buffers
  21129. var indices = [];
  21130. var vertices = [];
  21131. var normals = [];
  21132. var uvs = [];
  21133. // some helper variables
  21134. var segment;
  21135. var radius = innerRadius;
  21136. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21137. var vertex = new Vector3();
  21138. var uv = new Vector2();
  21139. var j, i;
  21140. // generate vertices, normals and uvs
  21141. for ( j = 0; j <= phiSegments; j ++ ) {
  21142. for ( i = 0; i <= thetaSegments; i ++ ) {
  21143. // values are generate from the inside of the ring to the outside
  21144. segment = thetaStart + i / thetaSegments * thetaLength;
  21145. // vertex
  21146. vertex.x = radius * Math.cos( segment );
  21147. vertex.y = radius * Math.sin( segment );
  21148. vertices.push( vertex.x, vertex.y, vertex.z );
  21149. // normal
  21150. normals.push( 0, 0, 1 );
  21151. // uv
  21152. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21153. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21154. uvs.push( uv.x, uv.y );
  21155. }
  21156. // increase the radius for next row of vertices
  21157. radius += radiusStep;
  21158. }
  21159. // indices
  21160. for ( j = 0; j < phiSegments; j ++ ) {
  21161. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  21162. for ( i = 0; i < thetaSegments; i ++ ) {
  21163. segment = i + thetaSegmentLevel;
  21164. var a = segment;
  21165. var b = segment + thetaSegments + 1;
  21166. var c = segment + thetaSegments + 2;
  21167. var d = segment + 1;
  21168. // faces
  21169. indices.push( a, b, d );
  21170. indices.push( b, c, d );
  21171. }
  21172. }
  21173. // build geometry
  21174. this.setIndex( indices );
  21175. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21176. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21177. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21178. }
  21179. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21180. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  21181. /**
  21182. * @author astrodud / http://astrodud.isgreat.org/
  21183. * @author zz85 / https://github.com/zz85
  21184. * @author bhouston / http://clara.io
  21185. * @author Mugen87 / https://github.com/Mugen87
  21186. */
  21187. // LatheGeometry
  21188. function LatheGeometry( points, segments, phiStart, phiLength ) {
  21189. Geometry.call( this );
  21190. this.type = 'LatheGeometry';
  21191. this.parameters = {
  21192. points: points,
  21193. segments: segments,
  21194. phiStart: phiStart,
  21195. phiLength: phiLength
  21196. };
  21197. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  21198. this.mergeVertices();
  21199. }
  21200. LatheGeometry.prototype = Object.create( Geometry.prototype );
  21201. LatheGeometry.prototype.constructor = LatheGeometry;
  21202. // LatheBufferGeometry
  21203. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  21204. BufferGeometry.call( this );
  21205. this.type = 'LatheBufferGeometry';
  21206. this.parameters = {
  21207. points: points,
  21208. segments: segments,
  21209. phiStart: phiStart,
  21210. phiLength: phiLength
  21211. };
  21212. segments = Math.floor( segments ) || 12;
  21213. phiStart = phiStart || 0;
  21214. phiLength = phiLength || Math.PI * 2;
  21215. // clamp phiLength so it's in range of [ 0, 2PI ]
  21216. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  21217. // buffers
  21218. var indices = [];
  21219. var vertices = [];
  21220. var uvs = [];
  21221. // helper variables
  21222. var base;
  21223. var inverseSegments = 1.0 / segments;
  21224. var vertex = new Vector3();
  21225. var uv = new Vector2();
  21226. var i, j;
  21227. // generate vertices and uvs
  21228. for ( i = 0; i <= segments; i ++ ) {
  21229. var phi = phiStart + i * inverseSegments * phiLength;
  21230. var sin = Math.sin( phi );
  21231. var cos = Math.cos( phi );
  21232. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  21233. // vertex
  21234. vertex.x = points[ j ].x * sin;
  21235. vertex.y = points[ j ].y;
  21236. vertex.z = points[ j ].x * cos;
  21237. vertices.push( vertex.x, vertex.y, vertex.z );
  21238. // uv
  21239. uv.x = i / segments;
  21240. uv.y = j / ( points.length - 1 );
  21241. uvs.push( uv.x, uv.y );
  21242. }
  21243. }
  21244. // indices
  21245. for ( i = 0; i < segments; i ++ ) {
  21246. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  21247. base = j + i * points.length;
  21248. var a = base;
  21249. var b = base + points.length;
  21250. var c = base + points.length + 1;
  21251. var d = base + 1;
  21252. // faces
  21253. indices.push( a, b, d );
  21254. indices.push( b, c, d );
  21255. }
  21256. }
  21257. // build geometry
  21258. this.setIndex( indices );
  21259. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21260. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21261. // generate normals
  21262. this.computeVertexNormals();
  21263. // if the geometry is closed, we need to average the normals along the seam.
  21264. // because the corresponding vertices are identical (but still have different UVs).
  21265. if ( phiLength === Math.PI * 2 ) {
  21266. var normals = this.attributes.normal.array;
  21267. var n1 = new Vector3();
  21268. var n2 = new Vector3();
  21269. var n = new Vector3();
  21270. // this is the buffer offset for the last line of vertices
  21271. base = segments * points.length * 3;
  21272. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21273. // select the normal of the vertex in the first line
  21274. n1.x = normals[ j + 0 ];
  21275. n1.y = normals[ j + 1 ];
  21276. n1.z = normals[ j + 2 ];
  21277. // select the normal of the vertex in the last line
  21278. n2.x = normals[ base + j + 0 ];
  21279. n2.y = normals[ base + j + 1 ];
  21280. n2.z = normals[ base + j + 2 ];
  21281. // average normals
  21282. n.addVectors( n1, n2 ).normalize();
  21283. // assign the new values to both normals
  21284. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21285. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21286. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21287. }
  21288. }
  21289. }
  21290. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21291. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  21292. /**
  21293. * @author jonobr1 / http://jonobr1.com
  21294. * @author Mugen87 / https://github.com/Mugen87
  21295. */
  21296. // ShapeGeometry
  21297. function ShapeGeometry( shapes, curveSegments ) {
  21298. Geometry.call( this );
  21299. this.type = 'ShapeGeometry';
  21300. if ( typeof curveSegments === 'object' ) {
  21301. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  21302. curveSegments = curveSegments.curveSegments;
  21303. }
  21304. this.parameters = {
  21305. shapes: shapes,
  21306. curveSegments: curveSegments
  21307. };
  21308. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  21309. this.mergeVertices();
  21310. }
  21311. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  21312. ShapeGeometry.prototype.constructor = ShapeGeometry;
  21313. // ShapeBufferGeometry
  21314. function ShapeBufferGeometry( shapes, curveSegments ) {
  21315. BufferGeometry.call( this );
  21316. this.type = 'ShapeBufferGeometry';
  21317. this.parameters = {
  21318. shapes: shapes,
  21319. curveSegments: curveSegments
  21320. };
  21321. curveSegments = curveSegments || 12;
  21322. // buffers
  21323. var indices = [];
  21324. var vertices = [];
  21325. var normals = [];
  21326. var uvs = [];
  21327. // helper variables
  21328. var groupStart = 0;
  21329. var groupCount = 0;
  21330. // allow single and array values for "shapes" parameter
  21331. if ( Array.isArray( shapes ) === false ) {
  21332. addShape( shapes );
  21333. } else {
  21334. for ( var i = 0; i < shapes.length; i ++ ) {
  21335. addShape( shapes[ i ] );
  21336. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21337. groupStart += groupCount;
  21338. groupCount = 0;
  21339. }
  21340. }
  21341. // build geometry
  21342. this.setIndex( indices );
  21343. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21344. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21345. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21346. // helper functions
  21347. function addShape( shape ) {
  21348. var i, l, shapeHole;
  21349. var indexOffset = vertices.length / 3;
  21350. var points = shape.extractPoints( curveSegments );
  21351. var shapeVertices = points.shape;
  21352. var shapeHoles = points.holes;
  21353. // check direction of vertices
  21354. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21355. shapeVertices = shapeVertices.reverse();
  21356. // also check if holes are in the opposite direction
  21357. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21358. shapeHole = shapeHoles[ i ];
  21359. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21360. shapeHoles[ i ] = shapeHole.reverse();
  21361. }
  21362. }
  21363. }
  21364. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21365. // join vertices of inner and outer paths to a single array
  21366. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21367. shapeHole = shapeHoles[ i ];
  21368. shapeVertices = shapeVertices.concat( shapeHole );
  21369. }
  21370. // vertices, normals, uvs
  21371. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21372. var vertex = shapeVertices[ i ];
  21373. vertices.push( vertex.x, vertex.y, 0 );
  21374. normals.push( 0, 0, 1 );
  21375. uvs.push( vertex.x, vertex.y ); // world uvs
  21376. }
  21377. // incides
  21378. for ( i = 0, l = faces.length; i < l; i ++ ) {
  21379. var face = faces[ i ];
  21380. var a = face[ 0 ] + indexOffset;
  21381. var b = face[ 1 ] + indexOffset;
  21382. var c = face[ 2 ] + indexOffset;
  21383. indices.push( a, b, c );
  21384. groupCount += 3;
  21385. }
  21386. }
  21387. }
  21388. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21389. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  21390. /**
  21391. * @author WestLangley / http://github.com/WestLangley
  21392. * @author Mugen87 / https://github.com/Mugen87
  21393. */
  21394. function EdgesGeometry( geometry, thresholdAngle ) {
  21395. BufferGeometry.call( this );
  21396. this.type = 'EdgesGeometry';
  21397. this.parameters = {
  21398. thresholdAngle: thresholdAngle
  21399. };
  21400. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21401. // buffer
  21402. var vertices = [];
  21403. // helper variables
  21404. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  21405. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  21406. var key, keys = [ 'a', 'b', 'c' ];
  21407. // prepare source geometry
  21408. var geometry2;
  21409. if ( geometry.isBufferGeometry ) {
  21410. geometry2 = new Geometry();
  21411. geometry2.fromBufferGeometry( geometry );
  21412. } else {
  21413. geometry2 = geometry.clone();
  21414. }
  21415. geometry2.mergeVertices();
  21416. geometry2.computeFaceNormals();
  21417. var sourceVertices = geometry2.vertices;
  21418. var faces = geometry2.faces;
  21419. // now create a data structure where each entry represents an edge with its adjoining faces
  21420. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21421. var face = faces[ i ];
  21422. for ( var j = 0; j < 3; j ++ ) {
  21423. edge1 = face[ keys[ j ] ];
  21424. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  21425. edge[ 0 ] = Math.min( edge1, edge2 );
  21426. edge[ 1 ] = Math.max( edge1, edge2 );
  21427. key = edge[ 0 ] + ',' + edge[ 1 ];
  21428. if ( edges[ key ] === undefined ) {
  21429. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  21430. } else {
  21431. edges[ key ].face2 = i;
  21432. }
  21433. }
  21434. }
  21435. // generate vertices
  21436. for ( key in edges ) {
  21437. var e = edges[ key ];
  21438. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  21439. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  21440. var vertex = sourceVertices[ e.index1 ];
  21441. vertices.push( vertex.x, vertex.y, vertex.z );
  21442. vertex = sourceVertices[ e.index2 ];
  21443. vertices.push( vertex.x, vertex.y, vertex.z );
  21444. }
  21445. }
  21446. // build geometry
  21447. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21448. }
  21449. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  21450. EdgesGeometry.prototype.constructor = EdgesGeometry;
  21451. /**
  21452. * @author mrdoob / http://mrdoob.com/
  21453. * @author Mugen87 / https://github.com/Mugen87
  21454. */
  21455. // CylinderGeometry
  21456. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21457. Geometry.call( this );
  21458. this.type = 'CylinderGeometry';
  21459. this.parameters = {
  21460. radiusTop: radiusTop,
  21461. radiusBottom: radiusBottom,
  21462. height: height,
  21463. radialSegments: radialSegments,
  21464. heightSegments: heightSegments,
  21465. openEnded: openEnded,
  21466. thetaStart: thetaStart,
  21467. thetaLength: thetaLength
  21468. };
  21469. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  21470. this.mergeVertices();
  21471. }
  21472. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  21473. CylinderGeometry.prototype.constructor = CylinderGeometry;
  21474. // CylinderBufferGeometry
  21475. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21476. BufferGeometry.call( this );
  21477. this.type = 'CylinderBufferGeometry';
  21478. this.parameters = {
  21479. radiusTop: radiusTop,
  21480. radiusBottom: radiusBottom,
  21481. height: height,
  21482. radialSegments: radialSegments,
  21483. heightSegments: heightSegments,
  21484. openEnded: openEnded,
  21485. thetaStart: thetaStart,
  21486. thetaLength: thetaLength
  21487. };
  21488. var scope = this;
  21489. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21490. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21491. height = height !== undefined ? height : 100;
  21492. radialSegments = Math.floor( radialSegments ) || 8;
  21493. heightSegments = Math.floor( heightSegments ) || 1;
  21494. openEnded = openEnded !== undefined ? openEnded : false;
  21495. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  21496. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  21497. // buffers
  21498. var indices = [];
  21499. var vertices = [];
  21500. var normals = [];
  21501. var uvs = [];
  21502. // helper variables
  21503. var index = 0;
  21504. var indexArray = [];
  21505. var halfHeight = height / 2;
  21506. var groupStart = 0;
  21507. // generate geometry
  21508. generateTorso();
  21509. if ( openEnded === false ) {
  21510. if ( radiusTop > 0 ) generateCap( true );
  21511. if ( radiusBottom > 0 ) generateCap( false );
  21512. }
  21513. // build geometry
  21514. this.setIndex( indices );
  21515. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21516. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21517. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21518. function generateTorso() {
  21519. var x, y;
  21520. var normal = new Vector3();
  21521. var vertex = new Vector3();
  21522. var groupCount = 0;
  21523. // this will be used to calculate the normal
  21524. var slope = ( radiusBottom - radiusTop ) / height;
  21525. // generate vertices, normals and uvs
  21526. for ( y = 0; y <= heightSegments; y ++ ) {
  21527. var indexRow = [];
  21528. var v = y / heightSegments;
  21529. // calculate the radius of the current row
  21530. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21531. for ( x = 0; x <= radialSegments; x ++ ) {
  21532. var u = x / radialSegments;
  21533. var theta = u * thetaLength + thetaStart;
  21534. var sinTheta = Math.sin( theta );
  21535. var cosTheta = Math.cos( theta );
  21536. // vertex
  21537. vertex.x = radius * sinTheta;
  21538. vertex.y = - v * height + halfHeight;
  21539. vertex.z = radius * cosTheta;
  21540. vertices.push( vertex.x, vertex.y, vertex.z );
  21541. // normal
  21542. normal.set( sinTheta, slope, cosTheta ).normalize();
  21543. normals.push( normal.x, normal.y, normal.z );
  21544. // uv
  21545. uvs.push( u, 1 - v );
  21546. // save index of vertex in respective row
  21547. indexRow.push( index ++ );
  21548. }
  21549. // now save vertices of the row in our index array
  21550. indexArray.push( indexRow );
  21551. }
  21552. // generate indices
  21553. for ( x = 0; x < radialSegments; x ++ ) {
  21554. for ( y = 0; y < heightSegments; y ++ ) {
  21555. // we use the index array to access the correct indices
  21556. var a = indexArray[ y ][ x ];
  21557. var b = indexArray[ y + 1 ][ x ];
  21558. var c = indexArray[ y + 1 ][ x + 1 ];
  21559. var d = indexArray[ y ][ x + 1 ];
  21560. // faces
  21561. indices.push( a, b, d );
  21562. indices.push( b, c, d );
  21563. // update group counter
  21564. groupCount += 6;
  21565. }
  21566. }
  21567. // add a group to the geometry. this will ensure multi material support
  21568. scope.addGroup( groupStart, groupCount, 0 );
  21569. // calculate new start value for groups
  21570. groupStart += groupCount;
  21571. }
  21572. function generateCap( top ) {
  21573. var x, centerIndexStart, centerIndexEnd;
  21574. var uv = new Vector2();
  21575. var vertex = new Vector3();
  21576. var groupCount = 0;
  21577. var radius = ( top === true ) ? radiusTop : radiusBottom;
  21578. var sign = ( top === true ) ? 1 : - 1;
  21579. // save the index of the first center vertex
  21580. centerIndexStart = index;
  21581. // first we generate the center vertex data of the cap.
  21582. // because the geometry needs one set of uvs per face,
  21583. // we must generate a center vertex per face/segment
  21584. for ( x = 1; x <= radialSegments; x ++ ) {
  21585. // vertex
  21586. vertices.push( 0, halfHeight * sign, 0 );
  21587. // normal
  21588. normals.push( 0, sign, 0 );
  21589. // uv
  21590. uvs.push( 0.5, 0.5 );
  21591. // increase index
  21592. index ++;
  21593. }
  21594. // save the index of the last center vertex
  21595. centerIndexEnd = index;
  21596. // now we generate the surrounding vertices, normals and uvs
  21597. for ( x = 0; x <= radialSegments; x ++ ) {
  21598. var u = x / radialSegments;
  21599. var theta = u * thetaLength + thetaStart;
  21600. var cosTheta = Math.cos( theta );
  21601. var sinTheta = Math.sin( theta );
  21602. // vertex
  21603. vertex.x = radius * sinTheta;
  21604. vertex.y = halfHeight * sign;
  21605. vertex.z = radius * cosTheta;
  21606. vertices.push( vertex.x, vertex.y, vertex.z );
  21607. // normal
  21608. normals.push( 0, sign, 0 );
  21609. // uv
  21610. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21611. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21612. uvs.push( uv.x, uv.y );
  21613. // increase index
  21614. index ++;
  21615. }
  21616. // generate indices
  21617. for ( x = 0; x < radialSegments; x ++ ) {
  21618. var c = centerIndexStart + x;
  21619. var i = centerIndexEnd + x;
  21620. if ( top === true ) {
  21621. // face top
  21622. indices.push( i, i + 1, c );
  21623. } else {
  21624. // face bottom
  21625. indices.push( i + 1, i, c );
  21626. }
  21627. groupCount += 3;
  21628. }
  21629. // add a group to the geometry. this will ensure multi material support
  21630. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21631. // calculate new start value for groups
  21632. groupStart += groupCount;
  21633. }
  21634. }
  21635. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21636. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  21637. /**
  21638. * @author abelnation / http://github.com/abelnation
  21639. */
  21640. // ConeGeometry
  21641. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21642. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21643. this.type = 'ConeGeometry';
  21644. this.parameters = {
  21645. radius: radius,
  21646. height: height,
  21647. radialSegments: radialSegments,
  21648. heightSegments: heightSegments,
  21649. openEnded: openEnded,
  21650. thetaStart: thetaStart,
  21651. thetaLength: thetaLength
  21652. };
  21653. }
  21654. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  21655. ConeGeometry.prototype.constructor = ConeGeometry;
  21656. // ConeBufferGeometry
  21657. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21658. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21659. this.type = 'ConeBufferGeometry';
  21660. this.parameters = {
  21661. radius: radius,
  21662. height: height,
  21663. radialSegments: radialSegments,
  21664. heightSegments: heightSegments,
  21665. openEnded: openEnded,
  21666. thetaStart: thetaStart,
  21667. thetaLength: thetaLength
  21668. };
  21669. }
  21670. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  21671. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  21672. /**
  21673. * @author benaadams / https://twitter.com/ben_a_adams
  21674. * @author Mugen87 / https://github.com/Mugen87
  21675. * @author hughes
  21676. */
  21677. // CircleGeometry
  21678. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  21679. Geometry.call( this );
  21680. this.type = 'CircleGeometry';
  21681. this.parameters = {
  21682. radius: radius,
  21683. segments: segments,
  21684. thetaStart: thetaStart,
  21685. thetaLength: thetaLength
  21686. };
  21687. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21688. this.mergeVertices();
  21689. }
  21690. CircleGeometry.prototype = Object.create( Geometry.prototype );
  21691. CircleGeometry.prototype.constructor = CircleGeometry;
  21692. // CircleBufferGeometry
  21693. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  21694. BufferGeometry.call( this );
  21695. this.type = 'CircleBufferGeometry';
  21696. this.parameters = {
  21697. radius: radius,
  21698. segments: segments,
  21699. thetaStart: thetaStart,
  21700. thetaLength: thetaLength
  21701. };
  21702. radius = radius || 50;
  21703. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21704. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21705. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21706. // buffers
  21707. var indices = [];
  21708. var vertices = [];
  21709. var normals = [];
  21710. var uvs = [];
  21711. // helper variables
  21712. var i, s;
  21713. var vertex = new Vector3();
  21714. var uv = new Vector2();
  21715. // center point
  21716. vertices.push( 0, 0, 0 );
  21717. normals.push( 0, 0, 1 );
  21718. uvs.push( 0.5, 0.5 );
  21719. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21720. var segment = thetaStart + s / segments * thetaLength;
  21721. // vertex
  21722. vertex.x = radius * Math.cos( segment );
  21723. vertex.y = radius * Math.sin( segment );
  21724. vertices.push( vertex.x, vertex.y, vertex.z );
  21725. // normal
  21726. normals.push( 0, 0, 1 );
  21727. // uvs
  21728. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21729. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21730. uvs.push( uv.x, uv.y );
  21731. }
  21732. // indices
  21733. for ( i = 1; i <= segments; i ++ ) {
  21734. indices.push( i, i + 1, 0 );
  21735. }
  21736. // build geometry
  21737. this.setIndex( indices );
  21738. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21739. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21740. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21741. }
  21742. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21743. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  21744. var Geometries = Object.freeze({
  21745. WireframeGeometry: WireframeGeometry,
  21746. ParametricGeometry: ParametricGeometry,
  21747. ParametricBufferGeometry: ParametricBufferGeometry,
  21748. TetrahedronGeometry: TetrahedronGeometry,
  21749. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  21750. OctahedronGeometry: OctahedronGeometry,
  21751. OctahedronBufferGeometry: OctahedronBufferGeometry,
  21752. IcosahedronGeometry: IcosahedronGeometry,
  21753. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  21754. DodecahedronGeometry: DodecahedronGeometry,
  21755. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  21756. PolyhedronGeometry: PolyhedronGeometry,
  21757. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  21758. TubeGeometry: TubeGeometry,
  21759. TubeBufferGeometry: TubeBufferGeometry,
  21760. TorusKnotGeometry: TorusKnotGeometry,
  21761. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  21762. TorusGeometry: TorusGeometry,
  21763. TorusBufferGeometry: TorusBufferGeometry,
  21764. TextGeometry: TextGeometry,
  21765. TextBufferGeometry: TextBufferGeometry,
  21766. SphereGeometry: SphereGeometry,
  21767. SphereBufferGeometry: SphereBufferGeometry,
  21768. RingGeometry: RingGeometry,
  21769. RingBufferGeometry: RingBufferGeometry,
  21770. PlaneGeometry: PlaneGeometry,
  21771. PlaneBufferGeometry: PlaneBufferGeometry,
  21772. LatheGeometry: LatheGeometry,
  21773. LatheBufferGeometry: LatheBufferGeometry,
  21774. ShapeGeometry: ShapeGeometry,
  21775. ShapeBufferGeometry: ShapeBufferGeometry,
  21776. ExtrudeGeometry: ExtrudeGeometry,
  21777. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  21778. EdgesGeometry: EdgesGeometry,
  21779. ConeGeometry: ConeGeometry,
  21780. ConeBufferGeometry: ConeBufferGeometry,
  21781. CylinderGeometry: CylinderGeometry,
  21782. CylinderBufferGeometry: CylinderBufferGeometry,
  21783. CircleGeometry: CircleGeometry,
  21784. CircleBufferGeometry: CircleBufferGeometry,
  21785. BoxGeometry: BoxGeometry,
  21786. BoxBufferGeometry: BoxBufferGeometry
  21787. });
  21788. /**
  21789. * @author mrdoob / http://mrdoob.com/
  21790. *
  21791. * parameters = {
  21792. * color: <THREE.Color>,
  21793. * opacity: <float>
  21794. * }
  21795. */
  21796. function ShadowMaterial( parameters ) {
  21797. Material.call( this );
  21798. this.type = 'ShadowMaterial';
  21799. this.color = new Color( 0x000000 );
  21800. this.opacity = 1.0;
  21801. this.lights = true;
  21802. this.transparent = true;
  21803. this.setValues( parameters );
  21804. }
  21805. ShadowMaterial.prototype = Object.create( Material.prototype );
  21806. ShadowMaterial.prototype.constructor = ShadowMaterial;
  21807. ShadowMaterial.prototype.isShadowMaterial = true;
  21808. /**
  21809. * @author mrdoob / http://mrdoob.com/
  21810. */
  21811. function RawShaderMaterial( parameters ) {
  21812. ShaderMaterial.call( this, parameters );
  21813. this.type = 'RawShaderMaterial';
  21814. }
  21815. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  21816. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  21817. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  21818. /**
  21819. * @author WestLangley / http://github.com/WestLangley
  21820. *
  21821. * parameters = {
  21822. * color: <hex>,
  21823. * roughness: <float>,
  21824. * metalness: <float>,
  21825. * opacity: <float>,
  21826. *
  21827. * map: new THREE.Texture( <Image> ),
  21828. *
  21829. * lightMap: new THREE.Texture( <Image> ),
  21830. * lightMapIntensity: <float>
  21831. *
  21832. * aoMap: new THREE.Texture( <Image> ),
  21833. * aoMapIntensity: <float>
  21834. *
  21835. * emissive: <hex>,
  21836. * emissiveIntensity: <float>
  21837. * emissiveMap: new THREE.Texture( <Image> ),
  21838. *
  21839. * bumpMap: new THREE.Texture( <Image> ),
  21840. * bumpScale: <float>,
  21841. *
  21842. * normalMap: new THREE.Texture( <Image> ),
  21843. * normalScale: <Vector2>,
  21844. *
  21845. * displacementMap: new THREE.Texture( <Image> ),
  21846. * displacementScale: <float>,
  21847. * displacementBias: <float>,
  21848. *
  21849. * roughnessMap: new THREE.Texture( <Image> ),
  21850. *
  21851. * metalnessMap: new THREE.Texture( <Image> ),
  21852. *
  21853. * alphaMap: new THREE.Texture( <Image> ),
  21854. *
  21855. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21856. * envMapIntensity: <float>
  21857. *
  21858. * refractionRatio: <float>,
  21859. *
  21860. * wireframe: <boolean>,
  21861. * wireframeLinewidth: <float>,
  21862. *
  21863. * skinning: <bool>,
  21864. * morphTargets: <bool>,
  21865. * morphNormals: <bool>
  21866. * }
  21867. */
  21868. function MeshStandardMaterial( parameters ) {
  21869. Material.call( this );
  21870. this.defines = { 'STANDARD': '' };
  21871. this.type = 'MeshStandardMaterial';
  21872. this.color = new Color( 0xffffff ); // diffuse
  21873. this.roughness = 0.5;
  21874. this.metalness = 0.5;
  21875. this.map = null;
  21876. this.lightMap = null;
  21877. this.lightMapIntensity = 1.0;
  21878. this.aoMap = null;
  21879. this.aoMapIntensity = 1.0;
  21880. this.emissive = new Color( 0x000000 );
  21881. this.emissiveIntensity = 1.0;
  21882. this.emissiveMap = null;
  21883. this.bumpMap = null;
  21884. this.bumpScale = 1;
  21885. this.normalMap = null;
  21886. this.normalScale = new Vector2( 1, 1 );
  21887. this.displacementMap = null;
  21888. this.displacementScale = 1;
  21889. this.displacementBias = 0;
  21890. this.roughnessMap = null;
  21891. this.metalnessMap = null;
  21892. this.alphaMap = null;
  21893. this.envMap = null;
  21894. this.envMapIntensity = 1.0;
  21895. this.refractionRatio = 0.98;
  21896. this.wireframe = false;
  21897. this.wireframeLinewidth = 1;
  21898. this.wireframeLinecap = 'round';
  21899. this.wireframeLinejoin = 'round';
  21900. this.skinning = false;
  21901. this.morphTargets = false;
  21902. this.morphNormals = false;
  21903. this.setValues( parameters );
  21904. }
  21905. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  21906. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  21907. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21908. MeshStandardMaterial.prototype.copy = function ( source ) {
  21909. Material.prototype.copy.call( this, source );
  21910. this.defines = { 'STANDARD': '' };
  21911. this.color.copy( source.color );
  21912. this.roughness = source.roughness;
  21913. this.metalness = source.metalness;
  21914. this.map = source.map;
  21915. this.lightMap = source.lightMap;
  21916. this.lightMapIntensity = source.lightMapIntensity;
  21917. this.aoMap = source.aoMap;
  21918. this.aoMapIntensity = source.aoMapIntensity;
  21919. this.emissive.copy( source.emissive );
  21920. this.emissiveMap = source.emissiveMap;
  21921. this.emissiveIntensity = source.emissiveIntensity;
  21922. this.bumpMap = source.bumpMap;
  21923. this.bumpScale = source.bumpScale;
  21924. this.normalMap = source.normalMap;
  21925. this.normalScale.copy( source.normalScale );
  21926. this.displacementMap = source.displacementMap;
  21927. this.displacementScale = source.displacementScale;
  21928. this.displacementBias = source.displacementBias;
  21929. this.roughnessMap = source.roughnessMap;
  21930. this.metalnessMap = source.metalnessMap;
  21931. this.alphaMap = source.alphaMap;
  21932. this.envMap = source.envMap;
  21933. this.envMapIntensity = source.envMapIntensity;
  21934. this.refractionRatio = source.refractionRatio;
  21935. this.wireframe = source.wireframe;
  21936. this.wireframeLinewidth = source.wireframeLinewidth;
  21937. this.wireframeLinecap = source.wireframeLinecap;
  21938. this.wireframeLinejoin = source.wireframeLinejoin;
  21939. this.skinning = source.skinning;
  21940. this.morphTargets = source.morphTargets;
  21941. this.morphNormals = source.morphNormals;
  21942. return this;
  21943. };
  21944. /**
  21945. * @author WestLangley / http://github.com/WestLangley
  21946. *
  21947. * parameters = {
  21948. * reflectivity: <float>
  21949. * }
  21950. */
  21951. function MeshPhysicalMaterial( parameters ) {
  21952. MeshStandardMaterial.call( this );
  21953. this.defines = { 'PHYSICAL': '' };
  21954. this.type = 'MeshPhysicalMaterial';
  21955. this.reflectivity = 0.5; // maps to F0 = 0.04
  21956. this.clearCoat = 0.0;
  21957. this.clearCoatRoughness = 0.0;
  21958. this.setValues( parameters );
  21959. }
  21960. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  21961. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  21962. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21963. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  21964. MeshStandardMaterial.prototype.copy.call( this, source );
  21965. this.defines = { 'PHYSICAL': '' };
  21966. this.reflectivity = source.reflectivity;
  21967. this.clearCoat = source.clearCoat;
  21968. this.clearCoatRoughness = source.clearCoatRoughness;
  21969. return this;
  21970. };
  21971. /**
  21972. * @author mrdoob / http://mrdoob.com/
  21973. * @author alteredq / http://alteredqualia.com/
  21974. *
  21975. * parameters = {
  21976. * color: <hex>,
  21977. * specular: <hex>,
  21978. * shininess: <float>,
  21979. * opacity: <float>,
  21980. *
  21981. * map: new THREE.Texture( <Image> ),
  21982. *
  21983. * lightMap: new THREE.Texture( <Image> ),
  21984. * lightMapIntensity: <float>
  21985. *
  21986. * aoMap: new THREE.Texture( <Image> ),
  21987. * aoMapIntensity: <float>
  21988. *
  21989. * emissive: <hex>,
  21990. * emissiveIntensity: <float>
  21991. * emissiveMap: new THREE.Texture( <Image> ),
  21992. *
  21993. * bumpMap: new THREE.Texture( <Image> ),
  21994. * bumpScale: <float>,
  21995. *
  21996. * normalMap: new THREE.Texture( <Image> ),
  21997. * normalScale: <Vector2>,
  21998. *
  21999. * displacementMap: new THREE.Texture( <Image> ),
  22000. * displacementScale: <float>,
  22001. * displacementBias: <float>,
  22002. *
  22003. * specularMap: new THREE.Texture( <Image> ),
  22004. *
  22005. * alphaMap: new THREE.Texture( <Image> ),
  22006. *
  22007. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  22008. * combine: THREE.Multiply,
  22009. * reflectivity: <float>,
  22010. * refractionRatio: <float>,
  22011. *
  22012. * wireframe: <boolean>,
  22013. * wireframeLinewidth: <float>,
  22014. *
  22015. * skinning: <bool>,
  22016. * morphTargets: <bool>,
  22017. * morphNormals: <bool>
  22018. * }
  22019. */
  22020. function MeshPhongMaterial( parameters ) {
  22021. Material.call( this );
  22022. this.type = 'MeshPhongMaterial';
  22023. this.color = new Color( 0xffffff ); // diffuse
  22024. this.specular = new Color( 0x111111 );
  22025. this.shininess = 30;
  22026. this.map = null;
  22027. this.lightMap = null;
  22028. this.lightMapIntensity = 1.0;
  22029. this.aoMap = null;
  22030. this.aoMapIntensity = 1.0;
  22031. this.emissive = new Color( 0x000000 );
  22032. this.emissiveIntensity = 1.0;
  22033. this.emissiveMap = null;
  22034. this.bumpMap = null;
  22035. this.bumpScale = 1;
  22036. this.normalMap = null;
  22037. this.normalScale = new Vector2( 1, 1 );
  22038. this.displacementMap = null;
  22039. this.displacementScale = 1;
  22040. this.displacementBias = 0;
  22041. this.specularMap = null;
  22042. this.alphaMap = null;
  22043. this.envMap = null;
  22044. this.combine = MultiplyOperation;
  22045. this.reflectivity = 1;
  22046. this.refractionRatio = 0.98;
  22047. this.wireframe = false;
  22048. this.wireframeLinewidth = 1;
  22049. this.wireframeLinecap = 'round';
  22050. this.wireframeLinejoin = 'round';
  22051. this.skinning = false;
  22052. this.morphTargets = false;
  22053. this.morphNormals = false;
  22054. this.setValues( parameters );
  22055. }
  22056. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  22057. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  22058. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22059. MeshPhongMaterial.prototype.copy = function ( source ) {
  22060. Material.prototype.copy.call( this, source );
  22061. this.color.copy( source.color );
  22062. this.specular.copy( source.specular );
  22063. this.shininess = source.shininess;
  22064. this.map = source.map;
  22065. this.lightMap = source.lightMap;
  22066. this.lightMapIntensity = source.lightMapIntensity;
  22067. this.aoMap = source.aoMap;
  22068. this.aoMapIntensity = source.aoMapIntensity;
  22069. this.emissive.copy( source.emissive );
  22070. this.emissiveMap = source.emissiveMap;
  22071. this.emissiveIntensity = source.emissiveIntensity;
  22072. this.bumpMap = source.bumpMap;
  22073. this.bumpScale = source.bumpScale;
  22074. this.normalMap = source.normalMap;
  22075. this.normalScale.copy( source.normalScale );
  22076. this.displacementMap = source.displacementMap;
  22077. this.displacementScale = source.displacementScale;
  22078. this.displacementBias = source.displacementBias;
  22079. this.specularMap = source.specularMap;
  22080. this.alphaMap = source.alphaMap;
  22081. this.envMap = source.envMap;
  22082. this.combine = source.combine;
  22083. this.reflectivity = source.reflectivity;
  22084. this.refractionRatio = source.refractionRatio;
  22085. this.wireframe = source.wireframe;
  22086. this.wireframeLinewidth = source.wireframeLinewidth;
  22087. this.wireframeLinecap = source.wireframeLinecap;
  22088. this.wireframeLinejoin = source.wireframeLinejoin;
  22089. this.skinning = source.skinning;
  22090. this.morphTargets = source.morphTargets;
  22091. this.morphNormals = source.morphNormals;
  22092. return this;
  22093. };
  22094. /**
  22095. * @author takahirox / http://github.com/takahirox
  22096. *
  22097. * parameters = {
  22098. * gradientMap: new THREE.Texture( <Image> )
  22099. * }
  22100. */
  22101. function MeshToonMaterial( parameters ) {
  22102. MeshPhongMaterial.call( this );
  22103. this.defines = { 'TOON': '' };
  22104. this.type = 'MeshToonMaterial';
  22105. this.gradientMap = null;
  22106. this.setValues( parameters );
  22107. }
  22108. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  22109. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  22110. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22111. MeshToonMaterial.prototype.copy = function ( source ) {
  22112. MeshPhongMaterial.prototype.copy.call( this, source );
  22113. this.gradientMap = source.gradientMap;
  22114. return this;
  22115. };
  22116. /**
  22117. * @author mrdoob / http://mrdoob.com/
  22118. * @author WestLangley / http://github.com/WestLangley
  22119. *
  22120. * parameters = {
  22121. * opacity: <float>,
  22122. *
  22123. * bumpMap: new THREE.Texture( <Image> ),
  22124. * bumpScale: <float>,
  22125. *
  22126. * normalMap: new THREE.Texture( <Image> ),
  22127. * normalScale: <Vector2>,
  22128. *
  22129. * displacementMap: new THREE.Texture( <Image> ),
  22130. * displacementScale: <float>,
  22131. * displacementBias: <float>,
  22132. *
  22133. * wireframe: <boolean>,
  22134. * wireframeLinewidth: <float>
  22135. *
  22136. * skinning: <bool>,
  22137. * morphTargets: <bool>,
  22138. * morphNormals: <bool>
  22139. * }
  22140. */
  22141. function MeshNormalMaterial( parameters ) {
  22142. Material.call( this );
  22143. this.type = 'MeshNormalMaterial';
  22144. this.bumpMap = null;
  22145. this.bumpScale = 1;
  22146. this.normalMap = null;
  22147. this.normalScale = new Vector2( 1, 1 );
  22148. this.displacementMap = null;
  22149. this.displacementScale = 1;
  22150. this.displacementBias = 0;
  22151. this.wireframe = false;
  22152. this.wireframeLinewidth = 1;
  22153. this.fog = false;
  22154. this.lights = false;
  22155. this.skinning = false;
  22156. this.morphTargets = false;
  22157. this.morphNormals = false;
  22158. this.setValues( parameters );
  22159. }
  22160. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  22161. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  22162. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22163. MeshNormalMaterial.prototype.copy = function ( source ) {
  22164. Material.prototype.copy.call( this, source );
  22165. this.bumpMap = source.bumpMap;
  22166. this.bumpScale = source.bumpScale;
  22167. this.normalMap = source.normalMap;
  22168. this.normalScale.copy( source.normalScale );
  22169. this.displacementMap = source.displacementMap;
  22170. this.displacementScale = source.displacementScale;
  22171. this.displacementBias = source.displacementBias;
  22172. this.wireframe = source.wireframe;
  22173. this.wireframeLinewidth = source.wireframeLinewidth;
  22174. this.skinning = source.skinning;
  22175. this.morphTargets = source.morphTargets;
  22176. this.morphNormals = source.morphNormals;
  22177. return this;
  22178. };
  22179. /**
  22180. * @author mrdoob / http://mrdoob.com/
  22181. * @author alteredq / http://alteredqualia.com/
  22182. *
  22183. * parameters = {
  22184. * color: <hex>,
  22185. * opacity: <float>,
  22186. *
  22187. * map: new THREE.Texture( <Image> ),
  22188. *
  22189. * lightMap: new THREE.Texture( <Image> ),
  22190. * lightMapIntensity: <float>
  22191. *
  22192. * aoMap: new THREE.Texture( <Image> ),
  22193. * aoMapIntensity: <float>
  22194. *
  22195. * emissive: <hex>,
  22196. * emissiveIntensity: <float>
  22197. * emissiveMap: new THREE.Texture( <Image> ),
  22198. *
  22199. * specularMap: new THREE.Texture( <Image> ),
  22200. *
  22201. * alphaMap: new THREE.Texture( <Image> ),
  22202. *
  22203. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  22204. * combine: THREE.Multiply,
  22205. * reflectivity: <float>,
  22206. * refractionRatio: <float>,
  22207. *
  22208. * wireframe: <boolean>,
  22209. * wireframeLinewidth: <float>,
  22210. *
  22211. * skinning: <bool>,
  22212. * morphTargets: <bool>,
  22213. * morphNormals: <bool>
  22214. * }
  22215. */
  22216. function MeshLambertMaterial( parameters ) {
  22217. Material.call( this );
  22218. this.type = 'MeshLambertMaterial';
  22219. this.color = new Color( 0xffffff ); // diffuse
  22220. this.map = null;
  22221. this.lightMap = null;
  22222. this.lightMapIntensity = 1.0;
  22223. this.aoMap = null;
  22224. this.aoMapIntensity = 1.0;
  22225. this.emissive = new Color( 0x000000 );
  22226. this.emissiveIntensity = 1.0;
  22227. this.emissiveMap = null;
  22228. this.specularMap = null;
  22229. this.alphaMap = null;
  22230. this.envMap = null;
  22231. this.combine = MultiplyOperation;
  22232. this.reflectivity = 1;
  22233. this.refractionRatio = 0.98;
  22234. this.wireframe = false;
  22235. this.wireframeLinewidth = 1;
  22236. this.wireframeLinecap = 'round';
  22237. this.wireframeLinejoin = 'round';
  22238. this.skinning = false;
  22239. this.morphTargets = false;
  22240. this.morphNormals = false;
  22241. this.setValues( parameters );
  22242. }
  22243. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  22244. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  22245. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22246. MeshLambertMaterial.prototype.copy = function ( source ) {
  22247. Material.prototype.copy.call( this, source );
  22248. this.color.copy( source.color );
  22249. this.map = source.map;
  22250. this.lightMap = source.lightMap;
  22251. this.lightMapIntensity = source.lightMapIntensity;
  22252. this.aoMap = source.aoMap;
  22253. this.aoMapIntensity = source.aoMapIntensity;
  22254. this.emissive.copy( source.emissive );
  22255. this.emissiveMap = source.emissiveMap;
  22256. this.emissiveIntensity = source.emissiveIntensity;
  22257. this.specularMap = source.specularMap;
  22258. this.alphaMap = source.alphaMap;
  22259. this.envMap = source.envMap;
  22260. this.combine = source.combine;
  22261. this.reflectivity = source.reflectivity;
  22262. this.refractionRatio = source.refractionRatio;
  22263. this.wireframe = source.wireframe;
  22264. this.wireframeLinewidth = source.wireframeLinewidth;
  22265. this.wireframeLinecap = source.wireframeLinecap;
  22266. this.wireframeLinejoin = source.wireframeLinejoin;
  22267. this.skinning = source.skinning;
  22268. this.morphTargets = source.morphTargets;
  22269. this.morphNormals = source.morphNormals;
  22270. return this;
  22271. };
  22272. /**
  22273. * @author alteredq / http://alteredqualia.com/
  22274. *
  22275. * parameters = {
  22276. * color: <hex>,
  22277. * opacity: <float>,
  22278. *
  22279. * linewidth: <float>,
  22280. *
  22281. * scale: <float>,
  22282. * dashSize: <float>,
  22283. * gapSize: <float>
  22284. * }
  22285. */
  22286. function LineDashedMaterial( parameters ) {
  22287. LineBasicMaterial.call( this );
  22288. this.type = 'LineDashedMaterial';
  22289. this.scale = 1;
  22290. this.dashSize = 3;
  22291. this.gapSize = 1;
  22292. this.setValues( parameters );
  22293. }
  22294. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  22295. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  22296. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22297. LineDashedMaterial.prototype.copy = function ( source ) {
  22298. LineBasicMaterial.prototype.copy.call( this, source );
  22299. this.scale = source.scale;
  22300. this.dashSize = source.dashSize;
  22301. this.gapSize = source.gapSize;
  22302. return this;
  22303. };
  22304. var Materials = Object.freeze({
  22305. ShadowMaterial: ShadowMaterial,
  22306. SpriteMaterial: SpriteMaterial,
  22307. RawShaderMaterial: RawShaderMaterial,
  22308. ShaderMaterial: ShaderMaterial,
  22309. PointsMaterial: PointsMaterial,
  22310. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22311. MeshStandardMaterial: MeshStandardMaterial,
  22312. MeshPhongMaterial: MeshPhongMaterial,
  22313. MeshToonMaterial: MeshToonMaterial,
  22314. MeshNormalMaterial: MeshNormalMaterial,
  22315. MeshLambertMaterial: MeshLambertMaterial,
  22316. MeshDepthMaterial: MeshDepthMaterial,
  22317. MeshDistanceMaterial: MeshDistanceMaterial,
  22318. MeshBasicMaterial: MeshBasicMaterial,
  22319. LineDashedMaterial: LineDashedMaterial,
  22320. LineBasicMaterial: LineBasicMaterial,
  22321. Material: Material
  22322. });
  22323. /**
  22324. * @author mrdoob / http://mrdoob.com/
  22325. */
  22326. var Cache = {
  22327. enabled: false,
  22328. files: {},
  22329. add: function ( key, file ) {
  22330. if ( this.enabled === false ) return;
  22331. // console.log( 'THREE.Cache', 'Adding key:', key );
  22332. this.files[ key ] = file;
  22333. },
  22334. get: function ( key ) {
  22335. if ( this.enabled === false ) return;
  22336. // console.log( 'THREE.Cache', 'Checking key:', key );
  22337. return this.files[ key ];
  22338. },
  22339. remove: function ( key ) {
  22340. delete this.files[ key ];
  22341. },
  22342. clear: function () {
  22343. this.files = {};
  22344. }
  22345. };
  22346. /**
  22347. * @author mrdoob / http://mrdoob.com/
  22348. */
  22349. function LoadingManager( onLoad, onProgress, onError ) {
  22350. var scope = this;
  22351. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  22352. this.onStart = undefined;
  22353. this.onLoad = onLoad;
  22354. this.onProgress = onProgress;
  22355. this.onError = onError;
  22356. this.itemStart = function ( url ) {
  22357. itemsTotal ++;
  22358. if ( isLoading === false ) {
  22359. if ( scope.onStart !== undefined ) {
  22360. scope.onStart( url, itemsLoaded, itemsTotal );
  22361. }
  22362. }
  22363. isLoading = true;
  22364. };
  22365. this.itemEnd = function ( url ) {
  22366. itemsLoaded ++;
  22367. if ( scope.onProgress !== undefined ) {
  22368. scope.onProgress( url, itemsLoaded, itemsTotal );
  22369. }
  22370. if ( itemsLoaded === itemsTotal ) {
  22371. isLoading = false;
  22372. if ( scope.onLoad !== undefined ) {
  22373. scope.onLoad();
  22374. }
  22375. }
  22376. };
  22377. this.itemError = function ( url ) {
  22378. if ( scope.onError !== undefined ) {
  22379. scope.onError( url );
  22380. }
  22381. };
  22382. }
  22383. var DefaultLoadingManager = new LoadingManager();
  22384. /**
  22385. * @author mrdoob / http://mrdoob.com/
  22386. */
  22387. function FileLoader( manager ) {
  22388. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22389. }
  22390. Object.assign( FileLoader.prototype, {
  22391. load: function ( url, onLoad, onProgress, onError ) {
  22392. if ( url === undefined ) url = '';
  22393. if ( this.path !== undefined ) url = this.path + url;
  22394. var scope = this;
  22395. var cached = Cache.get( url );
  22396. if ( cached !== undefined ) {
  22397. scope.manager.itemStart( url );
  22398. setTimeout( function () {
  22399. if ( onLoad ) onLoad( cached );
  22400. scope.manager.itemEnd( url );
  22401. }, 0 );
  22402. return cached;
  22403. }
  22404. // Check for data: URI
  22405. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22406. var dataUriRegexResult = url.match( dataUriRegex );
  22407. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22408. if ( dataUriRegexResult ) {
  22409. var mimeType = dataUriRegexResult[ 1 ];
  22410. var isBase64 = !! dataUriRegexResult[ 2 ];
  22411. var data = dataUriRegexResult[ 3 ];
  22412. data = window.decodeURIComponent( data );
  22413. if ( isBase64 ) data = window.atob( data );
  22414. try {
  22415. var response;
  22416. var responseType = ( this.responseType || '' ).toLowerCase();
  22417. switch ( responseType ) {
  22418. case 'arraybuffer':
  22419. case 'blob':
  22420. response = new ArrayBuffer( data.length );
  22421. var view = new Uint8Array( response );
  22422. for ( var i = 0; i < data.length; i ++ ) {
  22423. view[ i ] = data.charCodeAt( i );
  22424. }
  22425. if ( responseType === 'blob' ) {
  22426. response = new Blob( [ response ], { type: mimeType } );
  22427. }
  22428. break;
  22429. case 'document':
  22430. var parser = new DOMParser();
  22431. response = parser.parseFromString( data, mimeType );
  22432. break;
  22433. case 'json':
  22434. response = JSON.parse( data );
  22435. break;
  22436. default: // 'text' or other
  22437. response = data;
  22438. break;
  22439. }
  22440. // Wait for next browser tick
  22441. window.setTimeout( function () {
  22442. if ( onLoad ) onLoad( response );
  22443. scope.manager.itemEnd( url );
  22444. }, 0 );
  22445. } catch ( error ) {
  22446. // Wait for next browser tick
  22447. window.setTimeout( function () {
  22448. if ( onError ) onError( error );
  22449. scope.manager.itemEnd( url );
  22450. scope.manager.itemError( url );
  22451. }, 0 );
  22452. }
  22453. } else {
  22454. var request = new XMLHttpRequest();
  22455. request.open( 'GET', url, true );
  22456. request.addEventListener( 'load', function ( event ) {
  22457. var response = event.target.response;
  22458. Cache.add( url, response );
  22459. if ( this.status === 200 ) {
  22460. if ( onLoad ) onLoad( response );
  22461. scope.manager.itemEnd( url );
  22462. } else if ( this.status === 0 ) {
  22463. // Some browsers return HTTP Status 0 when using non-http protocol
  22464. // e.g. 'file://' or 'data://'. Handle as success.
  22465. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22466. if ( onLoad ) onLoad( response );
  22467. scope.manager.itemEnd( url );
  22468. } else {
  22469. if ( onError ) onError( event );
  22470. scope.manager.itemEnd( url );
  22471. scope.manager.itemError( url );
  22472. }
  22473. }, false );
  22474. if ( onProgress !== undefined ) {
  22475. request.addEventListener( 'progress', function ( event ) {
  22476. onProgress( event );
  22477. }, false );
  22478. }
  22479. request.addEventListener( 'error', function ( event ) {
  22480. if ( onError ) onError( event );
  22481. scope.manager.itemEnd( url );
  22482. scope.manager.itemError( url );
  22483. }, false );
  22484. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22485. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22486. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22487. for ( var header in this.requestHeader ) {
  22488. request.setRequestHeader( header, this.requestHeader[ header ] );
  22489. }
  22490. request.send( null );
  22491. }
  22492. scope.manager.itemStart( url );
  22493. return request;
  22494. },
  22495. setPath: function ( value ) {
  22496. this.path = value;
  22497. return this;
  22498. },
  22499. setResponseType: function ( value ) {
  22500. this.responseType = value;
  22501. return this;
  22502. },
  22503. setWithCredentials: function ( value ) {
  22504. this.withCredentials = value;
  22505. return this;
  22506. },
  22507. setMimeType: function ( value ) {
  22508. this.mimeType = value;
  22509. return this;
  22510. },
  22511. setRequestHeader: function ( value ) {
  22512. this.requestHeader = value;
  22513. return this;
  22514. }
  22515. } );
  22516. /**
  22517. * @author mrdoob / http://mrdoob.com/
  22518. *
  22519. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22520. */
  22521. function CompressedTextureLoader( manager ) {
  22522. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22523. // override in sub classes
  22524. this._parser = null;
  22525. }
  22526. Object.assign( CompressedTextureLoader.prototype, {
  22527. load: function ( url, onLoad, onProgress, onError ) {
  22528. var scope = this;
  22529. var images = [];
  22530. var texture = new CompressedTexture();
  22531. texture.image = images;
  22532. var loader = new FileLoader( this.manager );
  22533. loader.setPath( this.path );
  22534. loader.setResponseType( 'arraybuffer' );
  22535. function loadTexture( i ) {
  22536. loader.load( url[ i ], function ( buffer ) {
  22537. var texDatas = scope._parser( buffer, true );
  22538. images[ i ] = {
  22539. width: texDatas.width,
  22540. height: texDatas.height,
  22541. format: texDatas.format,
  22542. mipmaps: texDatas.mipmaps
  22543. };
  22544. loaded += 1;
  22545. if ( loaded === 6 ) {
  22546. if ( texDatas.mipmapCount === 1 )
  22547. texture.minFilter = LinearFilter;
  22548. texture.format = texDatas.format;
  22549. texture.needsUpdate = true;
  22550. if ( onLoad ) onLoad( texture );
  22551. }
  22552. }, onProgress, onError );
  22553. }
  22554. if ( Array.isArray( url ) ) {
  22555. var loaded = 0;
  22556. for ( var i = 0, il = url.length; i < il; ++ i ) {
  22557. loadTexture( i );
  22558. }
  22559. } else {
  22560. // compressed cubemap texture stored in a single DDS file
  22561. loader.load( url, function ( buffer ) {
  22562. var texDatas = scope._parser( buffer, true );
  22563. if ( texDatas.isCubemap ) {
  22564. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22565. for ( var f = 0; f < faces; f ++ ) {
  22566. images[ f ] = { mipmaps : [] };
  22567. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  22568. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22569. images[ f ].format = texDatas.format;
  22570. images[ f ].width = texDatas.width;
  22571. images[ f ].height = texDatas.height;
  22572. }
  22573. }
  22574. } else {
  22575. texture.image.width = texDatas.width;
  22576. texture.image.height = texDatas.height;
  22577. texture.mipmaps = texDatas.mipmaps;
  22578. }
  22579. if ( texDatas.mipmapCount === 1 ) {
  22580. texture.minFilter = LinearFilter;
  22581. }
  22582. texture.format = texDatas.format;
  22583. texture.needsUpdate = true;
  22584. if ( onLoad ) onLoad( texture );
  22585. }, onProgress, onError );
  22586. }
  22587. return texture;
  22588. },
  22589. setPath: function ( value ) {
  22590. this.path = value;
  22591. return this;
  22592. }
  22593. } );
  22594. /**
  22595. * @author Nikos M. / https://github.com/foo123/
  22596. *
  22597. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22598. */
  22599. function DataTextureLoader( manager ) {
  22600. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22601. // override in sub classes
  22602. this._parser = null;
  22603. }
  22604. Object.assign( DataTextureLoader.prototype, {
  22605. load: function ( url, onLoad, onProgress, onError ) {
  22606. var scope = this;
  22607. var texture = new DataTexture();
  22608. var loader = new FileLoader( this.manager );
  22609. loader.setResponseType( 'arraybuffer' );
  22610. loader.load( url, function ( buffer ) {
  22611. var texData = scope._parser( buffer );
  22612. if ( ! texData ) return;
  22613. if ( undefined !== texData.image ) {
  22614. texture.image = texData.image;
  22615. } else if ( undefined !== texData.data ) {
  22616. texture.image.width = texData.width;
  22617. texture.image.height = texData.height;
  22618. texture.image.data = texData.data;
  22619. }
  22620. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  22621. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  22622. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  22623. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  22624. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  22625. if ( undefined !== texData.format ) {
  22626. texture.format = texData.format;
  22627. }
  22628. if ( undefined !== texData.type ) {
  22629. texture.type = texData.type;
  22630. }
  22631. if ( undefined !== texData.mipmaps ) {
  22632. texture.mipmaps = texData.mipmaps;
  22633. }
  22634. if ( 1 === texData.mipmapCount ) {
  22635. texture.minFilter = LinearFilter;
  22636. }
  22637. texture.needsUpdate = true;
  22638. if ( onLoad ) onLoad( texture, texData );
  22639. }, onProgress, onError );
  22640. return texture;
  22641. }
  22642. } );
  22643. /**
  22644. * @author mrdoob / http://mrdoob.com/
  22645. */
  22646. function ImageLoader( manager ) {
  22647. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22648. }
  22649. Object.assign( ImageLoader.prototype, {
  22650. crossOrigin: 'Anonymous',
  22651. load: function ( url, onLoad, onProgress, onError ) {
  22652. if ( url === undefined ) url = '';
  22653. if ( this.path !== undefined ) url = this.path + url;
  22654. var scope = this;
  22655. var cached = Cache.get( url );
  22656. if ( cached !== undefined ) {
  22657. scope.manager.itemStart( url );
  22658. setTimeout( function () {
  22659. if ( onLoad ) onLoad( cached );
  22660. scope.manager.itemEnd( url );
  22661. }, 0 );
  22662. return cached;
  22663. }
  22664. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22665. image.addEventListener( 'load', function () {
  22666. Cache.add( url, this );
  22667. if ( onLoad ) onLoad( this );
  22668. scope.manager.itemEnd( url );
  22669. }, false );
  22670. /*
  22671. image.addEventListener( 'progress', function ( event ) {
  22672. if ( onProgress ) onProgress( event );
  22673. }, false );
  22674. */
  22675. image.addEventListener( 'error', function ( event ) {
  22676. if ( onError ) onError( event );
  22677. scope.manager.itemEnd( url );
  22678. scope.manager.itemError( url );
  22679. }, false );
  22680. if ( url.substr( 0, 5 ) !== 'data:' ) {
  22681. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  22682. }
  22683. scope.manager.itemStart( url );
  22684. image.src = url;
  22685. return image;
  22686. },
  22687. setCrossOrigin: function ( value ) {
  22688. this.crossOrigin = value;
  22689. return this;
  22690. },
  22691. setPath: function ( value ) {
  22692. this.path = value;
  22693. return this;
  22694. }
  22695. } );
  22696. /**
  22697. * @author mrdoob / http://mrdoob.com/
  22698. */
  22699. function CubeTextureLoader( manager ) {
  22700. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22701. }
  22702. Object.assign( CubeTextureLoader.prototype, {
  22703. crossOrigin: 'Anonymous',
  22704. load: function ( urls, onLoad, onProgress, onError ) {
  22705. var texture = new CubeTexture();
  22706. var loader = new ImageLoader( this.manager );
  22707. loader.setCrossOrigin( this.crossOrigin );
  22708. loader.setPath( this.path );
  22709. var loaded = 0;
  22710. function loadTexture( i ) {
  22711. loader.load( urls[ i ], function ( image ) {
  22712. texture.images[ i ] = image;
  22713. loaded ++;
  22714. if ( loaded === 6 ) {
  22715. texture.needsUpdate = true;
  22716. if ( onLoad ) onLoad( texture );
  22717. }
  22718. }, undefined, onError );
  22719. }
  22720. for ( var i = 0; i < urls.length; ++ i ) {
  22721. loadTexture( i );
  22722. }
  22723. return texture;
  22724. },
  22725. setCrossOrigin: function ( value ) {
  22726. this.crossOrigin = value;
  22727. return this;
  22728. },
  22729. setPath: function ( value ) {
  22730. this.path = value;
  22731. return this;
  22732. }
  22733. } );
  22734. /**
  22735. * @author mrdoob / http://mrdoob.com/
  22736. */
  22737. function TextureLoader( manager ) {
  22738. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22739. }
  22740. Object.assign( TextureLoader.prototype, {
  22741. crossOrigin: 'Anonymous',
  22742. load: function ( url, onLoad, onProgress, onError ) {
  22743. var loader = new ImageLoader( this.manager );
  22744. loader.setCrossOrigin( this.crossOrigin );
  22745. loader.setPath( this.path );
  22746. var texture = new Texture();
  22747. texture.image = loader.load( url, function () {
  22748. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22749. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22750. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22751. texture.needsUpdate = true;
  22752. if ( onLoad !== undefined ) {
  22753. onLoad( texture );
  22754. }
  22755. }, onProgress, onError );
  22756. return texture;
  22757. },
  22758. setCrossOrigin: function ( value ) {
  22759. this.crossOrigin = value;
  22760. return this;
  22761. },
  22762. setPath: function ( value ) {
  22763. this.path = value;
  22764. return this;
  22765. }
  22766. } );
  22767. /**
  22768. * @author mrdoob / http://mrdoob.com/
  22769. * @author alteredq / http://alteredqualia.com/
  22770. */
  22771. function Light( color, intensity ) {
  22772. Object3D.call( this );
  22773. this.type = 'Light';
  22774. this.color = new Color( color );
  22775. this.intensity = intensity !== undefined ? intensity : 1;
  22776. this.receiveShadow = undefined;
  22777. }
  22778. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22779. constructor: Light,
  22780. isLight: true,
  22781. copy: function ( source ) {
  22782. Object3D.prototype.copy.call( this, source );
  22783. this.color.copy( source.color );
  22784. this.intensity = source.intensity;
  22785. return this;
  22786. },
  22787. toJSON: function ( meta ) {
  22788. var data = Object3D.prototype.toJSON.call( this, meta );
  22789. data.object.color = this.color.getHex();
  22790. data.object.intensity = this.intensity;
  22791. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  22792. if ( this.distance !== undefined ) data.object.distance = this.distance;
  22793. if ( this.angle !== undefined ) data.object.angle = this.angle;
  22794. if ( this.decay !== undefined ) data.object.decay = this.decay;
  22795. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  22796. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  22797. return data;
  22798. }
  22799. } );
  22800. /**
  22801. * @author alteredq / http://alteredqualia.com/
  22802. */
  22803. function HemisphereLight( skyColor, groundColor, intensity ) {
  22804. Light.call( this, skyColor, intensity );
  22805. this.type = 'HemisphereLight';
  22806. this.castShadow = undefined;
  22807. this.position.copy( Object3D.DefaultUp );
  22808. this.updateMatrix();
  22809. this.groundColor = new Color( groundColor );
  22810. }
  22811. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22812. constructor: HemisphereLight,
  22813. isHemisphereLight: true,
  22814. copy: function ( source ) {
  22815. Light.prototype.copy.call( this, source );
  22816. this.groundColor.copy( source.groundColor );
  22817. return this;
  22818. }
  22819. } );
  22820. /**
  22821. * @author mrdoob / http://mrdoob.com/
  22822. */
  22823. function LightShadow( camera ) {
  22824. this.camera = camera;
  22825. this.bias = 0;
  22826. this.radius = 1;
  22827. this.mapSize = new Vector2( 512, 512 );
  22828. this.map = null;
  22829. this.matrix = new Matrix4();
  22830. }
  22831. Object.assign( LightShadow.prototype, {
  22832. copy: function ( source ) {
  22833. this.camera = source.camera.clone();
  22834. this.bias = source.bias;
  22835. this.radius = source.radius;
  22836. this.mapSize.copy( source.mapSize );
  22837. return this;
  22838. },
  22839. clone: function () {
  22840. return new this.constructor().copy( this );
  22841. },
  22842. toJSON: function () {
  22843. var object = {};
  22844. if ( this.bias !== 0 ) object.bias = this.bias;
  22845. if ( this.radius !== 1 ) object.radius = this.radius;
  22846. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  22847. object.camera = this.camera.toJSON( false ).object;
  22848. delete object.camera.matrix;
  22849. return object;
  22850. }
  22851. } );
  22852. /**
  22853. * @author mrdoob / http://mrdoob.com/
  22854. */
  22855. function SpotLightShadow() {
  22856. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  22857. }
  22858. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22859. constructor: SpotLightShadow,
  22860. isSpotLightShadow: true,
  22861. update: function ( light ) {
  22862. var camera = this.camera;
  22863. var fov = _Math.RAD2DEG * 2 * light.angle;
  22864. var aspect = this.mapSize.width / this.mapSize.height;
  22865. var far = light.distance || camera.far;
  22866. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  22867. camera.fov = fov;
  22868. camera.aspect = aspect;
  22869. camera.far = far;
  22870. camera.updateProjectionMatrix();
  22871. }
  22872. }
  22873. } );
  22874. /**
  22875. * @author alteredq / http://alteredqualia.com/
  22876. */
  22877. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  22878. Light.call( this, color, intensity );
  22879. this.type = 'SpotLight';
  22880. this.position.copy( Object3D.DefaultUp );
  22881. this.updateMatrix();
  22882. this.target = new Object3D();
  22883. Object.defineProperty( this, 'power', {
  22884. get: function () {
  22885. // intensity = power per solid angle.
  22886. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22887. return this.intensity * Math.PI;
  22888. },
  22889. set: function ( power ) {
  22890. // intensity = power per solid angle.
  22891. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22892. this.intensity = power / Math.PI;
  22893. }
  22894. } );
  22895. this.distance = ( distance !== undefined ) ? distance : 0;
  22896. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  22897. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  22898. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22899. this.shadow = new SpotLightShadow();
  22900. }
  22901. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22902. constructor: SpotLight,
  22903. isSpotLight: true,
  22904. copy: function ( source ) {
  22905. Light.prototype.copy.call( this, source );
  22906. this.distance = source.distance;
  22907. this.angle = source.angle;
  22908. this.penumbra = source.penumbra;
  22909. this.decay = source.decay;
  22910. this.target = source.target.clone();
  22911. this.shadow = source.shadow.clone();
  22912. return this;
  22913. }
  22914. } );
  22915. /**
  22916. * @author mrdoob / http://mrdoob.com/
  22917. */
  22918. function PointLight( color, intensity, distance, decay ) {
  22919. Light.call( this, color, intensity );
  22920. this.type = 'PointLight';
  22921. Object.defineProperty( this, 'power', {
  22922. get: function () {
  22923. // intensity = power per solid angle.
  22924. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22925. return this.intensity * 4 * Math.PI;
  22926. },
  22927. set: function ( power ) {
  22928. // intensity = power per solid angle.
  22929. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22930. this.intensity = power / ( 4 * Math.PI );
  22931. }
  22932. } );
  22933. this.distance = ( distance !== undefined ) ? distance : 0;
  22934. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22935. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  22936. }
  22937. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22938. constructor: PointLight,
  22939. isPointLight: true,
  22940. copy: function ( source ) {
  22941. Light.prototype.copy.call( this, source );
  22942. this.distance = source.distance;
  22943. this.decay = source.decay;
  22944. this.shadow = source.shadow.clone();
  22945. return this;
  22946. }
  22947. } );
  22948. /**
  22949. * @author mrdoob / http://mrdoob.com/
  22950. */
  22951. function DirectionalLightShadow( ) {
  22952. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  22953. }
  22954. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22955. constructor: DirectionalLightShadow
  22956. } );
  22957. /**
  22958. * @author mrdoob / http://mrdoob.com/
  22959. * @author alteredq / http://alteredqualia.com/
  22960. */
  22961. function DirectionalLight( color, intensity ) {
  22962. Light.call( this, color, intensity );
  22963. this.type = 'DirectionalLight';
  22964. this.position.copy( Object3D.DefaultUp );
  22965. this.updateMatrix();
  22966. this.target = new Object3D();
  22967. this.shadow = new DirectionalLightShadow();
  22968. }
  22969. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22970. constructor: DirectionalLight,
  22971. isDirectionalLight: true,
  22972. copy: function ( source ) {
  22973. Light.prototype.copy.call( this, source );
  22974. this.target = source.target.clone();
  22975. this.shadow = source.shadow.clone();
  22976. return this;
  22977. }
  22978. } );
  22979. /**
  22980. * @author mrdoob / http://mrdoob.com/
  22981. */
  22982. function AmbientLight( color, intensity ) {
  22983. Light.call( this, color, intensity );
  22984. this.type = 'AmbientLight';
  22985. this.castShadow = undefined;
  22986. }
  22987. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22988. constructor: AmbientLight,
  22989. isAmbientLight: true
  22990. } );
  22991. /**
  22992. * @author abelnation / http://github.com/abelnation
  22993. */
  22994. function RectAreaLight( color, intensity, width, height ) {
  22995. Light.call( this, color, intensity );
  22996. this.type = 'RectAreaLight';
  22997. this.position.set( 0, 1, 0 );
  22998. this.updateMatrix();
  22999. this.width = ( width !== undefined ) ? width : 10;
  23000. this.height = ( height !== undefined ) ? height : 10;
  23001. // TODO (abelnation): distance/decay
  23002. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  23003. // TODO (abelnation): shadows
  23004. }
  23005. // TODO (abelnation): RectAreaLight update when light shape is changed
  23006. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  23007. constructor: RectAreaLight,
  23008. isRectAreaLight: true,
  23009. copy: function ( source ) {
  23010. Light.prototype.copy.call( this, source );
  23011. this.width = source.width;
  23012. this.height = source.height;
  23013. return this;
  23014. },
  23015. toJSON: function ( meta ) {
  23016. var data = Light.prototype.toJSON.call( this, meta );
  23017. data.object.width = this.width;
  23018. data.object.height = this.height;
  23019. return data;
  23020. }
  23021. } );
  23022. /**
  23023. * @author tschw
  23024. * @author Ben Houston / http://clara.io/
  23025. * @author David Sarno / http://lighthaus.us/
  23026. */
  23027. var AnimationUtils = {
  23028. // same as Array.prototype.slice, but also works on typed arrays
  23029. arraySlice: function ( array, from, to ) {
  23030. if ( AnimationUtils.isTypedArray( array ) ) {
  23031. // in ios9 array.subarray(from, undefined) will return empty array
  23032. // but array.subarray(from) or array.subarray(from, len) is correct
  23033. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23034. }
  23035. return array.slice( from, to );
  23036. },
  23037. // converts an array to a specific type
  23038. convertArray: function ( array, type, forceClone ) {
  23039. if ( ! array || // let 'undefined' and 'null' pass
  23040. ! forceClone && array.constructor === type ) return array;
  23041. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23042. return new type( array ); // create typed array
  23043. }
  23044. return Array.prototype.slice.call( array ); // create Array
  23045. },
  23046. isTypedArray: function ( object ) {
  23047. return ArrayBuffer.isView( object ) &&
  23048. ! ( object instanceof DataView );
  23049. },
  23050. // returns an array by which times and values can be sorted
  23051. getKeyframeOrder: function ( times ) {
  23052. function compareTime( i, j ) {
  23053. return times[ i ] - times[ j ];
  23054. }
  23055. var n = times.length;
  23056. var result = new Array( n );
  23057. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  23058. result.sort( compareTime );
  23059. return result;
  23060. },
  23061. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23062. sortedArray: function ( values, stride, order ) {
  23063. var nValues = values.length;
  23064. var result = new values.constructor( nValues );
  23065. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23066. var srcOffset = order[ i ] * stride;
  23067. for ( var j = 0; j !== stride; ++ j ) {
  23068. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23069. }
  23070. }
  23071. return result;
  23072. },
  23073. // function for parsing AOS keyframe formats
  23074. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  23075. var i = 1, key = jsonKeys[ 0 ];
  23076. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23077. key = jsonKeys[ i ++ ];
  23078. }
  23079. if ( key === undefined ) return; // no data
  23080. var value = key[ valuePropertyName ];
  23081. if ( value === undefined ) return; // no data
  23082. if ( Array.isArray( value ) ) {
  23083. do {
  23084. value = key[ valuePropertyName ];
  23085. if ( value !== undefined ) {
  23086. times.push( key.time );
  23087. values.push.apply( values, value ); // push all elements
  23088. }
  23089. key = jsonKeys[ i ++ ];
  23090. } while ( key !== undefined );
  23091. } else if ( value.toArray !== undefined ) {
  23092. // ...assume THREE.Math-ish
  23093. do {
  23094. value = key[ valuePropertyName ];
  23095. if ( value !== undefined ) {
  23096. times.push( key.time );
  23097. value.toArray( values, values.length );
  23098. }
  23099. key = jsonKeys[ i ++ ];
  23100. } while ( key !== undefined );
  23101. } else {
  23102. // otherwise push as-is
  23103. do {
  23104. value = key[ valuePropertyName ];
  23105. if ( value !== undefined ) {
  23106. times.push( key.time );
  23107. values.push( value );
  23108. }
  23109. key = jsonKeys[ i ++ ];
  23110. } while ( key !== undefined );
  23111. }
  23112. }
  23113. };
  23114. /**
  23115. * Abstract base class of interpolants over parametric samples.
  23116. *
  23117. * The parameter domain is one dimensional, typically the time or a path
  23118. * along a curve defined by the data.
  23119. *
  23120. * The sample values can have any dimensionality and derived classes may
  23121. * apply special interpretations to the data.
  23122. *
  23123. * This class provides the interval seek in a Template Method, deferring
  23124. * the actual interpolation to derived classes.
  23125. *
  23126. * Time complexity is O(1) for linear access crossing at most two points
  23127. * and O(log N) for random access, where N is the number of positions.
  23128. *
  23129. * References:
  23130. *
  23131. * http://www.oodesign.com/template-method-pattern.html
  23132. *
  23133. * @author tschw
  23134. */
  23135. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23136. this.parameterPositions = parameterPositions;
  23137. this._cachedIndex = 0;
  23138. this.resultBuffer = resultBuffer !== undefined ?
  23139. resultBuffer : new sampleValues.constructor( sampleSize );
  23140. this.sampleValues = sampleValues;
  23141. this.valueSize = sampleSize;
  23142. }
  23143. Object.assign( Interpolant.prototype, {
  23144. evaluate: function( t ) {
  23145. var pp = this.parameterPositions,
  23146. i1 = this._cachedIndex,
  23147. t1 = pp[ i1 ],
  23148. t0 = pp[ i1 - 1 ];
  23149. validate_interval: {
  23150. seek: {
  23151. var right;
  23152. linear_scan: {
  23153. //- See http://jsperf.com/comparison-to-undefined/3
  23154. //- slower code:
  23155. //-
  23156. //- if ( t >= t1 || t1 === undefined ) {
  23157. forward_scan: if ( ! ( t < t1 ) ) {
  23158. for ( var giveUpAt = i1 + 2; ;) {
  23159. if ( t1 === undefined ) {
  23160. if ( t < t0 ) break forward_scan;
  23161. // after end
  23162. i1 = pp.length;
  23163. this._cachedIndex = i1;
  23164. return this.afterEnd_( i1 - 1, t, t0 );
  23165. }
  23166. if ( i1 === giveUpAt ) break; // this loop
  23167. t0 = t1;
  23168. t1 = pp[ ++ i1 ];
  23169. if ( t < t1 ) {
  23170. // we have arrived at the sought interval
  23171. break seek;
  23172. }
  23173. }
  23174. // prepare binary search on the right side of the index
  23175. right = pp.length;
  23176. break linear_scan;
  23177. }
  23178. //- slower code:
  23179. //- if ( t < t0 || t0 === undefined ) {
  23180. if ( ! ( t >= t0 ) ) {
  23181. // looping?
  23182. var t1global = pp[ 1 ];
  23183. if ( t < t1global ) {
  23184. i1 = 2; // + 1, using the scan for the details
  23185. t0 = t1global;
  23186. }
  23187. // linear reverse scan
  23188. for ( var giveUpAt = i1 - 2; ;) {
  23189. if ( t0 === undefined ) {
  23190. // before start
  23191. this._cachedIndex = 0;
  23192. return this.beforeStart_( 0, t, t1 );
  23193. }
  23194. if ( i1 === giveUpAt ) break; // this loop
  23195. t1 = t0;
  23196. t0 = pp[ -- i1 - 1 ];
  23197. if ( t >= t0 ) {
  23198. // we have arrived at the sought interval
  23199. break seek;
  23200. }
  23201. }
  23202. // prepare binary search on the left side of the index
  23203. right = i1;
  23204. i1 = 0;
  23205. break linear_scan;
  23206. }
  23207. // the interval is valid
  23208. break validate_interval;
  23209. } // linear scan
  23210. // binary search
  23211. while ( i1 < right ) {
  23212. var mid = ( i1 + right ) >>> 1;
  23213. if ( t < pp[ mid ] ) {
  23214. right = mid;
  23215. } else {
  23216. i1 = mid + 1;
  23217. }
  23218. }
  23219. t1 = pp[ i1 ];
  23220. t0 = pp[ i1 - 1 ];
  23221. // check boundary cases, again
  23222. if ( t0 === undefined ) {
  23223. this._cachedIndex = 0;
  23224. return this.beforeStart_( 0, t, t1 );
  23225. }
  23226. if ( t1 === undefined ) {
  23227. i1 = pp.length;
  23228. this._cachedIndex = i1;
  23229. return this.afterEnd_( i1 - 1, t0, t );
  23230. }
  23231. } // seek
  23232. this._cachedIndex = i1;
  23233. this.intervalChanged_( i1, t0, t1 );
  23234. } // validate_interval
  23235. return this.interpolate_( i1, t0, t, t1 );
  23236. },
  23237. settings: null, // optional, subclass-specific settings structure
  23238. // Note: The indirection allows central control of many interpolants.
  23239. // --- Protected interface
  23240. DefaultSettings_: {},
  23241. getSettings_: function() {
  23242. return this.settings || this.DefaultSettings_;
  23243. },
  23244. copySampleValue_: function( index ) {
  23245. // copies a sample value to the result buffer
  23246. var result = this.resultBuffer,
  23247. values = this.sampleValues,
  23248. stride = this.valueSize,
  23249. offset = index * stride;
  23250. for ( var i = 0; i !== stride; ++ i ) {
  23251. result[ i ] = values[ offset + i ];
  23252. }
  23253. return result;
  23254. },
  23255. // Template methods for derived classes:
  23256. interpolate_: function( i1, t0, t, t1 ) {
  23257. throw new Error( "call to abstract method" );
  23258. // implementations shall return this.resultBuffer
  23259. },
  23260. intervalChanged_: function( i1, t0, t1 ) {
  23261. // empty
  23262. }
  23263. } );
  23264. //!\ DECLARE ALIAS AFTER assign prototype !
  23265. Object.assign( Interpolant.prototype, {
  23266. //( 0, t, t0 ), returns this.resultBuffer
  23267. beforeStart_: Interpolant.prototype.copySampleValue_,
  23268. //( N-1, tN-1, t ), returns this.resultBuffer
  23269. afterEnd_: Interpolant.prototype.copySampleValue_,
  23270. } );
  23271. /**
  23272. * Fast and simple cubic spline interpolant.
  23273. *
  23274. * It was derived from a Hermitian construction setting the first derivative
  23275. * at each sample position to the linear slope between neighboring positions
  23276. * over their parameter interval.
  23277. *
  23278. * @author tschw
  23279. */
  23280. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23281. Interpolant.call(
  23282. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23283. this._weightPrev = -0;
  23284. this._offsetPrev = -0;
  23285. this._weightNext = -0;
  23286. this._offsetNext = -0;
  23287. }
  23288. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23289. constructor: CubicInterpolant,
  23290. DefaultSettings_: {
  23291. endingStart: ZeroCurvatureEnding,
  23292. endingEnd: ZeroCurvatureEnding
  23293. },
  23294. intervalChanged_: function( i1, t0, t1 ) {
  23295. var pp = this.parameterPositions,
  23296. iPrev = i1 - 2,
  23297. iNext = i1 + 1,
  23298. tPrev = pp[ iPrev ],
  23299. tNext = pp[ iNext ];
  23300. if ( tPrev === undefined ) {
  23301. switch ( this.getSettings_().endingStart ) {
  23302. case ZeroSlopeEnding:
  23303. // f'(t0) = 0
  23304. iPrev = i1;
  23305. tPrev = 2 * t0 - t1;
  23306. break;
  23307. case WrapAroundEnding:
  23308. // use the other end of the curve
  23309. iPrev = pp.length - 2;
  23310. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23311. break;
  23312. default: // ZeroCurvatureEnding
  23313. // f''(t0) = 0 a.k.a. Natural Spline
  23314. iPrev = i1;
  23315. tPrev = t1;
  23316. }
  23317. }
  23318. if ( tNext === undefined ) {
  23319. switch ( this.getSettings_().endingEnd ) {
  23320. case ZeroSlopeEnding:
  23321. // f'(tN) = 0
  23322. iNext = i1;
  23323. tNext = 2 * t1 - t0;
  23324. break;
  23325. case WrapAroundEnding:
  23326. // use the other end of the curve
  23327. iNext = 1;
  23328. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23329. break;
  23330. default: // ZeroCurvatureEnding
  23331. // f''(tN) = 0, a.k.a. Natural Spline
  23332. iNext = i1 - 1;
  23333. tNext = t0;
  23334. }
  23335. }
  23336. var halfDt = ( t1 - t0 ) * 0.5,
  23337. stride = this.valueSize;
  23338. this._weightPrev = halfDt / ( t0 - tPrev );
  23339. this._weightNext = halfDt / ( tNext - t1 );
  23340. this._offsetPrev = iPrev * stride;
  23341. this._offsetNext = iNext * stride;
  23342. },
  23343. interpolate_: function( i1, t0, t, t1 ) {
  23344. var result = this.resultBuffer,
  23345. values = this.sampleValues,
  23346. stride = this.valueSize,
  23347. o1 = i1 * stride, o0 = o1 - stride,
  23348. oP = this._offsetPrev, oN = this._offsetNext,
  23349. wP = this._weightPrev, wN = this._weightNext,
  23350. p = ( t - t0 ) / ( t1 - t0 ),
  23351. pp = p * p,
  23352. ppp = pp * p;
  23353. // evaluate polynomials
  23354. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  23355. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  23356. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23357. var sN = wN * ppp - wN * pp;
  23358. // combine data linearly
  23359. for ( var i = 0; i !== stride; ++ i ) {
  23360. result[ i ] =
  23361. sP * values[ oP + i ] +
  23362. s0 * values[ o0 + i ] +
  23363. s1 * values[ o1 + i ] +
  23364. sN * values[ oN + i ];
  23365. }
  23366. return result;
  23367. }
  23368. } );
  23369. /**
  23370. * @author tschw
  23371. */
  23372. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23373. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23374. }
  23375. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23376. constructor: LinearInterpolant,
  23377. interpolate_: function( i1, t0, t, t1 ) {
  23378. var result = this.resultBuffer,
  23379. values = this.sampleValues,
  23380. stride = this.valueSize,
  23381. offset1 = i1 * stride,
  23382. offset0 = offset1 - stride,
  23383. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23384. weight0 = 1 - weight1;
  23385. for ( var i = 0; i !== stride; ++ i ) {
  23386. result[ i ] =
  23387. values[ offset0 + i ] * weight0 +
  23388. values[ offset1 + i ] * weight1;
  23389. }
  23390. return result;
  23391. }
  23392. } );
  23393. /**
  23394. *
  23395. * Interpolant that evaluates to the sample value at the position preceeding
  23396. * the parameter.
  23397. *
  23398. * @author tschw
  23399. */
  23400. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23401. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23402. }
  23403. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23404. constructor: DiscreteInterpolant,
  23405. interpolate_: function( i1, t0, t, t1 ) {
  23406. return this.copySampleValue_( i1 - 1 );
  23407. }
  23408. } );
  23409. var KeyframeTrackPrototype;
  23410. KeyframeTrackPrototype = {
  23411. TimeBufferType: Float32Array,
  23412. ValueBufferType: Float32Array,
  23413. DefaultInterpolation: InterpolateLinear,
  23414. InterpolantFactoryMethodDiscrete: function ( result ) {
  23415. return new DiscreteInterpolant(
  23416. this.times, this.values, this.getValueSize(), result );
  23417. },
  23418. InterpolantFactoryMethodLinear: function ( result ) {
  23419. return new LinearInterpolant(
  23420. this.times, this.values, this.getValueSize(), result );
  23421. },
  23422. InterpolantFactoryMethodSmooth: function ( result ) {
  23423. return new CubicInterpolant(
  23424. this.times, this.values, this.getValueSize(), result );
  23425. },
  23426. setInterpolation: function ( interpolation ) {
  23427. var factoryMethod;
  23428. switch ( interpolation ) {
  23429. case InterpolateDiscrete:
  23430. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23431. break;
  23432. case InterpolateLinear:
  23433. factoryMethod = this.InterpolantFactoryMethodLinear;
  23434. break;
  23435. case InterpolateSmooth:
  23436. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23437. break;
  23438. }
  23439. if ( factoryMethod === undefined ) {
  23440. var message = "unsupported interpolation for " +
  23441. this.ValueTypeName + " keyframe track named " + this.name;
  23442. if ( this.createInterpolant === undefined ) {
  23443. // fall back to default, unless the default itself is messed up
  23444. if ( interpolation !== this.DefaultInterpolation ) {
  23445. this.setInterpolation( this.DefaultInterpolation );
  23446. } else {
  23447. throw new Error( message ); // fatal, in this case
  23448. }
  23449. }
  23450. console.warn( 'THREE.KeyframeTrackPrototype:', message );
  23451. return;
  23452. }
  23453. this.createInterpolant = factoryMethod;
  23454. },
  23455. getInterpolation: function () {
  23456. switch ( this.createInterpolant ) {
  23457. case this.InterpolantFactoryMethodDiscrete:
  23458. return InterpolateDiscrete;
  23459. case this.InterpolantFactoryMethodLinear:
  23460. return InterpolateLinear;
  23461. case this.InterpolantFactoryMethodSmooth:
  23462. return InterpolateSmooth;
  23463. }
  23464. },
  23465. getValueSize: function () {
  23466. return this.values.length / this.times.length;
  23467. },
  23468. // move all keyframes either forwards or backwards in time
  23469. shift: function ( timeOffset ) {
  23470. if ( timeOffset !== 0.0 ) {
  23471. var times = this.times;
  23472. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  23473. times[ i ] += timeOffset;
  23474. }
  23475. }
  23476. return this;
  23477. },
  23478. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23479. scale: function ( timeScale ) {
  23480. if ( timeScale !== 1.0 ) {
  23481. var times = this.times;
  23482. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  23483. times[ i ] *= timeScale;
  23484. }
  23485. }
  23486. return this;
  23487. },
  23488. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23489. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23490. trim: function ( startTime, endTime ) {
  23491. var times = this.times,
  23492. nKeys = times.length,
  23493. from = 0,
  23494. to = nKeys - 1;
  23495. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  23496. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  23497. ++ to; // inclusive -> exclusive bound
  23498. if ( from !== 0 || to !== nKeys ) {
  23499. // empty tracks are forbidden, so keep at least one keyframe
  23500. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  23501. var stride = this.getValueSize();
  23502. this.times = AnimationUtils.arraySlice( times, from, to );
  23503. this.values = AnimationUtils.
  23504. arraySlice( this.values, from * stride, to * stride );
  23505. }
  23506. return this;
  23507. },
  23508. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23509. validate: function () {
  23510. var valid = true;
  23511. var valueSize = this.getValueSize();
  23512. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23513. console.error( 'THREE.KeyframeTrackPrototype: Invalid value size in track.', this );
  23514. valid = false;
  23515. }
  23516. var times = this.times,
  23517. values = this.values,
  23518. nKeys = times.length;
  23519. if ( nKeys === 0 ) {
  23520. console.error( 'THREE.KeyframeTrackPrototype: Track is empty.', this );
  23521. valid = false;
  23522. }
  23523. var prevTime = null;
  23524. for ( var i = 0; i !== nKeys; i ++ ) {
  23525. var currTime = times[ i ];
  23526. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23527. console.error( 'THREE.KeyframeTrackPrototype: Time is not a valid number.', this, i, currTime );
  23528. valid = false;
  23529. break;
  23530. }
  23531. if ( prevTime !== null && prevTime > currTime ) {
  23532. console.error( 'THREE.KeyframeTrackPrototype: Out of order keys.', this, i, currTime, prevTime );
  23533. valid = false;
  23534. break;
  23535. }
  23536. prevTime = currTime;
  23537. }
  23538. if ( values !== undefined ) {
  23539. if ( AnimationUtils.isTypedArray( values ) ) {
  23540. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  23541. var value = values[ i ];
  23542. if ( isNaN( value ) ) {
  23543. console.error( 'THREE.KeyframeTrackPrototype: Value is not a valid number.', this, i, value );
  23544. valid = false;
  23545. break;
  23546. }
  23547. }
  23548. }
  23549. }
  23550. return valid;
  23551. },
  23552. // removes equivalent sequential keys as common in morph target sequences
  23553. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23554. optimize: function () {
  23555. var times = this.times,
  23556. values = this.values,
  23557. stride = this.getValueSize(),
  23558. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23559. writeIndex = 1,
  23560. lastIndex = times.length - 1;
  23561. for ( var i = 1; i < lastIndex; ++ i ) {
  23562. var keep = false;
  23563. var time = times[ i ];
  23564. var timeNext = times[ i + 1 ];
  23565. // remove adjacent keyframes scheduled at the same time
  23566. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  23567. if ( ! smoothInterpolation ) {
  23568. // remove unnecessary keyframes same as their neighbors
  23569. var offset = i * stride,
  23570. offsetP = offset - stride,
  23571. offsetN = offset + stride;
  23572. for ( var j = 0; j !== stride; ++ j ) {
  23573. var value = values[ offset + j ];
  23574. if ( value !== values[ offsetP + j ] ||
  23575. value !== values[ offsetN + j ] ) {
  23576. keep = true;
  23577. break;
  23578. }
  23579. }
  23580. } else keep = true;
  23581. }
  23582. // in-place compaction
  23583. if ( keep ) {
  23584. if ( i !== writeIndex ) {
  23585. times[ writeIndex ] = times[ i ];
  23586. var readOffset = i * stride,
  23587. writeOffset = writeIndex * stride;
  23588. for ( var j = 0; j !== stride; ++ j )
  23589. values[ writeOffset + j ] = values[ readOffset + j ];
  23590. }
  23591. ++ writeIndex;
  23592. }
  23593. }
  23594. // flush last keyframe (compaction looks ahead)
  23595. if ( lastIndex > 0 ) {
  23596. times[ writeIndex ] = times[ lastIndex ];
  23597. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  23598. values[ writeOffset + j ] = values[ readOffset + j ];
  23599. ++ writeIndex;
  23600. }
  23601. if ( writeIndex !== times.length ) {
  23602. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  23603. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  23604. }
  23605. return this;
  23606. }
  23607. };
  23608. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  23609. if ( name === undefined ) throw new Error( "track name is undefined" );
  23610. if ( times === undefined || times.length === 0 ) {
  23611. throw new Error( "no keyframes in track named " + name );
  23612. }
  23613. this.name = name;
  23614. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  23615. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  23616. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23617. this.validate();
  23618. this.optimize();
  23619. }
  23620. /**
  23621. *
  23622. * A Track of vectored keyframe values.
  23623. *
  23624. *
  23625. * @author Ben Houston / http://clara.io/
  23626. * @author David Sarno / http://lighthaus.us/
  23627. * @author tschw
  23628. */
  23629. function VectorKeyframeTrack( name, times, values, interpolation ) {
  23630. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23631. }
  23632. VectorKeyframeTrack.prototype =
  23633. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23634. constructor: VectorKeyframeTrack,
  23635. ValueTypeName: 'vector'
  23636. // ValueBufferType is inherited
  23637. // DefaultInterpolation is inherited
  23638. } );
  23639. /**
  23640. * Spherical linear unit quaternion interpolant.
  23641. *
  23642. * @author tschw
  23643. */
  23644. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23645. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23646. }
  23647. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  23648. constructor: QuaternionLinearInterpolant,
  23649. interpolate_: function( i1, t0, t, t1 ) {
  23650. var result = this.resultBuffer,
  23651. values = this.sampleValues,
  23652. stride = this.valueSize,
  23653. offset = i1 * stride,
  23654. alpha = ( t - t0 ) / ( t1 - t0 );
  23655. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  23656. Quaternion.slerpFlat( result, 0,
  23657. values, offset - stride, values, offset, alpha );
  23658. }
  23659. return result;
  23660. }
  23661. } );
  23662. /**
  23663. *
  23664. * A Track of quaternion keyframe values.
  23665. *
  23666. * @author Ben Houston / http://clara.io/
  23667. * @author David Sarno / http://lighthaus.us/
  23668. * @author tschw
  23669. */
  23670. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  23671. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23672. }
  23673. QuaternionKeyframeTrack.prototype =
  23674. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23675. constructor: QuaternionKeyframeTrack,
  23676. ValueTypeName: 'quaternion',
  23677. // ValueBufferType is inherited
  23678. DefaultInterpolation: InterpolateLinear,
  23679. InterpolantFactoryMethodLinear: function( result ) {
  23680. return new QuaternionLinearInterpolant(
  23681. this.times, this.values, this.getValueSize(), result );
  23682. },
  23683. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  23684. } );
  23685. /**
  23686. *
  23687. * A Track of numeric keyframe values.
  23688. *
  23689. * @author Ben Houston / http://clara.io/
  23690. * @author David Sarno / http://lighthaus.us/
  23691. * @author tschw
  23692. */
  23693. function NumberKeyframeTrack( name, times, values, interpolation ) {
  23694. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23695. }
  23696. NumberKeyframeTrack.prototype =
  23697. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23698. constructor: NumberKeyframeTrack,
  23699. ValueTypeName: 'number'
  23700. // ValueBufferType is inherited
  23701. // DefaultInterpolation is inherited
  23702. } );
  23703. /**
  23704. *
  23705. * A Track that interpolates Strings
  23706. *
  23707. *
  23708. * @author Ben Houston / http://clara.io/
  23709. * @author David Sarno / http://lighthaus.us/
  23710. * @author tschw
  23711. */
  23712. function StringKeyframeTrack( name, times, values, interpolation ) {
  23713. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23714. }
  23715. StringKeyframeTrack.prototype =
  23716. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23717. constructor: StringKeyframeTrack,
  23718. ValueTypeName: 'string',
  23719. ValueBufferType: Array,
  23720. DefaultInterpolation: InterpolateDiscrete,
  23721. InterpolantFactoryMethodLinear: undefined,
  23722. InterpolantFactoryMethodSmooth: undefined
  23723. } );
  23724. /**
  23725. *
  23726. * A Track of Boolean keyframe values.
  23727. *
  23728. *
  23729. * @author Ben Houston / http://clara.io/
  23730. * @author David Sarno / http://lighthaus.us/
  23731. * @author tschw
  23732. */
  23733. function BooleanKeyframeTrack( name, times, values ) {
  23734. KeyframeTrackConstructor.call( this, name, times, values );
  23735. }
  23736. BooleanKeyframeTrack.prototype =
  23737. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23738. constructor: BooleanKeyframeTrack,
  23739. ValueTypeName: 'bool',
  23740. ValueBufferType: Array,
  23741. DefaultInterpolation: InterpolateDiscrete,
  23742. InterpolantFactoryMethodLinear: undefined,
  23743. InterpolantFactoryMethodSmooth: undefined
  23744. // Note: Actually this track could have a optimized / compressed
  23745. // representation of a single value and a custom interpolant that
  23746. // computes "firstValue ^ isOdd( index )".
  23747. } );
  23748. /**
  23749. *
  23750. * A Track of keyframe values that represent color.
  23751. *
  23752. *
  23753. * @author Ben Houston / http://clara.io/
  23754. * @author David Sarno / http://lighthaus.us/
  23755. * @author tschw
  23756. */
  23757. function ColorKeyframeTrack( name, times, values, interpolation ) {
  23758. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23759. }
  23760. ColorKeyframeTrack.prototype =
  23761. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23762. constructor: ColorKeyframeTrack,
  23763. ValueTypeName: 'color'
  23764. // ValueBufferType is inherited
  23765. // DefaultInterpolation is inherited
  23766. // Note: Very basic implementation and nothing special yet.
  23767. // However, this is the place for color space parameterization.
  23768. } );
  23769. /**
  23770. *
  23771. * A timed sequence of keyframes for a specific property.
  23772. *
  23773. *
  23774. * @author Ben Houston / http://clara.io/
  23775. * @author David Sarno / http://lighthaus.us/
  23776. * @author tschw
  23777. */
  23778. function KeyframeTrack( name, times, values, interpolation ) {
  23779. KeyframeTrackConstructor.apply( this, arguments );
  23780. }
  23781. KeyframeTrack.prototype = KeyframeTrackPrototype;
  23782. KeyframeTrackPrototype.constructor = KeyframeTrack;
  23783. // Static methods:
  23784. Object.assign( KeyframeTrack, {
  23785. // Serialization (in static context, because of constructor invocation
  23786. // and automatic invocation of .toJSON):
  23787. parse: function( json ) {
  23788. if( json.type === undefined ) {
  23789. throw new Error( "track type undefined, can not parse" );
  23790. }
  23791. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  23792. if ( json.times === undefined ) {
  23793. var times = [], values = [];
  23794. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23795. json.times = times;
  23796. json.values = values;
  23797. }
  23798. // derived classes can define a static parse method
  23799. if ( trackType.parse !== undefined ) {
  23800. return trackType.parse( json );
  23801. } else {
  23802. // by default, we assume a constructor compatible with the base
  23803. return new trackType(
  23804. json.name, json.times, json.values, json.interpolation );
  23805. }
  23806. },
  23807. toJSON: function( track ) {
  23808. var trackType = track.constructor;
  23809. var json;
  23810. // derived classes can define a static toJSON method
  23811. if ( trackType.toJSON !== undefined ) {
  23812. json = trackType.toJSON( track );
  23813. } else {
  23814. // by default, we assume the data can be serialized as-is
  23815. json = {
  23816. 'name': track.name,
  23817. 'times': AnimationUtils.convertArray( track.times, Array ),
  23818. 'values': AnimationUtils.convertArray( track.values, Array )
  23819. };
  23820. var interpolation = track.getInterpolation();
  23821. if ( interpolation !== track.DefaultInterpolation ) {
  23822. json.interpolation = interpolation;
  23823. }
  23824. }
  23825. json.type = track.ValueTypeName; // mandatory
  23826. return json;
  23827. },
  23828. _getTrackTypeForValueTypeName: function( typeName ) {
  23829. switch( typeName.toLowerCase() ) {
  23830. case "scalar":
  23831. case "double":
  23832. case "float":
  23833. case "number":
  23834. case "integer":
  23835. return NumberKeyframeTrack;
  23836. case "vector":
  23837. case "vector2":
  23838. case "vector3":
  23839. case "vector4":
  23840. return VectorKeyframeTrack;
  23841. case "color":
  23842. return ColorKeyframeTrack;
  23843. case "quaternion":
  23844. return QuaternionKeyframeTrack;
  23845. case "bool":
  23846. case "boolean":
  23847. return BooleanKeyframeTrack;
  23848. case "string":
  23849. return StringKeyframeTrack;
  23850. }
  23851. throw new Error( "Unsupported typeName: " + typeName );
  23852. }
  23853. } );
  23854. /**
  23855. *
  23856. * Reusable set of Tracks that represent an animation.
  23857. *
  23858. * @author Ben Houston / http://clara.io/
  23859. * @author David Sarno / http://lighthaus.us/
  23860. */
  23861. function AnimationClip( name, duration, tracks ) {
  23862. this.name = name;
  23863. this.tracks = tracks;
  23864. this.duration = ( duration !== undefined ) ? duration : - 1;
  23865. this.uuid = _Math.generateUUID();
  23866. // this means it should figure out its duration by scanning the tracks
  23867. if ( this.duration < 0 ) {
  23868. this.resetDuration();
  23869. }
  23870. this.optimize();
  23871. }
  23872. Object.assign( AnimationClip, {
  23873. parse: function ( json ) {
  23874. var tracks = [],
  23875. jsonTracks = json.tracks,
  23876. frameTime = 1.0 / ( json.fps || 1.0 );
  23877. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23878. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  23879. }
  23880. return new AnimationClip( json.name, json.duration, tracks );
  23881. },
  23882. toJSON: function ( clip ) {
  23883. var tracks = [],
  23884. clipTracks = clip.tracks;
  23885. var json = {
  23886. 'name': clip.name,
  23887. 'duration': clip.duration,
  23888. 'tracks': tracks
  23889. };
  23890. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23891. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23892. }
  23893. return json;
  23894. },
  23895. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  23896. var numMorphTargets = morphTargetSequence.length;
  23897. var tracks = [];
  23898. for ( var i = 0; i < numMorphTargets; i ++ ) {
  23899. var times = [];
  23900. var values = [];
  23901. times.push(
  23902. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23903. i,
  23904. ( i + 1 ) % numMorphTargets );
  23905. values.push( 0, 1, 0 );
  23906. var order = AnimationUtils.getKeyframeOrder( times );
  23907. times = AnimationUtils.sortedArray( times, 1, order );
  23908. values = AnimationUtils.sortedArray( values, 1, order );
  23909. // if there is a key at the first frame, duplicate it as the
  23910. // last frame as well for perfect loop.
  23911. if ( ! noLoop && times[ 0 ] === 0 ) {
  23912. times.push( numMorphTargets );
  23913. values.push( values[ 0 ] );
  23914. }
  23915. tracks.push(
  23916. new NumberKeyframeTrack(
  23917. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23918. times, values
  23919. ).scale( 1.0 / fps ) );
  23920. }
  23921. return new AnimationClip( name, - 1, tracks );
  23922. },
  23923. findByName: function ( objectOrClipArray, name ) {
  23924. var clipArray = objectOrClipArray;
  23925. if ( ! Array.isArray( objectOrClipArray ) ) {
  23926. var o = objectOrClipArray;
  23927. clipArray = o.geometry && o.geometry.animations || o.animations;
  23928. }
  23929. for ( var i = 0; i < clipArray.length; i ++ ) {
  23930. if ( clipArray[ i ].name === name ) {
  23931. return clipArray[ i ];
  23932. }
  23933. }
  23934. return null;
  23935. },
  23936. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  23937. var animationToMorphTargets = {};
  23938. // tested with https://regex101.com/ on trick sequences
  23939. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23940. var pattern = /^([\w-]*?)([\d]+)$/;
  23941. // sort morph target names into animation groups based
  23942. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23943. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  23944. var morphTarget = morphTargets[ i ];
  23945. var parts = morphTarget.name.match( pattern );
  23946. if ( parts && parts.length > 1 ) {
  23947. var name = parts[ 1 ];
  23948. var animationMorphTargets = animationToMorphTargets[ name ];
  23949. if ( ! animationMorphTargets ) {
  23950. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23951. }
  23952. animationMorphTargets.push( morphTarget );
  23953. }
  23954. }
  23955. var clips = [];
  23956. for ( var name in animationToMorphTargets ) {
  23957. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23958. }
  23959. return clips;
  23960. },
  23961. // parse the animation.hierarchy format
  23962. parseAnimation: function ( animation, bones ) {
  23963. if ( ! animation ) {
  23964. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23965. return null;
  23966. }
  23967. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23968. // only return track if there are actually keys.
  23969. if ( animationKeys.length !== 0 ) {
  23970. var times = [];
  23971. var values = [];
  23972. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  23973. // empty keys are filtered out, so check again
  23974. if ( times.length !== 0 ) {
  23975. destTracks.push( new trackType( trackName, times, values ) );
  23976. }
  23977. }
  23978. };
  23979. var tracks = [];
  23980. var clipName = animation.name || 'default';
  23981. // automatic length determination in AnimationClip.
  23982. var duration = animation.length || - 1;
  23983. var fps = animation.fps || 30;
  23984. var hierarchyTracks = animation.hierarchy || [];
  23985. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  23986. var animationKeys = hierarchyTracks[ h ].keys;
  23987. // skip empty tracks
  23988. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23989. // process morph targets
  23990. if ( animationKeys[ 0 ].morphTargets ) {
  23991. // figure out all morph targets used in this track
  23992. var morphTargetNames = {};
  23993. for ( var k = 0; k < animationKeys.length; k ++ ) {
  23994. if ( animationKeys[ k ].morphTargets ) {
  23995. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23996. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23997. }
  23998. }
  23999. }
  24000. // create a track for each morph target with all zero
  24001. // morphTargetInfluences except for the keys in which
  24002. // the morphTarget is named.
  24003. for ( var morphTargetName in morphTargetNames ) {
  24004. var times = [];
  24005. var values = [];
  24006. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24007. var animationKey = animationKeys[ k ];
  24008. times.push( animationKey.time );
  24009. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24010. }
  24011. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24012. }
  24013. duration = morphTargetNames.length * ( fps || 1.0 );
  24014. } else {
  24015. // ...assume skeletal animation
  24016. var boneName = '.bones[' + bones[ h ].name + ']';
  24017. addNonemptyTrack(
  24018. VectorKeyframeTrack, boneName + '.position',
  24019. animationKeys, 'pos', tracks );
  24020. addNonemptyTrack(
  24021. QuaternionKeyframeTrack, boneName + '.quaternion',
  24022. animationKeys, 'rot', tracks );
  24023. addNonemptyTrack(
  24024. VectorKeyframeTrack, boneName + '.scale',
  24025. animationKeys, 'scl', tracks );
  24026. }
  24027. }
  24028. if ( tracks.length === 0 ) {
  24029. return null;
  24030. }
  24031. var clip = new AnimationClip( clipName, duration, tracks );
  24032. return clip;
  24033. }
  24034. } );
  24035. Object.assign( AnimationClip.prototype, {
  24036. resetDuration: function () {
  24037. var tracks = this.tracks, duration = 0;
  24038. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  24039. var track = this.tracks[ i ];
  24040. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24041. }
  24042. this.duration = duration;
  24043. },
  24044. trim: function () {
  24045. for ( var i = 0; i < this.tracks.length; i ++ ) {
  24046. this.tracks[ i ].trim( 0, this.duration );
  24047. }
  24048. return this;
  24049. },
  24050. optimize: function () {
  24051. for ( var i = 0; i < this.tracks.length; i ++ ) {
  24052. this.tracks[ i ].optimize();
  24053. }
  24054. return this;
  24055. }
  24056. } );
  24057. /**
  24058. * @author mrdoob / http://mrdoob.com/
  24059. */
  24060. function MaterialLoader( manager ) {
  24061. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24062. this.textures = {};
  24063. }
  24064. Object.assign( MaterialLoader.prototype, {
  24065. load: function ( url, onLoad, onProgress, onError ) {
  24066. var scope = this;
  24067. var loader = new FileLoader( scope.manager );
  24068. loader.load( url, function ( text ) {
  24069. onLoad( scope.parse( JSON.parse( text ) ) );
  24070. }, onProgress, onError );
  24071. },
  24072. setTextures: function ( value ) {
  24073. this.textures = value;
  24074. },
  24075. parse: function ( json ) {
  24076. var textures = this.textures;
  24077. function getTexture( name ) {
  24078. if ( textures[ name ] === undefined ) {
  24079. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24080. }
  24081. return textures[ name ];
  24082. }
  24083. var material = new Materials[ json.type ]();
  24084. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24085. if ( json.name !== undefined ) material.name = json.name;
  24086. if ( json.color !== undefined ) material.color.setHex( json.color );
  24087. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24088. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24089. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24090. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  24091. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24092. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  24093. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  24094. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  24095. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24096. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24097. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  24098. if ( json.fog !== undefined ) material.fog = json.fog;
  24099. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24100. if ( json.blending !== undefined ) material.blending = json.blending;
  24101. if ( json.side !== undefined ) material.side = json.side;
  24102. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24103. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24104. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24105. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24106. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24107. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24108. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24109. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24110. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24111. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24112. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  24113. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  24114. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24115. if ( json.visible !== undefined ) material.visible = json.visible;
  24116. if ( json.userData !== undefined ) material.userData = json.userData;
  24117. // Deprecated
  24118. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24119. // for PointsMaterial
  24120. if ( json.size !== undefined ) material.size = json.size;
  24121. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24122. // maps
  24123. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24124. if ( json.alphaMap !== undefined ) {
  24125. material.alphaMap = getTexture( json.alphaMap );
  24126. material.transparent = true;
  24127. }
  24128. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24129. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24130. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24131. if ( json.normalScale !== undefined ) {
  24132. var normalScale = json.normalScale;
  24133. if ( Array.isArray( normalScale ) === false ) {
  24134. // Blender exporter used to export a scalar. See #7459
  24135. normalScale = [ normalScale, normalScale ];
  24136. }
  24137. material.normalScale = new Vector2().fromArray( normalScale );
  24138. }
  24139. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24140. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24141. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24142. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24143. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24144. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24145. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24146. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24147. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24148. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24149. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24150. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24151. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24152. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24153. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24154. return material;
  24155. }
  24156. } );
  24157. /**
  24158. * @author mrdoob / http://mrdoob.com/
  24159. */
  24160. function BufferGeometryLoader( manager ) {
  24161. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24162. }
  24163. Object.assign( BufferGeometryLoader.prototype, {
  24164. load: function ( url, onLoad, onProgress, onError ) {
  24165. var scope = this;
  24166. var loader = new FileLoader( scope.manager );
  24167. loader.load( url, function ( text ) {
  24168. onLoad( scope.parse( JSON.parse( text ) ) );
  24169. }, onProgress, onError );
  24170. },
  24171. parse: function ( json ) {
  24172. var geometry = new BufferGeometry();
  24173. var index = json.data.index;
  24174. if ( index !== undefined ) {
  24175. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  24176. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24177. }
  24178. var attributes = json.data.attributes;
  24179. for ( var key in attributes ) {
  24180. var attribute = attributes[ key ];
  24181. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  24182. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  24183. }
  24184. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24185. if ( groups !== undefined ) {
  24186. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  24187. var group = groups[ i ];
  24188. geometry.addGroup( group.start, group.count, group.materialIndex );
  24189. }
  24190. }
  24191. var boundingSphere = json.data.boundingSphere;
  24192. if ( boundingSphere !== undefined ) {
  24193. var center = new Vector3();
  24194. if ( boundingSphere.center !== undefined ) {
  24195. center.fromArray( boundingSphere.center );
  24196. }
  24197. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24198. }
  24199. return geometry;
  24200. }
  24201. } );
  24202. var TYPED_ARRAYS = {
  24203. Int8Array: Int8Array,
  24204. Uint8Array: Uint8Array,
  24205. // Workaround for IE11 pre KB2929437. See #11440
  24206. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  24207. Int16Array: Int16Array,
  24208. Uint16Array: Uint16Array,
  24209. Int32Array: Int32Array,
  24210. Uint32Array: Uint32Array,
  24211. Float32Array: Float32Array,
  24212. Float64Array: Float64Array
  24213. };
  24214. /**
  24215. * @author alteredq / http://alteredqualia.com/
  24216. */
  24217. function Loader() {
  24218. this.onLoadStart = function () {};
  24219. this.onLoadProgress = function () {};
  24220. this.onLoadComplete = function () {};
  24221. }
  24222. Loader.Handlers = {
  24223. handlers: [],
  24224. add: function ( regex, loader ) {
  24225. this.handlers.push( regex, loader );
  24226. },
  24227. get: function ( file ) {
  24228. var handlers = this.handlers;
  24229. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  24230. var regex = handlers[ i ];
  24231. var loader = handlers[ i + 1 ];
  24232. if ( regex.test( file ) ) {
  24233. return loader;
  24234. }
  24235. }
  24236. return null;
  24237. }
  24238. };
  24239. Object.assign( Loader.prototype, {
  24240. crossOrigin: undefined,
  24241. extractUrlBase: function ( url ) {
  24242. var parts = url.split( '/' );
  24243. if ( parts.length === 1 ) return './';
  24244. parts.pop();
  24245. return parts.join( '/' ) + '/';
  24246. },
  24247. initMaterials: function ( materials, texturePath, crossOrigin ) {
  24248. var array = [];
  24249. for ( var i = 0; i < materials.length; ++ i ) {
  24250. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  24251. }
  24252. return array;
  24253. },
  24254. createMaterial: ( function () {
  24255. var BlendingMode = {
  24256. NoBlending: NoBlending,
  24257. NormalBlending: NormalBlending,
  24258. AdditiveBlending: AdditiveBlending,
  24259. SubtractiveBlending: SubtractiveBlending,
  24260. MultiplyBlending: MultiplyBlending,
  24261. CustomBlending: CustomBlending
  24262. };
  24263. var color = new Color();
  24264. var textureLoader = new TextureLoader();
  24265. var materialLoader = new MaterialLoader();
  24266. return function createMaterial( m, texturePath, crossOrigin ) {
  24267. // convert from old material format
  24268. var textures = {};
  24269. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  24270. var fullPath = texturePath + path;
  24271. var loader = Loader.Handlers.get( fullPath );
  24272. var texture;
  24273. if ( loader !== null ) {
  24274. texture = loader.load( fullPath );
  24275. } else {
  24276. textureLoader.setCrossOrigin( crossOrigin );
  24277. texture = textureLoader.load( fullPath );
  24278. }
  24279. if ( repeat !== undefined ) {
  24280. texture.repeat.fromArray( repeat );
  24281. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  24282. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  24283. }
  24284. if ( offset !== undefined ) {
  24285. texture.offset.fromArray( offset );
  24286. }
  24287. if ( wrap !== undefined ) {
  24288. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  24289. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  24290. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  24291. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  24292. }
  24293. if ( anisotropy !== undefined ) {
  24294. texture.anisotropy = anisotropy;
  24295. }
  24296. var uuid = _Math.generateUUID();
  24297. textures[ uuid ] = texture;
  24298. return uuid;
  24299. }
  24300. //
  24301. var json = {
  24302. uuid: _Math.generateUUID(),
  24303. type: 'MeshLambertMaterial'
  24304. };
  24305. for ( var name in m ) {
  24306. var value = m[ name ];
  24307. switch ( name ) {
  24308. case 'DbgColor':
  24309. case 'DbgIndex':
  24310. case 'opticalDensity':
  24311. case 'illumination':
  24312. break;
  24313. case 'DbgName':
  24314. json.name = value;
  24315. break;
  24316. case 'blending':
  24317. json.blending = BlendingMode[ value ];
  24318. break;
  24319. case 'colorAmbient':
  24320. case 'mapAmbient':
  24321. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  24322. break;
  24323. case 'colorDiffuse':
  24324. json.color = color.fromArray( value ).getHex();
  24325. break;
  24326. case 'colorSpecular':
  24327. json.specular = color.fromArray( value ).getHex();
  24328. break;
  24329. case 'colorEmissive':
  24330. json.emissive = color.fromArray( value ).getHex();
  24331. break;
  24332. case 'specularCoef':
  24333. json.shininess = value;
  24334. break;
  24335. case 'shading':
  24336. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  24337. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  24338. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  24339. break;
  24340. case 'mapDiffuse':
  24341. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  24342. break;
  24343. case 'mapDiffuseRepeat':
  24344. case 'mapDiffuseOffset':
  24345. case 'mapDiffuseWrap':
  24346. case 'mapDiffuseAnisotropy':
  24347. break;
  24348. case 'mapEmissive':
  24349. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  24350. break;
  24351. case 'mapEmissiveRepeat':
  24352. case 'mapEmissiveOffset':
  24353. case 'mapEmissiveWrap':
  24354. case 'mapEmissiveAnisotropy':
  24355. break;
  24356. case 'mapLight':
  24357. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  24358. break;
  24359. case 'mapLightRepeat':
  24360. case 'mapLightOffset':
  24361. case 'mapLightWrap':
  24362. case 'mapLightAnisotropy':
  24363. break;
  24364. case 'mapAO':
  24365. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  24366. break;
  24367. case 'mapAORepeat':
  24368. case 'mapAOOffset':
  24369. case 'mapAOWrap':
  24370. case 'mapAOAnisotropy':
  24371. break;
  24372. case 'mapBump':
  24373. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  24374. break;
  24375. case 'mapBumpScale':
  24376. json.bumpScale = value;
  24377. break;
  24378. case 'mapBumpRepeat':
  24379. case 'mapBumpOffset':
  24380. case 'mapBumpWrap':
  24381. case 'mapBumpAnisotropy':
  24382. break;
  24383. case 'mapNormal':
  24384. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  24385. break;
  24386. case 'mapNormalFactor':
  24387. json.normalScale = [ value, value ];
  24388. break;
  24389. case 'mapNormalRepeat':
  24390. case 'mapNormalOffset':
  24391. case 'mapNormalWrap':
  24392. case 'mapNormalAnisotropy':
  24393. break;
  24394. case 'mapSpecular':
  24395. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  24396. break;
  24397. case 'mapSpecularRepeat':
  24398. case 'mapSpecularOffset':
  24399. case 'mapSpecularWrap':
  24400. case 'mapSpecularAnisotropy':
  24401. break;
  24402. case 'mapMetalness':
  24403. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  24404. break;
  24405. case 'mapMetalnessRepeat':
  24406. case 'mapMetalnessOffset':
  24407. case 'mapMetalnessWrap':
  24408. case 'mapMetalnessAnisotropy':
  24409. break;
  24410. case 'mapRoughness':
  24411. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  24412. break;
  24413. case 'mapRoughnessRepeat':
  24414. case 'mapRoughnessOffset':
  24415. case 'mapRoughnessWrap':
  24416. case 'mapRoughnessAnisotropy':
  24417. break;
  24418. case 'mapAlpha':
  24419. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  24420. break;
  24421. case 'mapAlphaRepeat':
  24422. case 'mapAlphaOffset':
  24423. case 'mapAlphaWrap':
  24424. case 'mapAlphaAnisotropy':
  24425. break;
  24426. case 'flipSided':
  24427. json.side = BackSide;
  24428. break;
  24429. case 'doubleSided':
  24430. json.side = DoubleSide;
  24431. break;
  24432. case 'transparency':
  24433. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  24434. json.opacity = value;
  24435. break;
  24436. case 'depthTest':
  24437. case 'depthWrite':
  24438. case 'colorWrite':
  24439. case 'opacity':
  24440. case 'reflectivity':
  24441. case 'transparent':
  24442. case 'visible':
  24443. case 'wireframe':
  24444. json[ name ] = value;
  24445. break;
  24446. case 'vertexColors':
  24447. if ( value === true ) json.vertexColors = VertexColors;
  24448. if ( value === 'face' ) json.vertexColors = FaceColors;
  24449. break;
  24450. default:
  24451. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  24452. break;
  24453. }
  24454. }
  24455. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  24456. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  24457. if ( json.opacity < 1 ) json.transparent = true;
  24458. materialLoader.setTextures( textures );
  24459. return materialLoader.parse( json );
  24460. };
  24461. } )()
  24462. } );
  24463. /**
  24464. * @author mrdoob / http://mrdoob.com/
  24465. * @author alteredq / http://alteredqualia.com/
  24466. */
  24467. function JSONLoader( manager ) {
  24468. if ( typeof manager === 'boolean' ) {
  24469. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  24470. manager = undefined;
  24471. }
  24472. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24473. this.withCredentials = false;
  24474. }
  24475. Object.assign( JSONLoader.prototype, {
  24476. load: function ( url, onLoad, onProgress, onError ) {
  24477. var scope = this;
  24478. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  24479. var loader = new FileLoader( this.manager );
  24480. loader.setWithCredentials( this.withCredentials );
  24481. loader.load( url, function ( text ) {
  24482. var json = JSON.parse( text );
  24483. var metadata = json.metadata;
  24484. if ( metadata !== undefined ) {
  24485. var type = metadata.type;
  24486. if ( type !== undefined ) {
  24487. if ( type.toLowerCase() === 'object' ) {
  24488. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  24489. return;
  24490. }
  24491. if ( type.toLowerCase() === 'scene' ) {
  24492. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  24493. return;
  24494. }
  24495. }
  24496. }
  24497. var object = scope.parse( json, texturePath );
  24498. onLoad( object.geometry, object.materials );
  24499. }, onProgress, onError );
  24500. },
  24501. setTexturePath: function ( value ) {
  24502. this.texturePath = value;
  24503. },
  24504. parse: ( function () {
  24505. function parseModel( json, geometry ) {
  24506. function isBitSet( value, position ) {
  24507. return value & ( 1 << position );
  24508. }
  24509. var i, j, fi,
  24510. offset, zLength,
  24511. colorIndex, normalIndex, uvIndex, materialIndex,
  24512. type,
  24513. isQuad,
  24514. hasMaterial,
  24515. hasFaceVertexUv,
  24516. hasFaceNormal, hasFaceVertexNormal,
  24517. hasFaceColor, hasFaceVertexColor,
  24518. vertex, face, faceA, faceB, hex, normal,
  24519. uvLayer, uv, u, v,
  24520. faces = json.faces,
  24521. vertices = json.vertices,
  24522. normals = json.normals,
  24523. colors = json.colors,
  24524. scale = json.scale,
  24525. nUvLayers = 0;
  24526. if ( json.uvs !== undefined ) {
  24527. // disregard empty arrays
  24528. for ( i = 0; i < json.uvs.length; i ++ ) {
  24529. if ( json.uvs[ i ].length ) nUvLayers ++;
  24530. }
  24531. for ( i = 0; i < nUvLayers; i ++ ) {
  24532. geometry.faceVertexUvs[ i ] = [];
  24533. }
  24534. }
  24535. offset = 0;
  24536. zLength = vertices.length;
  24537. while ( offset < zLength ) {
  24538. vertex = new Vector3();
  24539. vertex.x = vertices[ offset ++ ] * scale;
  24540. vertex.y = vertices[ offset ++ ] * scale;
  24541. vertex.z = vertices[ offset ++ ] * scale;
  24542. geometry.vertices.push( vertex );
  24543. }
  24544. offset = 0;
  24545. zLength = faces.length;
  24546. while ( offset < zLength ) {
  24547. type = faces[ offset ++ ];
  24548. isQuad = isBitSet( type, 0 );
  24549. hasMaterial = isBitSet( type, 1 );
  24550. hasFaceVertexUv = isBitSet( type, 3 );
  24551. hasFaceNormal = isBitSet( type, 4 );
  24552. hasFaceVertexNormal = isBitSet( type, 5 );
  24553. hasFaceColor = isBitSet( type, 6 );
  24554. hasFaceVertexColor = isBitSet( type, 7 );
  24555. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  24556. if ( isQuad ) {
  24557. faceA = new Face3();
  24558. faceA.a = faces[ offset ];
  24559. faceA.b = faces[ offset + 1 ];
  24560. faceA.c = faces[ offset + 3 ];
  24561. faceB = new Face3();
  24562. faceB.a = faces[ offset + 1 ];
  24563. faceB.b = faces[ offset + 2 ];
  24564. faceB.c = faces[ offset + 3 ];
  24565. offset += 4;
  24566. if ( hasMaterial ) {
  24567. materialIndex = faces[ offset ++ ];
  24568. faceA.materialIndex = materialIndex;
  24569. faceB.materialIndex = materialIndex;
  24570. }
  24571. // to get face <=> uv index correspondence
  24572. fi = geometry.faces.length;
  24573. if ( hasFaceVertexUv ) {
  24574. for ( i = 0; i < nUvLayers; i ++ ) {
  24575. uvLayer = json.uvs[ i ];
  24576. geometry.faceVertexUvs[ i ][ fi ] = [];
  24577. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  24578. for ( j = 0; j < 4; j ++ ) {
  24579. uvIndex = faces[ offset ++ ];
  24580. u = uvLayer[ uvIndex * 2 ];
  24581. v = uvLayer[ uvIndex * 2 + 1 ];
  24582. uv = new Vector2( u, v );
  24583. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24584. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  24585. }
  24586. }
  24587. }
  24588. if ( hasFaceNormal ) {
  24589. normalIndex = faces[ offset ++ ] * 3;
  24590. faceA.normal.set(
  24591. normals[ normalIndex ++ ],
  24592. normals[ normalIndex ++ ],
  24593. normals[ normalIndex ]
  24594. );
  24595. faceB.normal.copy( faceA.normal );
  24596. }
  24597. if ( hasFaceVertexNormal ) {
  24598. for ( i = 0; i < 4; i ++ ) {
  24599. normalIndex = faces[ offset ++ ] * 3;
  24600. normal = new Vector3(
  24601. normals[ normalIndex ++ ],
  24602. normals[ normalIndex ++ ],
  24603. normals[ normalIndex ]
  24604. );
  24605. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  24606. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  24607. }
  24608. }
  24609. if ( hasFaceColor ) {
  24610. colorIndex = faces[ offset ++ ];
  24611. hex = colors[ colorIndex ];
  24612. faceA.color.setHex( hex );
  24613. faceB.color.setHex( hex );
  24614. }
  24615. if ( hasFaceVertexColor ) {
  24616. for ( i = 0; i < 4; i ++ ) {
  24617. colorIndex = faces[ offset ++ ];
  24618. hex = colors[ colorIndex ];
  24619. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  24620. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  24621. }
  24622. }
  24623. geometry.faces.push( faceA );
  24624. geometry.faces.push( faceB );
  24625. } else {
  24626. face = new Face3();
  24627. face.a = faces[ offset ++ ];
  24628. face.b = faces[ offset ++ ];
  24629. face.c = faces[ offset ++ ];
  24630. if ( hasMaterial ) {
  24631. materialIndex = faces[ offset ++ ];
  24632. face.materialIndex = materialIndex;
  24633. }
  24634. // to get face <=> uv index correspondence
  24635. fi = geometry.faces.length;
  24636. if ( hasFaceVertexUv ) {
  24637. for ( i = 0; i < nUvLayers; i ++ ) {
  24638. uvLayer = json.uvs[ i ];
  24639. geometry.faceVertexUvs[ i ][ fi ] = [];
  24640. for ( j = 0; j < 3; j ++ ) {
  24641. uvIndex = faces[ offset ++ ];
  24642. u = uvLayer[ uvIndex * 2 ];
  24643. v = uvLayer[ uvIndex * 2 + 1 ];
  24644. uv = new Vector2( u, v );
  24645. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24646. }
  24647. }
  24648. }
  24649. if ( hasFaceNormal ) {
  24650. normalIndex = faces[ offset ++ ] * 3;
  24651. face.normal.set(
  24652. normals[ normalIndex ++ ],
  24653. normals[ normalIndex ++ ],
  24654. normals[ normalIndex ]
  24655. );
  24656. }
  24657. if ( hasFaceVertexNormal ) {
  24658. for ( i = 0; i < 3; i ++ ) {
  24659. normalIndex = faces[ offset ++ ] * 3;
  24660. normal = new Vector3(
  24661. normals[ normalIndex ++ ],
  24662. normals[ normalIndex ++ ],
  24663. normals[ normalIndex ]
  24664. );
  24665. face.vertexNormals.push( normal );
  24666. }
  24667. }
  24668. if ( hasFaceColor ) {
  24669. colorIndex = faces[ offset ++ ];
  24670. face.color.setHex( colors[ colorIndex ] );
  24671. }
  24672. if ( hasFaceVertexColor ) {
  24673. for ( i = 0; i < 3; i ++ ) {
  24674. colorIndex = faces[ offset ++ ];
  24675. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  24676. }
  24677. }
  24678. geometry.faces.push( face );
  24679. }
  24680. }
  24681. }
  24682. function parseSkin( json, geometry ) {
  24683. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  24684. if ( json.skinWeights ) {
  24685. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  24686. var x = json.skinWeights[ i ];
  24687. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  24688. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  24689. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  24690. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  24691. }
  24692. }
  24693. if ( json.skinIndices ) {
  24694. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  24695. var a = json.skinIndices[ i ];
  24696. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  24697. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  24698. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  24699. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  24700. }
  24701. }
  24702. geometry.bones = json.bones;
  24703. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  24704. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  24705. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  24706. }
  24707. }
  24708. function parseMorphing( json, geometry ) {
  24709. var scale = json.scale;
  24710. if ( json.morphTargets !== undefined ) {
  24711. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  24712. geometry.morphTargets[ i ] = {};
  24713. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  24714. geometry.morphTargets[ i ].vertices = [];
  24715. var dstVertices = geometry.morphTargets[ i ].vertices;
  24716. var srcVertices = json.morphTargets[ i ].vertices;
  24717. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  24718. var vertex = new Vector3();
  24719. vertex.x = srcVertices[ v ] * scale;
  24720. vertex.y = srcVertices[ v + 1 ] * scale;
  24721. vertex.z = srcVertices[ v + 2 ] * scale;
  24722. dstVertices.push( vertex );
  24723. }
  24724. }
  24725. }
  24726. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  24727. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  24728. var faces = geometry.faces;
  24729. var morphColors = json.morphColors[ 0 ].colors;
  24730. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24731. faces[ i ].color.fromArray( morphColors, i * 3 );
  24732. }
  24733. }
  24734. }
  24735. function parseAnimations( json, geometry ) {
  24736. var outputAnimations = [];
  24737. // parse old style Bone/Hierarchy animations
  24738. var animations = [];
  24739. if ( json.animation !== undefined ) {
  24740. animations.push( json.animation );
  24741. }
  24742. if ( json.animations !== undefined ) {
  24743. if ( json.animations.length ) {
  24744. animations = animations.concat( json.animations );
  24745. } else {
  24746. animations.push( json.animations );
  24747. }
  24748. }
  24749. for ( var i = 0; i < animations.length; i ++ ) {
  24750. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  24751. if ( clip ) outputAnimations.push( clip );
  24752. }
  24753. // parse implicit morph animations
  24754. if ( geometry.morphTargets ) {
  24755. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  24756. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  24757. outputAnimations = outputAnimations.concat( morphAnimationClips );
  24758. }
  24759. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  24760. }
  24761. return function ( json, texturePath ) {
  24762. if ( json.data !== undefined ) {
  24763. // Geometry 4.0 spec
  24764. json = json.data;
  24765. }
  24766. if ( json.scale !== undefined ) {
  24767. json.scale = 1.0 / json.scale;
  24768. } else {
  24769. json.scale = 1.0;
  24770. }
  24771. var geometry = new Geometry();
  24772. parseModel( json, geometry );
  24773. parseSkin( json, geometry );
  24774. parseMorphing( json, geometry );
  24775. parseAnimations( json, geometry );
  24776. geometry.computeFaceNormals();
  24777. geometry.computeBoundingSphere();
  24778. if ( json.materials === undefined || json.materials.length === 0 ) {
  24779. return { geometry: geometry };
  24780. } else {
  24781. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  24782. return { geometry: geometry, materials: materials };
  24783. }
  24784. };
  24785. } )()
  24786. } );
  24787. /**
  24788. * @author mrdoob / http://mrdoob.com/
  24789. */
  24790. function ObjectLoader( manager ) {
  24791. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24792. this.texturePath = '';
  24793. }
  24794. Object.assign( ObjectLoader.prototype, {
  24795. load: function ( url, onLoad, onProgress, onError ) {
  24796. if ( this.texturePath === '' ) {
  24797. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  24798. }
  24799. var scope = this;
  24800. var loader = new FileLoader( scope.manager );
  24801. loader.load( url, function ( text ) {
  24802. var json = null;
  24803. try {
  24804. json = JSON.parse( text );
  24805. } catch ( error ) {
  24806. if ( onError !== undefined ) onError( error );
  24807. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24808. return;
  24809. }
  24810. var metadata = json.metadata;
  24811. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24812. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  24813. return;
  24814. }
  24815. scope.parse( json, onLoad );
  24816. }, onProgress, onError );
  24817. },
  24818. setTexturePath: function ( value ) {
  24819. this.texturePath = value;
  24820. },
  24821. setCrossOrigin: function ( value ) {
  24822. this.crossOrigin = value;
  24823. },
  24824. parse: function ( json, onLoad ) {
  24825. var geometries = this.parseGeometries( json.geometries );
  24826. var images = this.parseImages( json.images, function () {
  24827. if ( onLoad !== undefined ) onLoad( object );
  24828. } );
  24829. var textures = this.parseTextures( json.textures, images );
  24830. var materials = this.parseMaterials( json.materials, textures );
  24831. var object = this.parseObject( json.object, geometries, materials );
  24832. if ( json.animations ) {
  24833. object.animations = this.parseAnimations( json.animations );
  24834. }
  24835. if ( json.images === undefined || json.images.length === 0 ) {
  24836. if ( onLoad !== undefined ) onLoad( object );
  24837. }
  24838. return object;
  24839. },
  24840. parseGeometries: function ( json ) {
  24841. var geometries = {};
  24842. if ( json !== undefined ) {
  24843. var geometryLoader = new JSONLoader();
  24844. var bufferGeometryLoader = new BufferGeometryLoader();
  24845. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24846. var geometry;
  24847. var data = json[ i ];
  24848. switch ( data.type ) {
  24849. case 'PlaneGeometry':
  24850. case 'PlaneBufferGeometry':
  24851. geometry = new Geometries[ data.type ](
  24852. data.width,
  24853. data.height,
  24854. data.widthSegments,
  24855. data.heightSegments
  24856. );
  24857. break;
  24858. case 'BoxGeometry':
  24859. case 'BoxBufferGeometry':
  24860. case 'CubeGeometry': // backwards compatible
  24861. geometry = new Geometries[ data.type ](
  24862. data.width,
  24863. data.height,
  24864. data.depth,
  24865. data.widthSegments,
  24866. data.heightSegments,
  24867. data.depthSegments
  24868. );
  24869. break;
  24870. case 'CircleGeometry':
  24871. case 'CircleBufferGeometry':
  24872. geometry = new Geometries[ data.type ](
  24873. data.radius,
  24874. data.segments,
  24875. data.thetaStart,
  24876. data.thetaLength
  24877. );
  24878. break;
  24879. case 'CylinderGeometry':
  24880. case 'CylinderBufferGeometry':
  24881. geometry = new Geometries[ data.type ](
  24882. data.radiusTop,
  24883. data.radiusBottom,
  24884. data.height,
  24885. data.radialSegments,
  24886. data.heightSegments,
  24887. data.openEnded,
  24888. data.thetaStart,
  24889. data.thetaLength
  24890. );
  24891. break;
  24892. case 'ConeGeometry':
  24893. case 'ConeBufferGeometry':
  24894. geometry = new Geometries[ data.type ](
  24895. data.radius,
  24896. data.height,
  24897. data.radialSegments,
  24898. data.heightSegments,
  24899. data.openEnded,
  24900. data.thetaStart,
  24901. data.thetaLength
  24902. );
  24903. break;
  24904. case 'SphereGeometry':
  24905. case 'SphereBufferGeometry':
  24906. geometry = new Geometries[ data.type ](
  24907. data.radius,
  24908. data.widthSegments,
  24909. data.heightSegments,
  24910. data.phiStart,
  24911. data.phiLength,
  24912. data.thetaStart,
  24913. data.thetaLength
  24914. );
  24915. break;
  24916. case 'DodecahedronGeometry':
  24917. case 'IcosahedronGeometry':
  24918. case 'OctahedronGeometry':
  24919. case 'TetrahedronGeometry':
  24920. geometry = new Geometries[ data.type ](
  24921. data.radius,
  24922. data.detail
  24923. );
  24924. break;
  24925. case 'RingGeometry':
  24926. case 'RingBufferGeometry':
  24927. geometry = new Geometries[ data.type ](
  24928. data.innerRadius,
  24929. data.outerRadius,
  24930. data.thetaSegments,
  24931. data.phiSegments,
  24932. data.thetaStart,
  24933. data.thetaLength
  24934. );
  24935. break;
  24936. case 'TorusGeometry':
  24937. case 'TorusBufferGeometry':
  24938. geometry = new Geometries[ data.type ](
  24939. data.radius,
  24940. data.tube,
  24941. data.radialSegments,
  24942. data.tubularSegments,
  24943. data.arc
  24944. );
  24945. break;
  24946. case 'TorusKnotGeometry':
  24947. case 'TorusKnotBufferGeometry':
  24948. geometry = new Geometries[ data.type ](
  24949. data.radius,
  24950. data.tube,
  24951. data.tubularSegments,
  24952. data.radialSegments,
  24953. data.p,
  24954. data.q
  24955. );
  24956. break;
  24957. case 'LatheGeometry':
  24958. case 'LatheBufferGeometry':
  24959. geometry = new Geometries[ data.type ](
  24960. data.points,
  24961. data.segments,
  24962. data.phiStart,
  24963. data.phiLength
  24964. );
  24965. break;
  24966. case 'BufferGeometry':
  24967. geometry = bufferGeometryLoader.parse( data );
  24968. break;
  24969. case 'Geometry':
  24970. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  24971. break;
  24972. default:
  24973. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  24974. continue;
  24975. }
  24976. geometry.uuid = data.uuid;
  24977. if ( data.name !== undefined ) geometry.name = data.name;
  24978. geometries[ data.uuid ] = geometry;
  24979. }
  24980. }
  24981. return geometries;
  24982. },
  24983. parseMaterials: function ( json, textures ) {
  24984. var materials = {};
  24985. if ( json !== undefined ) {
  24986. var loader = new MaterialLoader();
  24987. loader.setTextures( textures );
  24988. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24989. var data = json[ i ];
  24990. if ( data.type === 'MultiMaterial' ) {
  24991. // Deprecated
  24992. var array = [];
  24993. for ( var j = 0; j < data.materials.length; j ++ ) {
  24994. array.push( loader.parse( data.materials[ j ] ) );
  24995. }
  24996. materials[ data.uuid ] = array;
  24997. } else {
  24998. materials[ data.uuid ] = loader.parse( data );
  24999. }
  25000. }
  25001. }
  25002. return materials;
  25003. },
  25004. parseAnimations: function ( json ) {
  25005. var animations = [];
  25006. for ( var i = 0; i < json.length; i ++ ) {
  25007. var clip = AnimationClip.parse( json[ i ] );
  25008. animations.push( clip );
  25009. }
  25010. return animations;
  25011. },
  25012. parseImages: function ( json, onLoad ) {
  25013. var scope = this;
  25014. var images = {};
  25015. function loadImage( url ) {
  25016. scope.manager.itemStart( url );
  25017. return loader.load( url, function () {
  25018. scope.manager.itemEnd( url );
  25019. }, undefined, function () {
  25020. scope.manager.itemEnd( url );
  25021. scope.manager.itemError( url );
  25022. } );
  25023. }
  25024. if ( json !== undefined && json.length > 0 ) {
  25025. var manager = new LoadingManager( onLoad );
  25026. var loader = new ImageLoader( manager );
  25027. loader.setCrossOrigin( this.crossOrigin );
  25028. for ( var i = 0, l = json.length; i < l; i ++ ) {
  25029. var image = json[ i ];
  25030. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  25031. images[ image.uuid ] = loadImage( path );
  25032. }
  25033. }
  25034. return images;
  25035. },
  25036. parseTextures: function ( json, images ) {
  25037. function parseConstant( value, type ) {
  25038. if ( typeof( value ) === 'number' ) return value;
  25039. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25040. return type[ value ];
  25041. }
  25042. var textures = {};
  25043. if ( json !== undefined ) {
  25044. for ( var i = 0, l = json.length; i < l; i ++ ) {
  25045. var data = json[ i ];
  25046. if ( data.image === undefined ) {
  25047. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25048. }
  25049. if ( images[ data.image ] === undefined ) {
  25050. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25051. }
  25052. var texture = new Texture( images[ data.image ] );
  25053. texture.needsUpdate = true;
  25054. texture.uuid = data.uuid;
  25055. if ( data.name !== undefined ) texture.name = data.name;
  25056. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25057. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25058. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25059. if ( data.wrap !== undefined ) {
  25060. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25061. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25062. }
  25063. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25064. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25065. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25066. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25067. textures[ data.uuid ] = texture;
  25068. }
  25069. }
  25070. return textures;
  25071. },
  25072. parseObject: function () {
  25073. var matrix = new Matrix4();
  25074. return function parseObject( data, geometries, materials ) {
  25075. var object;
  25076. function getGeometry( name ) {
  25077. if ( geometries[ name ] === undefined ) {
  25078. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25079. }
  25080. return geometries[ name ];
  25081. }
  25082. function getMaterial( name ) {
  25083. if ( name === undefined ) return undefined;
  25084. if ( Array.isArray( name ) ) {
  25085. var array = [];
  25086. for ( var i = 0, l = name.length; i < l; i ++ ) {
  25087. var uuid = name[ i ];
  25088. if ( materials[ uuid ] === undefined ) {
  25089. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25090. }
  25091. array.push( materials[ uuid ] );
  25092. }
  25093. return array;
  25094. }
  25095. if ( materials[ name ] === undefined ) {
  25096. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25097. }
  25098. return materials[ name ];
  25099. }
  25100. switch ( data.type ) {
  25101. case 'Scene':
  25102. object = new Scene();
  25103. if ( data.background !== undefined ) {
  25104. if ( Number.isInteger( data.background ) ) {
  25105. object.background = new Color( data.background );
  25106. }
  25107. }
  25108. if ( data.fog !== undefined ) {
  25109. if ( data.fog.type === 'Fog' ) {
  25110. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25111. } else if ( data.fog.type === 'FogExp2' ) {
  25112. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25113. }
  25114. }
  25115. break;
  25116. case 'PerspectiveCamera':
  25117. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25118. if ( data.focus !== undefined ) object.focus = data.focus;
  25119. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25120. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25121. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25122. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25123. break;
  25124. case 'OrthographicCamera':
  25125. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25126. break;
  25127. case 'AmbientLight':
  25128. object = new AmbientLight( data.color, data.intensity );
  25129. break;
  25130. case 'DirectionalLight':
  25131. object = new DirectionalLight( data.color, data.intensity );
  25132. break;
  25133. case 'PointLight':
  25134. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25135. break;
  25136. case 'RectAreaLight':
  25137. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25138. break;
  25139. case 'SpotLight':
  25140. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25141. break;
  25142. case 'HemisphereLight':
  25143. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25144. break;
  25145. case 'SkinnedMesh':
  25146. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  25147. case 'Mesh':
  25148. var geometry = getGeometry( data.geometry );
  25149. var material = getMaterial( data.material );
  25150. if ( geometry.bones && geometry.bones.length > 0 ) {
  25151. object = new SkinnedMesh( geometry, material );
  25152. } else {
  25153. object = new Mesh( geometry, material );
  25154. }
  25155. break;
  25156. case 'LOD':
  25157. object = new LOD();
  25158. break;
  25159. case 'Line':
  25160. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  25161. break;
  25162. case 'LineLoop':
  25163. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25164. break;
  25165. case 'LineSegments':
  25166. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25167. break;
  25168. case 'PointCloud':
  25169. case 'Points':
  25170. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25171. break;
  25172. case 'Sprite':
  25173. object = new Sprite( getMaterial( data.material ) );
  25174. break;
  25175. case 'Group':
  25176. object = new Group();
  25177. break;
  25178. default:
  25179. object = new Object3D();
  25180. }
  25181. object.uuid = data.uuid;
  25182. if ( data.name !== undefined ) object.name = data.name;
  25183. if ( data.matrix !== undefined ) {
  25184. matrix.fromArray( data.matrix );
  25185. matrix.decompose( object.position, object.quaternion, object.scale );
  25186. } else {
  25187. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25188. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25189. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25190. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25191. }
  25192. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25193. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25194. if ( data.shadow ) {
  25195. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25196. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25197. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25198. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25199. }
  25200. if ( data.visible !== undefined ) object.visible = data.visible;
  25201. if ( data.userData !== undefined ) object.userData = data.userData;
  25202. if ( data.children !== undefined ) {
  25203. var children = data.children;
  25204. for ( var i = 0; i < children.length; i ++ ) {
  25205. object.add( this.parseObject( children[ i ], geometries, materials ) );
  25206. }
  25207. }
  25208. if ( data.type === 'LOD' ) {
  25209. var levels = data.levels;
  25210. for ( var l = 0; l < levels.length; l ++ ) {
  25211. var level = levels[ l ];
  25212. var child = object.getObjectByProperty( 'uuid', level.object );
  25213. if ( child !== undefined ) {
  25214. object.addLevel( child, level.distance );
  25215. }
  25216. }
  25217. }
  25218. return object;
  25219. };
  25220. }()
  25221. } );
  25222. var TEXTURE_MAPPING = {
  25223. UVMapping: UVMapping,
  25224. CubeReflectionMapping: CubeReflectionMapping,
  25225. CubeRefractionMapping: CubeRefractionMapping,
  25226. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25227. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25228. SphericalReflectionMapping: SphericalReflectionMapping,
  25229. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25230. CubeUVRefractionMapping: CubeUVRefractionMapping
  25231. };
  25232. var TEXTURE_WRAPPING = {
  25233. RepeatWrapping: RepeatWrapping,
  25234. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25235. MirroredRepeatWrapping: MirroredRepeatWrapping
  25236. };
  25237. var TEXTURE_FILTER = {
  25238. NearestFilter: NearestFilter,
  25239. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  25240. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  25241. LinearFilter: LinearFilter,
  25242. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  25243. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  25244. };
  25245. /**
  25246. * @author zz85 / http://www.lab4games.net/zz85/blog
  25247. *
  25248. * Bezier Curves formulas obtained from
  25249. * http://en.wikipedia.org/wiki/Bézier_curve
  25250. */
  25251. function CatmullRom( t, p0, p1, p2, p3 ) {
  25252. var v0 = ( p2 - p0 ) * 0.5;
  25253. var v1 = ( p3 - p1 ) * 0.5;
  25254. var t2 = t * t;
  25255. var t3 = t * t2;
  25256. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  25257. }
  25258. //
  25259. function QuadraticBezierP0( t, p ) {
  25260. var k = 1 - t;
  25261. return k * k * p;
  25262. }
  25263. function QuadraticBezierP1( t, p ) {
  25264. return 2 * ( 1 - t ) * t * p;
  25265. }
  25266. function QuadraticBezierP2( t, p ) {
  25267. return t * t * p;
  25268. }
  25269. function QuadraticBezier( t, p0, p1, p2 ) {
  25270. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  25271. QuadraticBezierP2( t, p2 );
  25272. }
  25273. //
  25274. function CubicBezierP0( t, p ) {
  25275. var k = 1 - t;
  25276. return k * k * k * p;
  25277. }
  25278. function CubicBezierP1( t, p ) {
  25279. var k = 1 - t;
  25280. return 3 * k * k * t * p;
  25281. }
  25282. function CubicBezierP2( t, p ) {
  25283. return 3 * ( 1 - t ) * t * t * p;
  25284. }
  25285. function CubicBezierP3( t, p ) {
  25286. return t * t * t * p;
  25287. }
  25288. function CubicBezier( t, p0, p1, p2, p3 ) {
  25289. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  25290. CubicBezierP3( t, p3 );
  25291. }
  25292. /**
  25293. * @author zz85 / http://www.lab4games.net/zz85/blog
  25294. * Extensible curve object
  25295. *
  25296. * Some common of curve methods:
  25297. * .getPoint(t), getTangent(t)
  25298. * .getPointAt(u), getTangentAt(u)
  25299. * .getPoints(), .getSpacedPoints()
  25300. * .getLength()
  25301. * .updateArcLengths()
  25302. *
  25303. * This following curves inherit from THREE.Curve:
  25304. *
  25305. * -- 2D curves --
  25306. * THREE.ArcCurve
  25307. * THREE.CubicBezierCurve
  25308. * THREE.EllipseCurve
  25309. * THREE.LineCurve
  25310. * THREE.QuadraticBezierCurve
  25311. * THREE.SplineCurve
  25312. *
  25313. * -- 3D curves --
  25314. * THREE.CatmullRomCurve3
  25315. * THREE.CubicBezierCurve3
  25316. * THREE.LineCurve3
  25317. * THREE.QuadraticBezierCurve3
  25318. *
  25319. * A series of curves can be represented as a THREE.CurvePath.
  25320. *
  25321. **/
  25322. /**************************************************************
  25323. * Abstract Curve base class
  25324. **************************************************************/
  25325. function Curve() {
  25326. this.arcLengthDivisions = 200;
  25327. }
  25328. Object.assign( Curve.prototype, {
  25329. // Virtual base class method to overwrite and implement in subclasses
  25330. // - t [0 .. 1]
  25331. getPoint: function () {
  25332. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  25333. return null;
  25334. },
  25335. // Get point at relative position in curve according to arc length
  25336. // - u [0 .. 1]
  25337. getPointAt: function ( u ) {
  25338. var t = this.getUtoTmapping( u );
  25339. return this.getPoint( t );
  25340. },
  25341. // Get sequence of points using getPoint( t )
  25342. getPoints: function ( divisions ) {
  25343. if ( divisions === undefined ) divisions = 5;
  25344. var points = [];
  25345. for ( var d = 0; d <= divisions; d ++ ) {
  25346. points.push( this.getPoint( d / divisions ) );
  25347. }
  25348. return points;
  25349. },
  25350. // Get sequence of points using getPointAt( u )
  25351. getSpacedPoints: function ( divisions ) {
  25352. if ( divisions === undefined ) divisions = 5;
  25353. var points = [];
  25354. for ( var d = 0; d <= divisions; d ++ ) {
  25355. points.push( this.getPointAt( d / divisions ) );
  25356. }
  25357. return points;
  25358. },
  25359. // Get total curve arc length
  25360. getLength: function () {
  25361. var lengths = this.getLengths();
  25362. return lengths[ lengths.length - 1 ];
  25363. },
  25364. // Get list of cumulative segment lengths
  25365. getLengths: function ( divisions ) {
  25366. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  25367. if ( this.cacheArcLengths &&
  25368. ( this.cacheArcLengths.length === divisions + 1 ) &&
  25369. ! this.needsUpdate ) {
  25370. return this.cacheArcLengths;
  25371. }
  25372. this.needsUpdate = false;
  25373. var cache = [];
  25374. var current, last = this.getPoint( 0 );
  25375. var p, sum = 0;
  25376. cache.push( 0 );
  25377. for ( p = 1; p <= divisions; p ++ ) {
  25378. current = this.getPoint( p / divisions );
  25379. sum += current.distanceTo( last );
  25380. cache.push( sum );
  25381. last = current;
  25382. }
  25383. this.cacheArcLengths = cache;
  25384. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  25385. },
  25386. updateArcLengths: function () {
  25387. this.needsUpdate = true;
  25388. this.getLengths();
  25389. },
  25390. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  25391. getUtoTmapping: function ( u, distance ) {
  25392. var arcLengths = this.getLengths();
  25393. var i = 0, il = arcLengths.length;
  25394. var targetArcLength; // The targeted u distance value to get
  25395. if ( distance ) {
  25396. targetArcLength = distance;
  25397. } else {
  25398. targetArcLength = u * arcLengths[ il - 1 ];
  25399. }
  25400. // binary search for the index with largest value smaller than target u distance
  25401. var low = 0, high = il - 1, comparison;
  25402. while ( low <= high ) {
  25403. 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
  25404. comparison = arcLengths[ i ] - targetArcLength;
  25405. if ( comparison < 0 ) {
  25406. low = i + 1;
  25407. } else if ( comparison > 0 ) {
  25408. high = i - 1;
  25409. } else {
  25410. high = i;
  25411. break;
  25412. // DONE
  25413. }
  25414. }
  25415. i = high;
  25416. if ( arcLengths[ i ] === targetArcLength ) {
  25417. return i / ( il - 1 );
  25418. }
  25419. // we could get finer grain at lengths, or use simple interpolation between two points
  25420. var lengthBefore = arcLengths[ i ];
  25421. var lengthAfter = arcLengths[ i + 1 ];
  25422. var segmentLength = lengthAfter - lengthBefore;
  25423. // determine where we are between the 'before' and 'after' points
  25424. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  25425. // add that fractional amount to t
  25426. var t = ( i + segmentFraction ) / ( il - 1 );
  25427. return t;
  25428. },
  25429. // Returns a unit vector tangent at t
  25430. // In case any sub curve does not implement its tangent derivation,
  25431. // 2 points a small delta apart will be used to find its gradient
  25432. // which seems to give a reasonable approximation
  25433. getTangent: function ( t ) {
  25434. var delta = 0.0001;
  25435. var t1 = t - delta;
  25436. var t2 = t + delta;
  25437. // Capping in case of danger
  25438. if ( t1 < 0 ) t1 = 0;
  25439. if ( t2 > 1 ) t2 = 1;
  25440. var pt1 = this.getPoint( t1 );
  25441. var pt2 = this.getPoint( t2 );
  25442. var vec = pt2.clone().sub( pt1 );
  25443. return vec.normalize();
  25444. },
  25445. getTangentAt: function ( u ) {
  25446. var t = this.getUtoTmapping( u );
  25447. return this.getTangent( t );
  25448. },
  25449. computeFrenetFrames: function ( segments, closed ) {
  25450. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  25451. var normal = new Vector3();
  25452. var tangents = [];
  25453. var normals = [];
  25454. var binormals = [];
  25455. var vec = new Vector3();
  25456. var mat = new Matrix4();
  25457. var i, u, theta;
  25458. // compute the tangent vectors for each segment on the curve
  25459. for ( i = 0; i <= segments; i ++ ) {
  25460. u = i / segments;
  25461. tangents[ i ] = this.getTangentAt( u );
  25462. tangents[ i ].normalize();
  25463. }
  25464. // select an initial normal vector perpendicular to the first tangent vector,
  25465. // and in the direction of the minimum tangent xyz component
  25466. normals[ 0 ] = new Vector3();
  25467. binormals[ 0 ] = new Vector3();
  25468. var min = Number.MAX_VALUE;
  25469. var tx = Math.abs( tangents[ 0 ].x );
  25470. var ty = Math.abs( tangents[ 0 ].y );
  25471. var tz = Math.abs( tangents[ 0 ].z );
  25472. if ( tx <= min ) {
  25473. min = tx;
  25474. normal.set( 1, 0, 0 );
  25475. }
  25476. if ( ty <= min ) {
  25477. min = ty;
  25478. normal.set( 0, 1, 0 );
  25479. }
  25480. if ( tz <= min ) {
  25481. normal.set( 0, 0, 1 );
  25482. }
  25483. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  25484. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  25485. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  25486. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  25487. for ( i = 1; i <= segments; i ++ ) {
  25488. normals[ i ] = normals[ i - 1 ].clone();
  25489. binormals[ i ] = binormals[ i - 1 ].clone();
  25490. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  25491. if ( vec.length() > Number.EPSILON ) {
  25492. vec.normalize();
  25493. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  25494. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  25495. }
  25496. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25497. }
  25498. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  25499. if ( closed === true ) {
  25500. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  25501. theta /= segments;
  25502. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  25503. theta = - theta;
  25504. }
  25505. for ( i = 1; i <= segments; i ++ ) {
  25506. // twist a little...
  25507. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  25508. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  25509. }
  25510. }
  25511. return {
  25512. tangents: tangents,
  25513. normals: normals,
  25514. binormals: binormals
  25515. };
  25516. }
  25517. } );
  25518. function LineCurve( v1, v2 ) {
  25519. Curve.call( this );
  25520. this.v1 = v1;
  25521. this.v2 = v2;
  25522. }
  25523. LineCurve.prototype = Object.create( Curve.prototype );
  25524. LineCurve.prototype.constructor = LineCurve;
  25525. LineCurve.prototype.isLineCurve = true;
  25526. LineCurve.prototype.getPoint = function ( t ) {
  25527. if ( t === 1 ) {
  25528. return this.v2.clone();
  25529. }
  25530. var point = this.v2.clone().sub( this.v1 );
  25531. point.multiplyScalar( t ).add( this.v1 );
  25532. return point;
  25533. };
  25534. // Line curve is linear, so we can overwrite default getPointAt
  25535. LineCurve.prototype.getPointAt = function ( u ) {
  25536. return this.getPoint( u );
  25537. };
  25538. LineCurve.prototype.getTangent = function ( t ) {
  25539. var tangent = this.v2.clone().sub( this.v1 );
  25540. return tangent.normalize();
  25541. };
  25542. /**
  25543. * @author zz85 / http://www.lab4games.net/zz85/blog
  25544. *
  25545. **/
  25546. /**************************************************************
  25547. * Curved Path - a curve path is simply a array of connected
  25548. * curves, but retains the api of a curve
  25549. **************************************************************/
  25550. function CurvePath() {
  25551. Curve.call( this );
  25552. this.curves = [];
  25553. this.autoClose = false; // Automatically closes the path
  25554. }
  25555. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  25556. constructor: CurvePath,
  25557. add: function ( curve ) {
  25558. this.curves.push( curve );
  25559. },
  25560. closePath: function () {
  25561. // Add a line curve if start and end of lines are not connected
  25562. var startPoint = this.curves[ 0 ].getPoint( 0 );
  25563. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25564. if ( ! startPoint.equals( endPoint ) ) {
  25565. this.curves.push( new LineCurve( endPoint, startPoint ) );
  25566. }
  25567. },
  25568. // To get accurate point with reference to
  25569. // entire path distance at time t,
  25570. // following has to be done:
  25571. // 1. Length of each sub path have to be known
  25572. // 2. Locate and identify type of curve
  25573. // 3. Get t for the curve
  25574. // 4. Return curve.getPointAt(t')
  25575. getPoint: function ( t ) {
  25576. var d = t * this.getLength();
  25577. var curveLengths = this.getCurveLengths();
  25578. var i = 0;
  25579. // To think about boundaries points.
  25580. while ( i < curveLengths.length ) {
  25581. if ( curveLengths[ i ] >= d ) {
  25582. var diff = curveLengths[ i ] - d;
  25583. var curve = this.curves[ i ];
  25584. var segmentLength = curve.getLength();
  25585. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25586. return curve.getPointAt( u );
  25587. }
  25588. i ++;
  25589. }
  25590. return null;
  25591. // loop where sum != 0, sum > d , sum+1 <d
  25592. },
  25593. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25594. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25595. // getPoint() depends on getLength
  25596. getLength: function () {
  25597. var lens = this.getCurveLengths();
  25598. return lens[ lens.length - 1 ];
  25599. },
  25600. // cacheLengths must be recalculated.
  25601. updateArcLengths: function () {
  25602. this.needsUpdate = true;
  25603. this.cacheLengths = null;
  25604. this.getCurveLengths();
  25605. },
  25606. // Compute lengths and cache them
  25607. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25608. getCurveLengths: function () {
  25609. // We use cache values if curves and cache array are same length
  25610. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25611. return this.cacheLengths;
  25612. }
  25613. // Get length of sub-curve
  25614. // Push sums into cached array
  25615. var lengths = [], sums = 0;
  25616. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  25617. sums += this.curves[ i ].getLength();
  25618. lengths.push( sums );
  25619. }
  25620. this.cacheLengths = lengths;
  25621. return lengths;
  25622. },
  25623. getSpacedPoints: function ( divisions ) {
  25624. if ( divisions === undefined ) divisions = 40;
  25625. var points = [];
  25626. for ( var i = 0; i <= divisions; i ++ ) {
  25627. points.push( this.getPoint( i / divisions ) );
  25628. }
  25629. if ( this.autoClose ) {
  25630. points.push( points[ 0 ] );
  25631. }
  25632. return points;
  25633. },
  25634. getPoints: function ( divisions ) {
  25635. divisions = divisions || 12;
  25636. var points = [], last;
  25637. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25638. var curve = curves[ i ];
  25639. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  25640. : (curve && curve.isLineCurve) ? 1
  25641. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  25642. : divisions;
  25643. var pts = curve.getPoints( resolution );
  25644. for ( var j = 0; j < pts.length; j++ ) {
  25645. var point = pts[ j ];
  25646. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25647. points.push( point );
  25648. last = point;
  25649. }
  25650. }
  25651. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25652. points.push( points[ 0 ] );
  25653. }
  25654. return points;
  25655. },
  25656. /**************************************************************
  25657. * Create Geometries Helpers
  25658. **************************************************************/
  25659. /// Generate geometry from path points (for Line or Points objects)
  25660. createPointsGeometry: function ( divisions ) {
  25661. var pts = this.getPoints( divisions );
  25662. return this.createGeometry( pts );
  25663. },
  25664. // Generate geometry from equidistant sampling along the path
  25665. createSpacedPointsGeometry: function ( divisions ) {
  25666. var pts = this.getSpacedPoints( divisions );
  25667. return this.createGeometry( pts );
  25668. },
  25669. createGeometry: function ( points ) {
  25670. var geometry = new Geometry();
  25671. for ( var i = 0, l = points.length; i < l; i ++ ) {
  25672. var point = points[ i ];
  25673. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  25674. }
  25675. return geometry;
  25676. }
  25677. } );
  25678. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25679. Curve.call( this );
  25680. this.aX = aX;
  25681. this.aY = aY;
  25682. this.xRadius = xRadius;
  25683. this.yRadius = yRadius;
  25684. this.aStartAngle = aStartAngle;
  25685. this.aEndAngle = aEndAngle;
  25686. this.aClockwise = aClockwise;
  25687. this.aRotation = aRotation || 0;
  25688. }
  25689. EllipseCurve.prototype = Object.create( Curve.prototype );
  25690. EllipseCurve.prototype.constructor = EllipseCurve;
  25691. EllipseCurve.prototype.isEllipseCurve = true;
  25692. EllipseCurve.prototype.getPoint = function ( t ) {
  25693. var twoPi = Math.PI * 2;
  25694. var deltaAngle = this.aEndAngle - this.aStartAngle;
  25695. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  25696. // ensures that deltaAngle is 0 .. 2 PI
  25697. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  25698. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  25699. if ( deltaAngle < Number.EPSILON ) {
  25700. if ( samePoints ) {
  25701. deltaAngle = 0;
  25702. } else {
  25703. deltaAngle = twoPi;
  25704. }
  25705. }
  25706. if ( this.aClockwise === true && ! samePoints ) {
  25707. if ( deltaAngle === twoPi ) {
  25708. deltaAngle = - twoPi;
  25709. } else {
  25710. deltaAngle = deltaAngle - twoPi;
  25711. }
  25712. }
  25713. var angle = this.aStartAngle + t * deltaAngle;
  25714. var x = this.aX + this.xRadius * Math.cos( angle );
  25715. var y = this.aY + this.yRadius * Math.sin( angle );
  25716. if ( this.aRotation !== 0 ) {
  25717. var cos = Math.cos( this.aRotation );
  25718. var sin = Math.sin( this.aRotation );
  25719. var tx = x - this.aX;
  25720. var ty = y - this.aY;
  25721. // Rotate the point about the center of the ellipse.
  25722. x = tx * cos - ty * sin + this.aX;
  25723. y = tx * sin + ty * cos + this.aY;
  25724. }
  25725. return new Vector2( x, y );
  25726. };
  25727. function SplineCurve( points /* array of Vector2 */ ) {
  25728. Curve.call( this );
  25729. this.points = ( points === undefined ) ? [] : points;
  25730. }
  25731. SplineCurve.prototype = Object.create( Curve.prototype );
  25732. SplineCurve.prototype.constructor = SplineCurve;
  25733. SplineCurve.prototype.isSplineCurve = true;
  25734. SplineCurve.prototype.getPoint = function ( t ) {
  25735. var points = this.points;
  25736. var point = ( points.length - 1 ) * t;
  25737. var intPoint = Math.floor( point );
  25738. var weight = point - intPoint;
  25739. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  25740. var point1 = points[ intPoint ];
  25741. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  25742. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  25743. return new Vector2(
  25744. CatmullRom( weight, point0.x, point1.x, point2.x, point3.x ),
  25745. CatmullRom( weight, point0.y, point1.y, point2.y, point3.y )
  25746. );
  25747. };
  25748. function CubicBezierCurve( v0, v1, v2, v3 ) {
  25749. Curve.call( this );
  25750. this.v0 = v0;
  25751. this.v1 = v1;
  25752. this.v2 = v2;
  25753. this.v3 = v3;
  25754. }
  25755. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  25756. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  25757. CubicBezierCurve.prototype.getPoint = function ( t ) {
  25758. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  25759. return new Vector2(
  25760. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  25761. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  25762. );
  25763. };
  25764. function QuadraticBezierCurve( v0, v1, v2 ) {
  25765. Curve.call( this );
  25766. this.v0 = v0;
  25767. this.v1 = v1;
  25768. this.v2 = v2;
  25769. }
  25770. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  25771. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  25772. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  25773. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  25774. return new Vector2(
  25775. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  25776. QuadraticBezier( t, v0.y, v1.y, v2.y )
  25777. );
  25778. };
  25779. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  25780. fromPoints: function ( vectors ) {
  25781. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  25782. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  25783. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  25784. }
  25785. },
  25786. moveTo: function ( x, y ) {
  25787. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25788. },
  25789. lineTo: function ( x, y ) {
  25790. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25791. this.curves.push( curve );
  25792. this.currentPoint.set( x, y );
  25793. },
  25794. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25795. var curve = new QuadraticBezierCurve(
  25796. this.currentPoint.clone(),
  25797. new Vector2( aCPx, aCPy ),
  25798. new Vector2( aX, aY )
  25799. );
  25800. this.curves.push( curve );
  25801. this.currentPoint.set( aX, aY );
  25802. },
  25803. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25804. var curve = new CubicBezierCurve(
  25805. this.currentPoint.clone(),
  25806. new Vector2( aCP1x, aCP1y ),
  25807. new Vector2( aCP2x, aCP2y ),
  25808. new Vector2( aX, aY )
  25809. );
  25810. this.curves.push( curve );
  25811. this.currentPoint.set( aX, aY );
  25812. },
  25813. splineThru: function ( pts /*Array of Vector*/ ) {
  25814. var npts = [ this.currentPoint.clone() ].concat( pts );
  25815. var curve = new SplineCurve( npts );
  25816. this.curves.push( curve );
  25817. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25818. },
  25819. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25820. var x0 = this.currentPoint.x;
  25821. var y0 = this.currentPoint.y;
  25822. this.absarc( aX + x0, aY + y0, aRadius,
  25823. aStartAngle, aEndAngle, aClockwise );
  25824. },
  25825. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25826. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25827. },
  25828. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25829. var x0 = this.currentPoint.x;
  25830. var y0 = this.currentPoint.y;
  25831. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25832. },
  25833. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25834. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25835. if ( this.curves.length > 0 ) {
  25836. // if a previous curve is present, attempt to join
  25837. var firstPoint = curve.getPoint( 0 );
  25838. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25839. this.lineTo( firstPoint.x, firstPoint.y );
  25840. }
  25841. }
  25842. this.curves.push( curve );
  25843. var lastPoint = curve.getPoint( 1 );
  25844. this.currentPoint.copy( lastPoint );
  25845. }
  25846. } );
  25847. /**
  25848. * @author zz85 / http://www.lab4games.net/zz85/blog
  25849. * Creates free form 2d path using series of points, lines or curves.
  25850. **/
  25851. function Path( points ) {
  25852. CurvePath.call( this );
  25853. this.currentPoint = new Vector2();
  25854. if ( points ) {
  25855. this.fromPoints( points );
  25856. }
  25857. }
  25858. Path.prototype = PathPrototype;
  25859. PathPrototype.constructor = Path;
  25860. /**
  25861. * @author zz85 / http://www.lab4games.net/zz85/blog
  25862. * Defines a 2d shape plane using paths.
  25863. **/
  25864. // STEP 1 Create a path.
  25865. // STEP 2 Turn path into shape.
  25866. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  25867. // STEP 3a - Extract points from each shape, turn to vertices
  25868. // STEP 3b - Triangulate each shape, add faces.
  25869. function Shape() {
  25870. Path.apply( this, arguments );
  25871. this.holes = [];
  25872. }
  25873. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  25874. constructor: Shape,
  25875. getPointsHoles: function ( divisions ) {
  25876. var holesPts = [];
  25877. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  25878. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25879. }
  25880. return holesPts;
  25881. },
  25882. // Get points of shape and holes (keypoints based on segments parameter)
  25883. extractAllPoints: function ( divisions ) {
  25884. return {
  25885. shape: this.getPoints( divisions ),
  25886. holes: this.getPointsHoles( divisions )
  25887. };
  25888. },
  25889. extractPoints: function ( divisions ) {
  25890. return this.extractAllPoints( divisions );
  25891. }
  25892. } );
  25893. /**
  25894. * @author zz85 / http://www.lab4games.net/zz85/blog
  25895. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25896. **/
  25897. function ShapePath() {
  25898. this.subPaths = [];
  25899. this.currentPath = null;
  25900. }
  25901. Object.assign( ShapePath.prototype, {
  25902. moveTo: function ( x, y ) {
  25903. this.currentPath = new Path();
  25904. this.subPaths.push( this.currentPath );
  25905. this.currentPath.moveTo( x, y );
  25906. },
  25907. lineTo: function ( x, y ) {
  25908. this.currentPath.lineTo( x, y );
  25909. },
  25910. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25911. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25912. },
  25913. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25914. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25915. },
  25916. splineThru: function ( pts ) {
  25917. this.currentPath.splineThru( pts );
  25918. },
  25919. toShapes: function ( isCCW, noHoles ) {
  25920. function toShapesNoHoles( inSubpaths ) {
  25921. var shapes = [];
  25922. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25923. var tmpPath = inSubpaths[ i ];
  25924. var tmpShape = new Shape();
  25925. tmpShape.curves = tmpPath.curves;
  25926. shapes.push( tmpShape );
  25927. }
  25928. return shapes;
  25929. }
  25930. function isPointInsidePolygon( inPt, inPolygon ) {
  25931. var polyLen = inPolygon.length;
  25932. // inPt on polygon contour => immediate success or
  25933. // toggling of inside/outside at every single! intersection point of an edge
  25934. // with the horizontal line through inPt, left of inPt
  25935. // not counting lowerY endpoints of edges and whole edges on that line
  25936. var inside = false;
  25937. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25938. var edgeLowPt = inPolygon[ p ];
  25939. var edgeHighPt = inPolygon[ q ];
  25940. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25941. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25942. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25943. // not parallel
  25944. if ( edgeDy < 0 ) {
  25945. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25946. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25947. }
  25948. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25949. if ( inPt.y === edgeLowPt.y ) {
  25950. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25951. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25952. } else {
  25953. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25954. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25955. if ( perpEdge < 0 ) continue;
  25956. inside = ! inside; // true intersection left of inPt
  25957. }
  25958. } else {
  25959. // parallel or collinear
  25960. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25961. // edge lies on the same horizontal line as inPt
  25962. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25963. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25964. // continue;
  25965. }
  25966. }
  25967. return inside;
  25968. }
  25969. var isClockWise = ShapeUtils.isClockWise;
  25970. var subPaths = this.subPaths;
  25971. if ( subPaths.length === 0 ) return [];
  25972. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25973. var solid, tmpPath, tmpShape, shapes = [];
  25974. if ( subPaths.length === 1 ) {
  25975. tmpPath = subPaths[ 0 ];
  25976. tmpShape = new Shape();
  25977. tmpShape.curves = tmpPath.curves;
  25978. shapes.push( tmpShape );
  25979. return shapes;
  25980. }
  25981. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25982. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25983. // console.log("Holes first", holesFirst);
  25984. var betterShapeHoles = [];
  25985. var newShapes = [];
  25986. var newShapeHoles = [];
  25987. var mainIdx = 0;
  25988. var tmpPoints;
  25989. newShapes[ mainIdx ] = undefined;
  25990. newShapeHoles[ mainIdx ] = [];
  25991. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  25992. tmpPath = subPaths[ i ];
  25993. tmpPoints = tmpPath.getPoints();
  25994. solid = isClockWise( tmpPoints );
  25995. solid = isCCW ? ! solid : solid;
  25996. if ( solid ) {
  25997. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25998. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25999. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  26000. if ( holesFirst ) mainIdx ++;
  26001. newShapeHoles[ mainIdx ] = [];
  26002. //console.log('cw', i);
  26003. } else {
  26004. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  26005. //console.log('ccw', i);
  26006. }
  26007. }
  26008. // only Holes? -> probably all Shapes with wrong orientation
  26009. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  26010. if ( newShapes.length > 1 ) {
  26011. var ambiguous = false;
  26012. var toChange = [];
  26013. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  26014. betterShapeHoles[ sIdx ] = [];
  26015. }
  26016. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  26017. var sho = newShapeHoles[ sIdx ];
  26018. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  26019. var ho = sho[ hIdx ];
  26020. var hole_unassigned = true;
  26021. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  26022. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  26023. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  26024. if ( hole_unassigned ) {
  26025. hole_unassigned = false;
  26026. betterShapeHoles[ s2Idx ].push( ho );
  26027. } else {
  26028. ambiguous = true;
  26029. }
  26030. }
  26031. }
  26032. if ( hole_unassigned ) {
  26033. betterShapeHoles[ sIdx ].push( ho );
  26034. }
  26035. }
  26036. }
  26037. // console.log("ambiguous: ", ambiguous);
  26038. if ( toChange.length > 0 ) {
  26039. // console.log("to change: ", toChange);
  26040. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  26041. }
  26042. }
  26043. var tmpHoles;
  26044. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  26045. tmpShape = newShapes[ i ].s;
  26046. shapes.push( tmpShape );
  26047. tmpHoles = newShapeHoles[ i ];
  26048. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  26049. tmpShape.holes.push( tmpHoles[ j ].h );
  26050. }
  26051. }
  26052. //console.log("shape", shapes);
  26053. return shapes;
  26054. }
  26055. } );
  26056. /**
  26057. * @author zz85 / http://www.lab4games.net/zz85/blog
  26058. * @author mrdoob / http://mrdoob.com/
  26059. */
  26060. function Font( data ) {
  26061. this.data = data;
  26062. }
  26063. Object.assign( Font.prototype, {
  26064. isFont: true,
  26065. generateShapes: function ( text, size, divisions ) {
  26066. function createPaths( text ) {
  26067. var chars = String( text ).split( '' );
  26068. var scale = size / data.resolution;
  26069. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  26070. var offsetX = 0, offsetY = 0;
  26071. var paths = [];
  26072. for ( var i = 0; i < chars.length; i ++ ) {
  26073. var char = chars[ i ];
  26074. if ( char === '\n' ) {
  26075. offsetX = 0;
  26076. offsetY -= line_height;
  26077. } else {
  26078. var ret = createPath( char, scale, offsetX, offsetY );
  26079. offsetX += ret.offsetX;
  26080. paths.push( ret.path );
  26081. }
  26082. }
  26083. return paths;
  26084. }
  26085. function createPath( c, scale, offsetX, offsetY ) {
  26086. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  26087. if ( ! glyph ) return;
  26088. var path = new ShapePath();
  26089. var pts = [];
  26090. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  26091. if ( glyph.o ) {
  26092. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  26093. for ( var i = 0, l = outline.length; i < l; ) {
  26094. var action = outline[ i ++ ];
  26095. switch ( action ) {
  26096. case 'm': // moveTo
  26097. x = outline[ i ++ ] * scale + offsetX;
  26098. y = outline[ i ++ ] * scale + offsetY;
  26099. path.moveTo( x, y );
  26100. break;
  26101. case 'l': // lineTo
  26102. x = outline[ i ++ ] * scale + offsetX;
  26103. y = outline[ i ++ ] * scale + offsetY;
  26104. path.lineTo( x, y );
  26105. break;
  26106. case 'q': // quadraticCurveTo
  26107. cpx = outline[ i ++ ] * scale + offsetX;
  26108. cpy = outline[ i ++ ] * scale + offsetY;
  26109. cpx1 = outline[ i ++ ] * scale + offsetX;
  26110. cpy1 = outline[ i ++ ] * scale + offsetY;
  26111. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  26112. laste = pts[ pts.length - 1 ];
  26113. if ( laste ) {
  26114. cpx0 = laste.x;
  26115. cpy0 = laste.y;
  26116. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  26117. var t = i2 / divisions;
  26118. QuadraticBezier( t, cpx0, cpx1, cpx );
  26119. QuadraticBezier( t, cpy0, cpy1, cpy );
  26120. }
  26121. }
  26122. break;
  26123. case 'b': // bezierCurveTo
  26124. cpx = outline[ i ++ ] * scale + offsetX;
  26125. cpy = outline[ i ++ ] * scale + offsetY;
  26126. cpx1 = outline[ i ++ ] * scale + offsetX;
  26127. cpy1 = outline[ i ++ ] * scale + offsetY;
  26128. cpx2 = outline[ i ++ ] * scale + offsetX;
  26129. cpy2 = outline[ i ++ ] * scale + offsetY;
  26130. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  26131. laste = pts[ pts.length - 1 ];
  26132. if ( laste ) {
  26133. cpx0 = laste.x;
  26134. cpy0 = laste.y;
  26135. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  26136. var t = i2 / divisions;
  26137. CubicBezier( t, cpx0, cpx1, cpx2, cpx );
  26138. CubicBezier( t, cpy0, cpy1, cpy2, cpy );
  26139. }
  26140. }
  26141. break;
  26142. }
  26143. }
  26144. }
  26145. return { offsetX: glyph.ha * scale, path: path };
  26146. }
  26147. //
  26148. if ( size === undefined ) size = 100;
  26149. if ( divisions === undefined ) divisions = 4;
  26150. var data = this.data;
  26151. var paths = createPaths( text );
  26152. var shapes = [];
  26153. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  26154. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  26155. }
  26156. return shapes;
  26157. }
  26158. } );
  26159. /**
  26160. * @author mrdoob / http://mrdoob.com/
  26161. */
  26162. function FontLoader( manager ) {
  26163. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26164. }
  26165. Object.assign( FontLoader.prototype, {
  26166. load: function ( url, onLoad, onProgress, onError ) {
  26167. var scope = this;
  26168. var loader = new FileLoader( this.manager );
  26169. loader.load( url, function ( text ) {
  26170. var json;
  26171. try {
  26172. json = JSON.parse( text );
  26173. } catch ( e ) {
  26174. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  26175. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  26176. }
  26177. var font = scope.parse( json );
  26178. if ( onLoad ) onLoad( font );
  26179. }, onProgress, onError );
  26180. },
  26181. parse: function ( json ) {
  26182. return new Font( json );
  26183. }
  26184. } );
  26185. var context;
  26186. var AudioContext = {
  26187. getContext: function () {
  26188. if ( context === undefined ) {
  26189. context = new ( window.AudioContext || window.webkitAudioContext )();
  26190. }
  26191. return context;
  26192. },
  26193. setContext: function ( value ) {
  26194. context = value;
  26195. }
  26196. };
  26197. /**
  26198. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  26199. */
  26200. function AudioLoader( manager ) {
  26201. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26202. }
  26203. Object.assign( AudioLoader.prototype, {
  26204. load: function ( url, onLoad, onProgress, onError ) {
  26205. var loader = new FileLoader( this.manager );
  26206. loader.setResponseType( 'arraybuffer' );
  26207. loader.load( url, function ( buffer ) {
  26208. var context = AudioContext.getContext();
  26209. context.decodeAudioData( buffer, function ( audioBuffer ) {
  26210. onLoad( audioBuffer );
  26211. } );
  26212. }, onProgress, onError );
  26213. }
  26214. } );
  26215. /**
  26216. * @author mrdoob / http://mrdoob.com/
  26217. */
  26218. function StereoCamera() {
  26219. this.type = 'StereoCamera';
  26220. this.aspect = 1;
  26221. this.eyeSep = 0.064;
  26222. this.cameraL = new PerspectiveCamera();
  26223. this.cameraL.layers.enable( 1 );
  26224. this.cameraL.matrixAutoUpdate = false;
  26225. this.cameraR = new PerspectiveCamera();
  26226. this.cameraR.layers.enable( 2 );
  26227. this.cameraR.matrixAutoUpdate = false;
  26228. }
  26229. Object.assign( StereoCamera.prototype, {
  26230. update: ( function () {
  26231. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  26232. var eyeRight = new Matrix4();
  26233. var eyeLeft = new Matrix4();
  26234. return function update( camera ) {
  26235. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  26236. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  26237. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  26238. if ( needsUpdate ) {
  26239. instance = this;
  26240. focus = camera.focus;
  26241. fov = camera.fov;
  26242. aspect = camera.aspect * this.aspect;
  26243. near = camera.near;
  26244. far = camera.far;
  26245. zoom = camera.zoom;
  26246. // Off-axis stereoscopic effect based on
  26247. // http://paulbourke.net/stereographics/stereorender/
  26248. var projectionMatrix = camera.projectionMatrix.clone();
  26249. eyeSep = this.eyeSep / 2;
  26250. var eyeSepOnProjection = eyeSep * near / focus;
  26251. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  26252. var xmin, xmax;
  26253. // translate xOffset
  26254. eyeLeft.elements[ 12 ] = - eyeSep;
  26255. eyeRight.elements[ 12 ] = eyeSep;
  26256. // for left eye
  26257. xmin = - ymax * aspect + eyeSepOnProjection;
  26258. xmax = ymax * aspect + eyeSepOnProjection;
  26259. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  26260. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26261. this.cameraL.projectionMatrix.copy( projectionMatrix );
  26262. // for right eye
  26263. xmin = - ymax * aspect - eyeSepOnProjection;
  26264. xmax = ymax * aspect - eyeSepOnProjection;
  26265. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  26266. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26267. this.cameraR.projectionMatrix.copy( projectionMatrix );
  26268. }
  26269. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  26270. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  26271. };
  26272. } )()
  26273. } );
  26274. /**
  26275. * Camera for rendering cube maps
  26276. * - renders scene into axis-aligned cube
  26277. *
  26278. * @author alteredq / http://alteredqualia.com/
  26279. */
  26280. function CubeCamera( near, far, cubeResolution ) {
  26281. Object3D.call( this );
  26282. this.type = 'CubeCamera';
  26283. var fov = 90, aspect = 1;
  26284. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  26285. cameraPX.up.set( 0, - 1, 0 );
  26286. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  26287. this.add( cameraPX );
  26288. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  26289. cameraNX.up.set( 0, - 1, 0 );
  26290. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  26291. this.add( cameraNX );
  26292. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  26293. cameraPY.up.set( 0, 0, 1 );
  26294. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  26295. this.add( cameraPY );
  26296. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  26297. cameraNY.up.set( 0, 0, - 1 );
  26298. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  26299. this.add( cameraNY );
  26300. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  26301. cameraPZ.up.set( 0, - 1, 0 );
  26302. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  26303. this.add( cameraPZ );
  26304. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  26305. cameraNZ.up.set( 0, - 1, 0 );
  26306. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  26307. this.add( cameraNZ );
  26308. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  26309. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  26310. this.renderTarget.texture.name = "CubeCamera";
  26311. this.update = function ( renderer, scene ) {
  26312. if ( this.parent === null ) this.updateMatrixWorld();
  26313. var renderTarget = this.renderTarget;
  26314. var generateMipmaps = renderTarget.texture.generateMipmaps;
  26315. renderTarget.texture.generateMipmaps = false;
  26316. renderTarget.activeCubeFace = 0;
  26317. renderer.render( scene, cameraPX, renderTarget );
  26318. renderTarget.activeCubeFace = 1;
  26319. renderer.render( scene, cameraNX, renderTarget );
  26320. renderTarget.activeCubeFace = 2;
  26321. renderer.render( scene, cameraPY, renderTarget );
  26322. renderTarget.activeCubeFace = 3;
  26323. renderer.render( scene, cameraNY, renderTarget );
  26324. renderTarget.activeCubeFace = 4;
  26325. renderer.render( scene, cameraPZ, renderTarget );
  26326. renderTarget.texture.generateMipmaps = generateMipmaps;
  26327. renderTarget.activeCubeFace = 5;
  26328. renderer.render( scene, cameraNZ, renderTarget );
  26329. renderer.setRenderTarget( null );
  26330. };
  26331. this.clear = function ( renderer, color, depth, stencil ) {
  26332. var renderTarget = this.renderTarget;
  26333. for ( var i = 0; i < 6; i ++ ) {
  26334. renderTarget.activeCubeFace = i;
  26335. renderer.setRenderTarget( renderTarget );
  26336. renderer.clear( color, depth, stencil );
  26337. }
  26338. renderer.setRenderTarget( null );
  26339. };
  26340. }
  26341. CubeCamera.prototype = Object.create( Object3D.prototype );
  26342. CubeCamera.prototype.constructor = CubeCamera;
  26343. /**
  26344. * @author mrdoob / http://mrdoob.com/
  26345. */
  26346. function AudioListener() {
  26347. Object3D.call( this );
  26348. this.type = 'AudioListener';
  26349. this.context = AudioContext.getContext();
  26350. this.gain = this.context.createGain();
  26351. this.gain.connect( this.context.destination );
  26352. this.filter = null;
  26353. }
  26354. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  26355. constructor: AudioListener,
  26356. getInput: function () {
  26357. return this.gain;
  26358. },
  26359. removeFilter: function ( ) {
  26360. if ( this.filter !== null ) {
  26361. this.gain.disconnect( this.filter );
  26362. this.filter.disconnect( this.context.destination );
  26363. this.gain.connect( this.context.destination );
  26364. this.filter = null;
  26365. }
  26366. },
  26367. getFilter: function () {
  26368. return this.filter;
  26369. },
  26370. setFilter: function ( value ) {
  26371. if ( this.filter !== null ) {
  26372. this.gain.disconnect( this.filter );
  26373. this.filter.disconnect( this.context.destination );
  26374. } else {
  26375. this.gain.disconnect( this.context.destination );
  26376. }
  26377. this.filter = value;
  26378. this.gain.connect( this.filter );
  26379. this.filter.connect( this.context.destination );
  26380. },
  26381. getMasterVolume: function () {
  26382. return this.gain.gain.value;
  26383. },
  26384. setMasterVolume: function ( value ) {
  26385. this.gain.gain.value = value;
  26386. },
  26387. updateMatrixWorld: ( function () {
  26388. var position = new Vector3();
  26389. var quaternion = new Quaternion();
  26390. var scale = new Vector3();
  26391. var orientation = new Vector3();
  26392. return function updateMatrixWorld( force ) {
  26393. Object3D.prototype.updateMatrixWorld.call( this, force );
  26394. var listener = this.context.listener;
  26395. var up = this.up;
  26396. this.matrixWorld.decompose( position, quaternion, scale );
  26397. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  26398. if ( listener.positionX ) {
  26399. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  26400. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  26401. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  26402. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  26403. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  26404. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  26405. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  26406. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  26407. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  26408. } else {
  26409. listener.setPosition( position.x, position.y, position.z );
  26410. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  26411. }
  26412. };
  26413. } )()
  26414. } );
  26415. /**
  26416. * @author mrdoob / http://mrdoob.com/
  26417. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  26418. */
  26419. function Audio( listener ) {
  26420. Object3D.call( this );
  26421. this.type = 'Audio';
  26422. this.context = listener.context;
  26423. this.gain = this.context.createGain();
  26424. this.gain.connect( listener.getInput() );
  26425. this.autoplay = false;
  26426. this.buffer = null;
  26427. this.loop = false;
  26428. this.startTime = 0;
  26429. this.playbackRate = 1;
  26430. this.isPlaying = false;
  26431. this.hasPlaybackControl = true;
  26432. this.sourceType = 'empty';
  26433. this.filters = [];
  26434. }
  26435. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  26436. constructor: Audio,
  26437. getOutput: function () {
  26438. return this.gain;
  26439. },
  26440. setNodeSource: function ( audioNode ) {
  26441. this.hasPlaybackControl = false;
  26442. this.sourceType = 'audioNode';
  26443. this.source = audioNode;
  26444. this.connect();
  26445. return this;
  26446. },
  26447. setBuffer: function ( audioBuffer ) {
  26448. this.buffer = audioBuffer;
  26449. this.sourceType = 'buffer';
  26450. if ( this.autoplay ) this.play();
  26451. return this;
  26452. },
  26453. play: function () {
  26454. if ( this.isPlaying === true ) {
  26455. console.warn( 'THREE.Audio: Audio is already playing.' );
  26456. return;
  26457. }
  26458. if ( this.hasPlaybackControl === false ) {
  26459. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26460. return;
  26461. }
  26462. var source = this.context.createBufferSource();
  26463. source.buffer = this.buffer;
  26464. source.loop = this.loop;
  26465. source.onended = this.onEnded.bind( this );
  26466. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  26467. source.start( 0, this.startTime );
  26468. this.isPlaying = true;
  26469. this.source = source;
  26470. return this.connect();
  26471. },
  26472. pause: function () {
  26473. if ( this.hasPlaybackControl === false ) {
  26474. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26475. return;
  26476. }
  26477. this.source.stop();
  26478. this.startTime = this.context.currentTime;
  26479. this.isPlaying = false;
  26480. return this;
  26481. },
  26482. stop: function () {
  26483. if ( this.hasPlaybackControl === false ) {
  26484. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26485. return;
  26486. }
  26487. this.source.stop();
  26488. this.startTime = 0;
  26489. this.isPlaying = false;
  26490. return this;
  26491. },
  26492. connect: function () {
  26493. if ( this.filters.length > 0 ) {
  26494. this.source.connect( this.filters[ 0 ] );
  26495. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  26496. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26497. }
  26498. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26499. } else {
  26500. this.source.connect( this.getOutput() );
  26501. }
  26502. return this;
  26503. },
  26504. disconnect: function () {
  26505. if ( this.filters.length > 0 ) {
  26506. this.source.disconnect( this.filters[ 0 ] );
  26507. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  26508. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26509. }
  26510. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26511. } else {
  26512. this.source.disconnect( this.getOutput() );
  26513. }
  26514. return this;
  26515. },
  26516. getFilters: function () {
  26517. return this.filters;
  26518. },
  26519. setFilters: function ( value ) {
  26520. if ( ! value ) value = [];
  26521. if ( this.isPlaying === true ) {
  26522. this.disconnect();
  26523. this.filters = value;
  26524. this.connect();
  26525. } else {
  26526. this.filters = value;
  26527. }
  26528. return this;
  26529. },
  26530. getFilter: function () {
  26531. return this.getFilters()[ 0 ];
  26532. },
  26533. setFilter: function ( filter ) {
  26534. return this.setFilters( filter ? [ filter ] : [] );
  26535. },
  26536. setPlaybackRate: function ( value ) {
  26537. if ( this.hasPlaybackControl === false ) {
  26538. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26539. return;
  26540. }
  26541. this.playbackRate = value;
  26542. if ( this.isPlaying === true ) {
  26543. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  26544. }
  26545. return this;
  26546. },
  26547. getPlaybackRate: function () {
  26548. return this.playbackRate;
  26549. },
  26550. onEnded: function () {
  26551. this.isPlaying = false;
  26552. },
  26553. getLoop: function () {
  26554. if ( this.hasPlaybackControl === false ) {
  26555. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26556. return false;
  26557. }
  26558. return this.loop;
  26559. },
  26560. setLoop: function ( value ) {
  26561. if ( this.hasPlaybackControl === false ) {
  26562. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26563. return;
  26564. }
  26565. this.loop = value;
  26566. if ( this.isPlaying === true ) {
  26567. this.source.loop = this.loop;
  26568. }
  26569. return this;
  26570. },
  26571. getVolume: function () {
  26572. return this.gain.gain.value;
  26573. },
  26574. setVolume: function ( value ) {
  26575. this.gain.gain.value = value;
  26576. return this;
  26577. }
  26578. } );
  26579. /**
  26580. * @author mrdoob / http://mrdoob.com/
  26581. */
  26582. function PositionalAudio( listener ) {
  26583. Audio.call( this, listener );
  26584. this.panner = this.context.createPanner();
  26585. this.panner.connect( this.gain );
  26586. }
  26587. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  26588. constructor: PositionalAudio,
  26589. getOutput: function () {
  26590. return this.panner;
  26591. },
  26592. getRefDistance: function () {
  26593. return this.panner.refDistance;
  26594. },
  26595. setRefDistance: function ( value ) {
  26596. this.panner.refDistance = value;
  26597. },
  26598. getRolloffFactor: function () {
  26599. return this.panner.rolloffFactor;
  26600. },
  26601. setRolloffFactor: function ( value ) {
  26602. this.panner.rolloffFactor = value;
  26603. },
  26604. getDistanceModel: function () {
  26605. return this.panner.distanceModel;
  26606. },
  26607. setDistanceModel: function ( value ) {
  26608. this.panner.distanceModel = value;
  26609. },
  26610. getMaxDistance: function () {
  26611. return this.panner.maxDistance;
  26612. },
  26613. setMaxDistance: function ( value ) {
  26614. this.panner.maxDistance = value;
  26615. },
  26616. updateMatrixWorld: ( function () {
  26617. var position = new Vector3();
  26618. return function updateMatrixWorld( force ) {
  26619. Object3D.prototype.updateMatrixWorld.call( this, force );
  26620. position.setFromMatrixPosition( this.matrixWorld );
  26621. this.panner.setPosition( position.x, position.y, position.z );
  26622. };
  26623. } )()
  26624. } );
  26625. /**
  26626. * @author mrdoob / http://mrdoob.com/
  26627. */
  26628. function AudioAnalyser( audio, fftSize ) {
  26629. this.analyser = audio.context.createAnalyser();
  26630. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  26631. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26632. audio.getOutput().connect( this.analyser );
  26633. }
  26634. Object.assign( AudioAnalyser.prototype, {
  26635. getFrequencyData: function () {
  26636. this.analyser.getByteFrequencyData( this.data );
  26637. return this.data;
  26638. },
  26639. getAverageFrequency: function () {
  26640. var value = 0, data = this.getFrequencyData();
  26641. for ( var i = 0; i < data.length; i ++ ) {
  26642. value += data[ i ];
  26643. }
  26644. return value / data.length;
  26645. }
  26646. } );
  26647. /**
  26648. *
  26649. * Buffered scene graph property that allows weighted accumulation.
  26650. *
  26651. *
  26652. * @author Ben Houston / http://clara.io/
  26653. * @author David Sarno / http://lighthaus.us/
  26654. * @author tschw
  26655. */
  26656. function PropertyMixer( binding, typeName, valueSize ) {
  26657. this.binding = binding;
  26658. this.valueSize = valueSize;
  26659. var bufferType = Float64Array,
  26660. mixFunction;
  26661. switch ( typeName ) {
  26662. case 'quaternion':
  26663. mixFunction = this._slerp;
  26664. break;
  26665. case 'string':
  26666. case 'bool':
  26667. bufferType = Array;
  26668. mixFunction = this._select;
  26669. break;
  26670. default:
  26671. mixFunction = this._lerp;
  26672. }
  26673. this.buffer = new bufferType( valueSize * 4 );
  26674. // layout: [ incoming | accu0 | accu1 | orig ]
  26675. //
  26676. // interpolators can use .buffer as their .result
  26677. // the data then goes to 'incoming'
  26678. //
  26679. // 'accu0' and 'accu1' are used frame-interleaved for
  26680. // the cumulative result and are compared to detect
  26681. // changes
  26682. //
  26683. // 'orig' stores the original state of the property
  26684. this._mixBufferRegion = mixFunction;
  26685. this.cumulativeWeight = 0;
  26686. this.useCount = 0;
  26687. this.referenceCount = 0;
  26688. }
  26689. Object.assign( PropertyMixer.prototype, {
  26690. // accumulate data in the 'incoming' region into 'accu<i>'
  26691. accumulate: function ( accuIndex, weight ) {
  26692. // note: happily accumulating nothing when weight = 0, the caller knows
  26693. // the weight and shouldn't have made the call in the first place
  26694. var buffer = this.buffer,
  26695. stride = this.valueSize,
  26696. offset = accuIndex * stride + stride,
  26697. currentWeight = this.cumulativeWeight;
  26698. if ( currentWeight === 0 ) {
  26699. // accuN := incoming * weight
  26700. for ( var i = 0; i !== stride; ++ i ) {
  26701. buffer[ offset + i ] = buffer[ i ];
  26702. }
  26703. currentWeight = weight;
  26704. } else {
  26705. // accuN := accuN + incoming * weight
  26706. currentWeight += weight;
  26707. var mix = weight / currentWeight;
  26708. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26709. }
  26710. this.cumulativeWeight = currentWeight;
  26711. },
  26712. // apply the state of 'accu<i>' to the binding when accus differ
  26713. apply: function ( accuIndex ) {
  26714. var stride = this.valueSize,
  26715. buffer = this.buffer,
  26716. offset = accuIndex * stride + stride,
  26717. weight = this.cumulativeWeight,
  26718. binding = this.binding;
  26719. this.cumulativeWeight = 0;
  26720. if ( weight < 1 ) {
  26721. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26722. var originalValueOffset = stride * 3;
  26723. this._mixBufferRegion(
  26724. buffer, offset, originalValueOffset, 1 - weight, stride );
  26725. }
  26726. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  26727. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26728. // value has changed -> update scene graph
  26729. binding.setValue( buffer, offset );
  26730. break;
  26731. }
  26732. }
  26733. },
  26734. // remember the state of the bound property and copy it to both accus
  26735. saveOriginalState: function () {
  26736. var binding = this.binding;
  26737. var buffer = this.buffer,
  26738. stride = this.valueSize,
  26739. originalValueOffset = stride * 3;
  26740. binding.getValue( buffer, originalValueOffset );
  26741. // accu[0..1] := orig -- initially detect changes against the original
  26742. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26743. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26744. }
  26745. this.cumulativeWeight = 0;
  26746. },
  26747. // apply the state previously taken via 'saveOriginalState' to the binding
  26748. restoreOriginalState: function () {
  26749. var originalValueOffset = this.valueSize * 3;
  26750. this.binding.setValue( this.buffer, originalValueOffset );
  26751. },
  26752. // mix functions
  26753. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26754. if ( t >= 0.5 ) {
  26755. for ( var i = 0; i !== stride; ++ i ) {
  26756. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26757. }
  26758. }
  26759. },
  26760. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  26761. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26762. },
  26763. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26764. var s = 1 - t;
  26765. for ( var i = 0; i !== stride; ++ i ) {
  26766. var j = dstOffset + i;
  26767. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26768. }
  26769. }
  26770. } );
  26771. /**
  26772. *
  26773. * A reference to a real property in the scene graph.
  26774. *
  26775. *
  26776. * @author Ben Houston / http://clara.io/
  26777. * @author David Sarno / http://lighthaus.us/
  26778. * @author tschw
  26779. */
  26780. function Composite( targetGroup, path, optionalParsedPath ) {
  26781. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26782. this._targetGroup = targetGroup;
  26783. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26784. }
  26785. Object.assign( Composite.prototype, {
  26786. getValue: function ( array, offset ) {
  26787. this.bind(); // bind all binding
  26788. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26789. binding = this._bindings[ firstValidIndex ];
  26790. // and only call .getValue on the first
  26791. if ( binding !== undefined ) binding.getValue( array, offset );
  26792. },
  26793. setValue: function ( array, offset ) {
  26794. var bindings = this._bindings;
  26795. for ( var i = this._targetGroup.nCachedObjects_,
  26796. n = bindings.length; i !== n; ++ i ) {
  26797. bindings[ i ].setValue( array, offset );
  26798. }
  26799. },
  26800. bind: function () {
  26801. var bindings = this._bindings;
  26802. for ( var i = this._targetGroup.nCachedObjects_,
  26803. n = bindings.length; i !== n; ++ i ) {
  26804. bindings[ i ].bind();
  26805. }
  26806. },
  26807. unbind: function () {
  26808. var bindings = this._bindings;
  26809. for ( var i = this._targetGroup.nCachedObjects_,
  26810. n = bindings.length; i !== n; ++ i ) {
  26811. bindings[ i ].unbind();
  26812. }
  26813. }
  26814. } );
  26815. function PropertyBinding( rootNode, path, parsedPath ) {
  26816. this.path = path;
  26817. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26818. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26819. this.rootNode = rootNode;
  26820. }
  26821. Object.assign( PropertyBinding, {
  26822. Composite: Composite,
  26823. create: function ( root, path, parsedPath ) {
  26824. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26825. return new PropertyBinding( root, path, parsedPath );
  26826. } else {
  26827. return new PropertyBinding.Composite( root, path, parsedPath );
  26828. }
  26829. },
  26830. /**
  26831. * Replaces spaces with underscores and removes unsupported characters from
  26832. * node names, to ensure compatibility with parseTrackName().
  26833. *
  26834. * @param {string} name Node name to be sanitized.
  26835. * @return {string}
  26836. */
  26837. sanitizeNodeName: function ( name ) {
  26838. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  26839. },
  26840. parseTrackName: function () {
  26841. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26842. // be matched to parse the rest of the track name.
  26843. var directoryRe = /((?:[\w-]+[\/:])*)/;
  26844. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26845. var nodeRe = /([\w-\.]+)?/;
  26846. // Object on target node, and accessor. Name may contain only word
  26847. // characters. Accessor may contain any character except closing bracket.
  26848. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  26849. // Property and accessor. May contain only word characters. Accessor may
  26850. // contain any non-bracket characters.
  26851. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  26852. var trackRe = new RegExp(''
  26853. + '^'
  26854. + directoryRe.source
  26855. + nodeRe.source
  26856. + objectRe.source
  26857. + propertyRe.source
  26858. + '$'
  26859. );
  26860. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26861. return function ( trackName ) {
  26862. var matches = trackRe.exec( trackName );
  26863. if ( ! matches ) {
  26864. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26865. }
  26866. var results = {
  26867. // directoryName: matches[ 1 ], // (tschw) currently unused
  26868. nodeName: matches[ 2 ],
  26869. objectName: matches[ 3 ],
  26870. objectIndex: matches[ 4 ],
  26871. propertyName: matches[ 5 ], // required
  26872. propertyIndex: matches[ 6 ]
  26873. };
  26874. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26875. if ( lastDot !== undefined && lastDot !== -1 ) {
  26876. var objectName = results.nodeName.substring( lastDot + 1 );
  26877. // Object names must be checked against a whitelist. Otherwise, there
  26878. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26879. // 'bar' could be the objectName, or part of a nodeName (which can
  26880. // include '.' characters).
  26881. if ( supportedObjectNames.indexOf( objectName ) !== -1 ) {
  26882. results.nodeName = results.nodeName.substring( 0, lastDot );
  26883. results.objectName = objectName;
  26884. }
  26885. }
  26886. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26887. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26888. }
  26889. return results;
  26890. };
  26891. }(),
  26892. findNode: function ( root, nodeName ) {
  26893. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26894. return root;
  26895. }
  26896. // search into skeleton bones.
  26897. if ( root.skeleton ) {
  26898. var searchSkeleton = function ( skeleton ) {
  26899. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  26900. var bone = skeleton.bones[ i ];
  26901. if ( bone.name === nodeName ) {
  26902. return bone;
  26903. }
  26904. }
  26905. return null;
  26906. };
  26907. var bone = searchSkeleton( root.skeleton );
  26908. if ( bone ) {
  26909. return bone;
  26910. }
  26911. }
  26912. // search into node subtree.
  26913. if ( root.children ) {
  26914. var searchNodeSubtree = function ( children ) {
  26915. for ( var i = 0; i < children.length; i ++ ) {
  26916. var childNode = children[ i ];
  26917. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26918. return childNode;
  26919. }
  26920. var result = searchNodeSubtree( childNode.children );
  26921. if ( result ) return result;
  26922. }
  26923. return null;
  26924. };
  26925. var subTreeNode = searchNodeSubtree( root.children );
  26926. if ( subTreeNode ) {
  26927. return subTreeNode;
  26928. }
  26929. }
  26930. return null;
  26931. }
  26932. } );
  26933. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26934. // these are used to "bind" a nonexistent property
  26935. _getValue_unavailable: function () {},
  26936. _setValue_unavailable: function () {},
  26937. BindingType: {
  26938. Direct: 0,
  26939. EntireArray: 1,
  26940. ArrayElement: 2,
  26941. HasFromToArray: 3
  26942. },
  26943. Versioning: {
  26944. None: 0,
  26945. NeedsUpdate: 1,
  26946. MatrixWorldNeedsUpdate: 2
  26947. },
  26948. GetterByBindingType: [
  26949. function getValue_direct( buffer, offset ) {
  26950. buffer[ offset ] = this.node[ this.propertyName ];
  26951. },
  26952. function getValue_array( buffer, offset ) {
  26953. var source = this.resolvedProperty;
  26954. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  26955. buffer[ offset ++ ] = source[ i ];
  26956. }
  26957. },
  26958. function getValue_arrayElement( buffer, offset ) {
  26959. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26960. },
  26961. function getValue_toArray( buffer, offset ) {
  26962. this.resolvedProperty.toArray( buffer, offset );
  26963. }
  26964. ],
  26965. SetterByBindingTypeAndVersioning: [
  26966. [
  26967. // Direct
  26968. function setValue_direct( buffer, offset ) {
  26969. this.node[ this.propertyName ] = buffer[ offset ];
  26970. },
  26971. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26972. this.node[ this.propertyName ] = buffer[ offset ];
  26973. this.targetObject.needsUpdate = true;
  26974. },
  26975. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26976. this.node[ this.propertyName ] = buffer[ offset ];
  26977. this.targetObject.matrixWorldNeedsUpdate = true;
  26978. }
  26979. ], [
  26980. // EntireArray
  26981. function setValue_array( buffer, offset ) {
  26982. var dest = this.resolvedProperty;
  26983. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26984. dest[ i ] = buffer[ offset ++ ];
  26985. }
  26986. },
  26987. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26988. var dest = this.resolvedProperty;
  26989. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26990. dest[ i ] = buffer[ offset ++ ];
  26991. }
  26992. this.targetObject.needsUpdate = true;
  26993. },
  26994. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26995. var dest = this.resolvedProperty;
  26996. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26997. dest[ i ] = buffer[ offset ++ ];
  26998. }
  26999. this.targetObject.matrixWorldNeedsUpdate = true;
  27000. }
  27001. ], [
  27002. // ArrayElement
  27003. function setValue_arrayElement( buffer, offset ) {
  27004. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27005. },
  27006. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27007. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27008. this.targetObject.needsUpdate = true;
  27009. },
  27010. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27011. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27012. this.targetObject.matrixWorldNeedsUpdate = true;
  27013. }
  27014. ], [
  27015. // HasToFromArray
  27016. function setValue_fromArray( buffer, offset ) {
  27017. this.resolvedProperty.fromArray( buffer, offset );
  27018. },
  27019. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27020. this.resolvedProperty.fromArray( buffer, offset );
  27021. this.targetObject.needsUpdate = true;
  27022. },
  27023. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27024. this.resolvedProperty.fromArray( buffer, offset );
  27025. this.targetObject.matrixWorldNeedsUpdate = true;
  27026. }
  27027. ]
  27028. ],
  27029. getValue: function getValue_unbound( targetArray, offset ) {
  27030. this.bind();
  27031. this.getValue( targetArray, offset );
  27032. // Note: This class uses a State pattern on a per-method basis:
  27033. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27034. // prototype version of these methods with one that represents
  27035. // the bound state. When the property is not found, the methods
  27036. // become no-ops.
  27037. },
  27038. setValue: function getValue_unbound( sourceArray, offset ) {
  27039. this.bind();
  27040. this.setValue( sourceArray, offset );
  27041. },
  27042. // create getter / setter pair for a property in the scene graph
  27043. bind: function () {
  27044. var targetObject = this.node,
  27045. parsedPath = this.parsedPath,
  27046. objectName = parsedPath.objectName,
  27047. propertyName = parsedPath.propertyName,
  27048. propertyIndex = parsedPath.propertyIndex;
  27049. if ( ! targetObject ) {
  27050. targetObject = PropertyBinding.findNode(
  27051. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27052. this.node = targetObject;
  27053. }
  27054. // set fail state so we can just 'return' on error
  27055. this.getValue = this._getValue_unavailable;
  27056. this.setValue = this._setValue_unavailable;
  27057. // ensure there is a value node
  27058. if ( ! targetObject ) {
  27059. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27060. return;
  27061. }
  27062. if ( objectName ) {
  27063. var objectIndex = parsedPath.objectIndex;
  27064. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27065. switch ( objectName ) {
  27066. case 'materials':
  27067. if ( ! targetObject.material ) {
  27068. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27069. return;
  27070. }
  27071. if ( ! targetObject.material.materials ) {
  27072. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27073. return;
  27074. }
  27075. targetObject = targetObject.material.materials;
  27076. break;
  27077. case 'bones':
  27078. if ( ! targetObject.skeleton ) {
  27079. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27080. return;
  27081. }
  27082. // potential future optimization: skip this if propertyIndex is already an integer
  27083. // and convert the integer string to a true integer.
  27084. targetObject = targetObject.skeleton.bones;
  27085. // support resolving morphTarget names into indices.
  27086. for ( var i = 0; i < targetObject.length; i ++ ) {
  27087. if ( targetObject[ i ].name === objectIndex ) {
  27088. objectIndex = i;
  27089. break;
  27090. }
  27091. }
  27092. break;
  27093. default:
  27094. if ( targetObject[ objectName ] === undefined ) {
  27095. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27096. return;
  27097. }
  27098. targetObject = targetObject[ objectName ];
  27099. }
  27100. if ( objectIndex !== undefined ) {
  27101. if ( targetObject[ objectIndex ] === undefined ) {
  27102. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27103. return;
  27104. }
  27105. targetObject = targetObject[ objectIndex ];
  27106. }
  27107. }
  27108. // resolve property
  27109. var nodeProperty = targetObject[ propertyName ];
  27110. if ( nodeProperty === undefined ) {
  27111. var nodeName = parsedPath.nodeName;
  27112. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27113. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27114. return;
  27115. }
  27116. // determine versioning scheme
  27117. var versioning = this.Versioning.None;
  27118. if ( targetObject.needsUpdate !== undefined ) { // material
  27119. versioning = this.Versioning.NeedsUpdate;
  27120. this.targetObject = targetObject;
  27121. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27122. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27123. this.targetObject = targetObject;
  27124. }
  27125. // determine how the property gets bound
  27126. var bindingType = this.BindingType.Direct;
  27127. if ( propertyIndex !== undefined ) {
  27128. // access a sub element of the property array (only primitives are supported right now)
  27129. if ( propertyName === "morphTargetInfluences" ) {
  27130. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27131. // support resolving morphTarget names into indices.
  27132. if ( ! targetObject.geometry ) {
  27133. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27134. return;
  27135. }
  27136. if ( targetObject.geometry.isBufferGeometry ) {
  27137. if ( ! targetObject.geometry.morphAttributes ) {
  27138. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27139. return;
  27140. }
  27141. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  27142. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  27143. propertyIndex = i;
  27144. break;
  27145. }
  27146. }
  27147. } else {
  27148. if ( ! targetObject.geometry.morphTargets ) {
  27149. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  27150. return;
  27151. }
  27152. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  27153. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  27154. propertyIndex = i;
  27155. break;
  27156. }
  27157. }
  27158. }
  27159. }
  27160. bindingType = this.BindingType.ArrayElement;
  27161. this.resolvedProperty = nodeProperty;
  27162. this.propertyIndex = propertyIndex;
  27163. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27164. // must use copy for Object3D.Euler/Quaternion
  27165. bindingType = this.BindingType.HasFromToArray;
  27166. this.resolvedProperty = nodeProperty;
  27167. } else if ( Array.isArray( nodeProperty ) ) {
  27168. bindingType = this.BindingType.EntireArray;
  27169. this.resolvedProperty = nodeProperty;
  27170. } else {
  27171. this.propertyName = propertyName;
  27172. }
  27173. // select getter / setter
  27174. this.getValue = this.GetterByBindingType[ bindingType ];
  27175. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27176. },
  27177. unbind: function () {
  27178. this.node = null;
  27179. // back to the prototype version of getValue / setValue
  27180. // note: avoiding to mutate the shape of 'this' via 'delete'
  27181. this.getValue = this._getValue_unbound;
  27182. this.setValue = this._setValue_unbound;
  27183. }
  27184. } );
  27185. //!\ DECLARE ALIAS AFTER assign prototype !
  27186. Object.assign( PropertyBinding.prototype, {
  27187. // initial state of these methods that calls 'bind'
  27188. _getValue_unbound: PropertyBinding.prototype.getValue,
  27189. _setValue_unbound: PropertyBinding.prototype.setValue,
  27190. } );
  27191. /**
  27192. *
  27193. * A group of objects that receives a shared animation state.
  27194. *
  27195. * Usage:
  27196. *
  27197. * - Add objects you would otherwise pass as 'root' to the
  27198. * constructor or the .clipAction method of AnimationMixer.
  27199. *
  27200. * - Instead pass this object as 'root'.
  27201. *
  27202. * - You can also add and remove objects later when the mixer
  27203. * is running.
  27204. *
  27205. * Note:
  27206. *
  27207. * Objects of this class appear as one object to the mixer,
  27208. * so cache control of the individual objects must be done
  27209. * on the group.
  27210. *
  27211. * Limitation:
  27212. *
  27213. * - The animated properties must be compatible among the
  27214. * all objects in the group.
  27215. *
  27216. * - A single property can either be controlled through a
  27217. * target group or directly, but not both.
  27218. *
  27219. * @author tschw
  27220. */
  27221. function AnimationObjectGroup( var_args ) {
  27222. this.uuid = _Math.generateUUID();
  27223. // cached objects followed by the active ones
  27224. this._objects = Array.prototype.slice.call( arguments );
  27225. this.nCachedObjects_ = 0; // threshold
  27226. // note: read by PropertyBinding.Composite
  27227. var indices = {};
  27228. this._indicesByUUID = indices; // for bookkeeping
  27229. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  27230. indices[ arguments[ i ].uuid ] = i;
  27231. }
  27232. this._paths = []; // inside: string
  27233. this._parsedPaths = []; // inside: { we don't care, here }
  27234. this._bindings = []; // inside: Array< PropertyBinding >
  27235. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27236. var scope = this;
  27237. this.stats = {
  27238. objects: {
  27239. get total() { return scope._objects.length; },
  27240. get inUse() { return this.total - scope.nCachedObjects_; }
  27241. },
  27242. get bindingsPerObject() { return scope._bindings.length; }
  27243. };
  27244. }
  27245. Object.assign( AnimationObjectGroup.prototype, {
  27246. isAnimationObjectGroup: true,
  27247. add: function( var_args ) {
  27248. var objects = this._objects,
  27249. nObjects = objects.length,
  27250. nCachedObjects = this.nCachedObjects_,
  27251. indicesByUUID = this._indicesByUUID,
  27252. paths = this._paths,
  27253. parsedPaths = this._parsedPaths,
  27254. bindings = this._bindings,
  27255. nBindings = bindings.length;
  27256. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  27257. var object = arguments[ i ],
  27258. uuid = object.uuid,
  27259. index = indicesByUUID[ uuid ],
  27260. knownObject = undefined;
  27261. if ( index === undefined ) {
  27262. // unknown object -> add it to the ACTIVE region
  27263. index = nObjects ++;
  27264. indicesByUUID[ uuid ] = index;
  27265. objects.push( object );
  27266. // accounting is done, now do the same for all bindings
  27267. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  27268. bindings[ j ].push(
  27269. new PropertyBinding(
  27270. object, paths[ j ], parsedPaths[ j ] ) );
  27271. }
  27272. } else if ( index < nCachedObjects ) {
  27273. knownObject = objects[ index ];
  27274. // move existing object to the ACTIVE region
  27275. var firstActiveIndex = -- nCachedObjects,
  27276. lastCachedObject = objects[ firstActiveIndex ];
  27277. indicesByUUID[ lastCachedObject.uuid ] = index;
  27278. objects[ index ] = lastCachedObject;
  27279. indicesByUUID[ uuid ] = firstActiveIndex;
  27280. objects[ firstActiveIndex ] = object;
  27281. // accounting is done, now do the same for all bindings
  27282. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  27283. var bindingsForPath = bindings[ j ],
  27284. lastCached = bindingsForPath[ firstActiveIndex ],
  27285. binding = bindingsForPath[ index ];
  27286. bindingsForPath[ index ] = lastCached;
  27287. if ( binding === undefined ) {
  27288. // since we do not bother to create new bindings
  27289. // for objects that are cached, the binding may
  27290. // or may not exist
  27291. binding = new PropertyBinding(
  27292. object, paths[ j ], parsedPaths[ j ] );
  27293. }
  27294. bindingsForPath[ firstActiveIndex ] = binding;
  27295. }
  27296. } else if ( objects[ index ] !== knownObject ) {
  27297. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27298. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27299. } // else the object is already where we want it to be
  27300. } // for arguments
  27301. this.nCachedObjects_ = nCachedObjects;
  27302. },
  27303. remove: function( var_args ) {
  27304. var objects = this._objects,
  27305. nCachedObjects = this.nCachedObjects_,
  27306. indicesByUUID = this._indicesByUUID,
  27307. bindings = this._bindings,
  27308. nBindings = bindings.length;
  27309. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  27310. var object = arguments[ i ],
  27311. uuid = object.uuid,
  27312. index = indicesByUUID[ uuid ];
  27313. if ( index !== undefined && index >= nCachedObjects ) {
  27314. // move existing object into the CACHED region
  27315. var lastCachedIndex = nCachedObjects ++,
  27316. firstActiveObject = objects[ lastCachedIndex ];
  27317. indicesByUUID[ firstActiveObject.uuid ] = index;
  27318. objects[ index ] = firstActiveObject;
  27319. indicesByUUID[ uuid ] = lastCachedIndex;
  27320. objects[ lastCachedIndex ] = object;
  27321. // accounting is done, now do the same for all bindings
  27322. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  27323. var bindingsForPath = bindings[ j ],
  27324. firstActive = bindingsForPath[ lastCachedIndex ],
  27325. binding = bindingsForPath[ index ];
  27326. bindingsForPath[ index ] = firstActive;
  27327. bindingsForPath[ lastCachedIndex ] = binding;
  27328. }
  27329. }
  27330. } // for arguments
  27331. this.nCachedObjects_ = nCachedObjects;
  27332. },
  27333. // remove & forget
  27334. uncache: function( var_args ) {
  27335. var objects = this._objects,
  27336. nObjects = objects.length,
  27337. nCachedObjects = this.nCachedObjects_,
  27338. indicesByUUID = this._indicesByUUID,
  27339. bindings = this._bindings,
  27340. nBindings = bindings.length;
  27341. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  27342. var object = arguments[ i ],
  27343. uuid = object.uuid,
  27344. index = indicesByUUID[ uuid ];
  27345. if ( index !== undefined ) {
  27346. delete indicesByUUID[ uuid ];
  27347. if ( index < nCachedObjects ) {
  27348. // object is cached, shrink the CACHED region
  27349. var firstActiveIndex = -- nCachedObjects,
  27350. lastCachedObject = objects[ firstActiveIndex ],
  27351. lastIndex = -- nObjects,
  27352. lastObject = objects[ lastIndex ];
  27353. // last cached object takes this object's place
  27354. indicesByUUID[ lastCachedObject.uuid ] = index;
  27355. objects[ index ] = lastCachedObject;
  27356. // last object goes to the activated slot and pop
  27357. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27358. objects[ firstActiveIndex ] = lastObject;
  27359. objects.pop();
  27360. // accounting is done, now do the same for all bindings
  27361. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  27362. var bindingsForPath = bindings[ j ],
  27363. lastCached = bindingsForPath[ firstActiveIndex ],
  27364. last = bindingsForPath[ lastIndex ];
  27365. bindingsForPath[ index ] = lastCached;
  27366. bindingsForPath[ firstActiveIndex ] = last;
  27367. bindingsForPath.pop();
  27368. }
  27369. } else {
  27370. // object is active, just swap with the last and pop
  27371. var lastIndex = -- nObjects,
  27372. lastObject = objects[ lastIndex ];
  27373. indicesByUUID[ lastObject.uuid ] = index;
  27374. objects[ index ] = lastObject;
  27375. objects.pop();
  27376. // accounting is done, now do the same for all bindings
  27377. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  27378. var bindingsForPath = bindings[ j ];
  27379. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27380. bindingsForPath.pop();
  27381. }
  27382. } // cached or active
  27383. } // if object is known
  27384. } // for arguments
  27385. this.nCachedObjects_ = nCachedObjects;
  27386. },
  27387. // Internal interface used by befriended PropertyBinding.Composite:
  27388. subscribe_: function ( path, parsedPath ) {
  27389. // returns an array of bindings for the given path that is changed
  27390. // according to the contained objects in the group
  27391. var indicesByPath = this._bindingsIndicesByPath,
  27392. index = indicesByPath[ path ],
  27393. bindings = this._bindings;
  27394. if ( index !== undefined ) return bindings[ index ];
  27395. var paths = this._paths,
  27396. parsedPaths = this._parsedPaths,
  27397. objects = this._objects,
  27398. nObjects = objects.length,
  27399. nCachedObjects = this.nCachedObjects_,
  27400. bindingsForPath = new Array( nObjects );
  27401. index = bindings.length;
  27402. indicesByPath[ path ] = index;
  27403. paths.push( path );
  27404. parsedPaths.push( parsedPath );
  27405. bindings.push( bindingsForPath );
  27406. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27407. var object = objects[ i ];
  27408. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27409. }
  27410. return bindingsForPath;
  27411. },
  27412. unsubscribe_: function ( path ) {
  27413. // tells the group to forget about a property path and no longer
  27414. // update the array previously obtained with 'subscribe_'
  27415. var indicesByPath = this._bindingsIndicesByPath,
  27416. index = indicesByPath[ path ];
  27417. if ( index !== undefined ) {
  27418. var paths = this._paths,
  27419. parsedPaths = this._parsedPaths,
  27420. bindings = this._bindings,
  27421. lastBindingsIndex = bindings.length - 1,
  27422. lastBindings = bindings[ lastBindingsIndex ],
  27423. lastBindingsPath = path[ lastBindingsIndex ];
  27424. indicesByPath[ lastBindingsPath ] = index;
  27425. bindings[ index ] = lastBindings;
  27426. bindings.pop();
  27427. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27428. parsedPaths.pop();
  27429. paths[ index ] = paths[ lastBindingsIndex ];
  27430. paths.pop();
  27431. }
  27432. }
  27433. } );
  27434. /**
  27435. *
  27436. * Action provided by AnimationMixer for scheduling clip playback on specific
  27437. * objects.
  27438. *
  27439. * @author Ben Houston / http://clara.io/
  27440. * @author David Sarno / http://lighthaus.us/
  27441. * @author tschw
  27442. *
  27443. */
  27444. function AnimationAction( mixer, clip, localRoot ) {
  27445. this._mixer = mixer;
  27446. this._clip = clip;
  27447. this._localRoot = localRoot || null;
  27448. var tracks = clip.tracks,
  27449. nTracks = tracks.length,
  27450. interpolants = new Array( nTracks );
  27451. var interpolantSettings = {
  27452. endingStart: ZeroCurvatureEnding,
  27453. endingEnd: ZeroCurvatureEnding
  27454. };
  27455. for ( var i = 0; i !== nTracks; ++ i ) {
  27456. var interpolant = tracks[ i ].createInterpolant( null );
  27457. interpolants[ i ] = interpolant;
  27458. interpolant.settings = interpolantSettings;
  27459. }
  27460. this._interpolantSettings = interpolantSettings;
  27461. this._interpolants = interpolants; // bound by the mixer
  27462. // inside: PropertyMixer (managed by the mixer)
  27463. this._propertyBindings = new Array( nTracks );
  27464. this._cacheIndex = null; // for the memory manager
  27465. this._byClipCacheIndex = null; // for the memory manager
  27466. this._timeScaleInterpolant = null;
  27467. this._weightInterpolant = null;
  27468. this.loop = LoopRepeat;
  27469. this._loopCount = -1;
  27470. // global mixer time when the action is to be started
  27471. // it's set back to 'null' upon start of the action
  27472. this._startTime = null;
  27473. // scaled local time of the action
  27474. // gets clamped or wrapped to 0..clip.duration according to loop
  27475. this.time = 0;
  27476. this.timeScale = 1;
  27477. this._effectiveTimeScale = 1;
  27478. this.weight = 1;
  27479. this._effectiveWeight = 1;
  27480. this.repetitions = Infinity; // no. of repetitions when looping
  27481. this.paused = false; // true -> zero effective time scale
  27482. this.enabled = true; // false -> zero effective weight
  27483. this.clampWhenFinished = false; // keep feeding the last frame?
  27484. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  27485. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  27486. }
  27487. Object.assign( AnimationAction.prototype, {
  27488. // State & Scheduling
  27489. play: function() {
  27490. this._mixer._activateAction( this );
  27491. return this;
  27492. },
  27493. stop: function() {
  27494. this._mixer._deactivateAction( this );
  27495. return this.reset();
  27496. },
  27497. reset: function() {
  27498. this.paused = false;
  27499. this.enabled = true;
  27500. this.time = 0; // restart clip
  27501. this._loopCount = -1; // forget previous loops
  27502. this._startTime = null; // forget scheduling
  27503. return this.stopFading().stopWarping();
  27504. },
  27505. isRunning: function() {
  27506. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27507. this._startTime === null && this._mixer._isActiveAction( this );
  27508. },
  27509. // return true when play has been called
  27510. isScheduled: function() {
  27511. return this._mixer._isActiveAction( this );
  27512. },
  27513. startAt: function( time ) {
  27514. this._startTime = time;
  27515. return this;
  27516. },
  27517. setLoop: function( mode, repetitions ) {
  27518. this.loop = mode;
  27519. this.repetitions = repetitions;
  27520. return this;
  27521. },
  27522. // Weight
  27523. // set the weight stopping any scheduled fading
  27524. // although .enabled = false yields an effective weight of zero, this
  27525. // method does *not* change .enabled, because it would be confusing
  27526. setEffectiveWeight: function( weight ) {
  27527. this.weight = weight;
  27528. // note: same logic as when updated at runtime
  27529. this._effectiveWeight = this.enabled ? weight : 0;
  27530. return this.stopFading();
  27531. },
  27532. // return the weight considering fading and .enabled
  27533. getEffectiveWeight: function() {
  27534. return this._effectiveWeight;
  27535. },
  27536. fadeIn: function( duration ) {
  27537. return this._scheduleFading( duration, 0, 1 );
  27538. },
  27539. fadeOut: function( duration ) {
  27540. return this._scheduleFading( duration, 1, 0 );
  27541. },
  27542. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  27543. fadeOutAction.fadeOut( duration );
  27544. this.fadeIn( duration );
  27545. if( warp ) {
  27546. var fadeInDuration = this._clip.duration,
  27547. fadeOutDuration = fadeOutAction._clip.duration,
  27548. startEndRatio = fadeOutDuration / fadeInDuration,
  27549. endStartRatio = fadeInDuration / fadeOutDuration;
  27550. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27551. this.warp( endStartRatio, 1.0, duration );
  27552. }
  27553. return this;
  27554. },
  27555. crossFadeTo: function( fadeInAction, duration, warp ) {
  27556. return fadeInAction.crossFadeFrom( this, duration, warp );
  27557. },
  27558. stopFading: function() {
  27559. var weightInterpolant = this._weightInterpolant;
  27560. if ( weightInterpolant !== null ) {
  27561. this._weightInterpolant = null;
  27562. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27563. }
  27564. return this;
  27565. },
  27566. // Time Scale Control
  27567. // set the time scale stopping any scheduled warping
  27568. // although .paused = true yields an effective time scale of zero, this
  27569. // method does *not* change .paused, because it would be confusing
  27570. setEffectiveTimeScale: function( timeScale ) {
  27571. this.timeScale = timeScale;
  27572. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  27573. return this.stopWarping();
  27574. },
  27575. // return the time scale considering warping and .paused
  27576. getEffectiveTimeScale: function() {
  27577. return this._effectiveTimeScale;
  27578. },
  27579. setDuration: function( duration ) {
  27580. this.timeScale = this._clip.duration / duration;
  27581. return this.stopWarping();
  27582. },
  27583. syncWith: function( action ) {
  27584. this.time = action.time;
  27585. this.timeScale = action.timeScale;
  27586. return this.stopWarping();
  27587. },
  27588. halt: function( duration ) {
  27589. return this.warp( this._effectiveTimeScale, 0, duration );
  27590. },
  27591. warp: function( startTimeScale, endTimeScale, duration ) {
  27592. var mixer = this._mixer, now = mixer.time,
  27593. interpolant = this._timeScaleInterpolant,
  27594. timeScale = this.timeScale;
  27595. if ( interpolant === null ) {
  27596. interpolant = mixer._lendControlInterpolant();
  27597. this._timeScaleInterpolant = interpolant;
  27598. }
  27599. var times = interpolant.parameterPositions,
  27600. values = interpolant.sampleValues;
  27601. times[ 0 ] = now;
  27602. times[ 1 ] = now + duration;
  27603. values[ 0 ] = startTimeScale / timeScale;
  27604. values[ 1 ] = endTimeScale / timeScale;
  27605. return this;
  27606. },
  27607. stopWarping: function() {
  27608. var timeScaleInterpolant = this._timeScaleInterpolant;
  27609. if ( timeScaleInterpolant !== null ) {
  27610. this._timeScaleInterpolant = null;
  27611. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27612. }
  27613. return this;
  27614. },
  27615. // Object Accessors
  27616. getMixer: function() {
  27617. return this._mixer;
  27618. },
  27619. getClip: function() {
  27620. return this._clip;
  27621. },
  27622. getRoot: function() {
  27623. return this._localRoot || this._mixer._root;
  27624. },
  27625. // Interna
  27626. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  27627. // called by the mixer
  27628. if ( ! this.enabled ) {
  27629. // call ._updateWeight() to update ._effectiveWeight
  27630. this._updateWeight( time );
  27631. return;
  27632. }
  27633. var startTime = this._startTime;
  27634. if ( startTime !== null ) {
  27635. // check for scheduled start of action
  27636. var timeRunning = ( time - startTime ) * timeDirection;
  27637. if ( timeRunning < 0 || timeDirection === 0 ) {
  27638. return; // yet to come / don't decide when delta = 0
  27639. }
  27640. // start
  27641. this._startTime = null; // unschedule
  27642. deltaTime = timeDirection * timeRunning;
  27643. }
  27644. // apply time scale and advance time
  27645. deltaTime *= this._updateTimeScale( time );
  27646. var clipTime = this._updateTime( deltaTime );
  27647. // note: _updateTime may disable the action resulting in
  27648. // an effective weight of 0
  27649. var weight = this._updateWeight( time );
  27650. if ( weight > 0 ) {
  27651. var interpolants = this._interpolants;
  27652. var propertyMixers = this._propertyBindings;
  27653. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  27654. interpolants[ j ].evaluate( clipTime );
  27655. propertyMixers[ j ].accumulate( accuIndex, weight );
  27656. }
  27657. }
  27658. },
  27659. _updateWeight: function( time ) {
  27660. var weight = 0;
  27661. if ( this.enabled ) {
  27662. weight = this.weight;
  27663. var interpolant = this._weightInterpolant;
  27664. if ( interpolant !== null ) {
  27665. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  27666. weight *= interpolantValue;
  27667. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27668. this.stopFading();
  27669. if ( interpolantValue === 0 ) {
  27670. // faded out, disable
  27671. this.enabled = false;
  27672. }
  27673. }
  27674. }
  27675. }
  27676. this._effectiveWeight = weight;
  27677. return weight;
  27678. },
  27679. _updateTimeScale: function( time ) {
  27680. var timeScale = 0;
  27681. if ( ! this.paused ) {
  27682. timeScale = this.timeScale;
  27683. var interpolant = this._timeScaleInterpolant;
  27684. if ( interpolant !== null ) {
  27685. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  27686. timeScale *= interpolantValue;
  27687. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27688. this.stopWarping();
  27689. if ( timeScale === 0 ) {
  27690. // motion has halted, pause
  27691. this.paused = true;
  27692. } else {
  27693. // warp done - apply final time scale
  27694. this.timeScale = timeScale;
  27695. }
  27696. }
  27697. }
  27698. }
  27699. this._effectiveTimeScale = timeScale;
  27700. return timeScale;
  27701. },
  27702. _updateTime: function( deltaTime ) {
  27703. var time = this.time + deltaTime;
  27704. if ( deltaTime === 0 ) return time;
  27705. var duration = this._clip.duration,
  27706. loop = this.loop,
  27707. loopCount = this._loopCount;
  27708. if ( loop === LoopOnce ) {
  27709. if ( loopCount === -1 ) {
  27710. // just started
  27711. this._loopCount = 0;
  27712. this._setEndings( true, true, false );
  27713. }
  27714. handle_stop: {
  27715. if ( time >= duration ) {
  27716. time = duration;
  27717. } else if ( time < 0 ) {
  27718. time = 0;
  27719. } else break handle_stop;
  27720. if ( this.clampWhenFinished ) this.paused = true;
  27721. else this.enabled = false;
  27722. this._mixer.dispatchEvent( {
  27723. type: 'finished', action: this,
  27724. direction: deltaTime < 0 ? -1 : 1
  27725. } );
  27726. }
  27727. } else { // repetitive Repeat or PingPong
  27728. var pingPong = ( loop === LoopPingPong );
  27729. if ( loopCount === -1 ) {
  27730. // just started
  27731. if ( deltaTime >= 0 ) {
  27732. loopCount = 0;
  27733. this._setEndings(
  27734. true, this.repetitions === 0, pingPong );
  27735. } else {
  27736. // when looping in reverse direction, the initial
  27737. // transition through zero counts as a repetition,
  27738. // so leave loopCount at -1
  27739. this._setEndings(
  27740. this.repetitions === 0, true, pingPong );
  27741. }
  27742. }
  27743. if ( time >= duration || time < 0 ) {
  27744. // wrap around
  27745. var loopDelta = Math.floor( time / duration ); // signed
  27746. time -= duration * loopDelta;
  27747. loopCount += Math.abs( loopDelta );
  27748. var pending = this.repetitions - loopCount;
  27749. if ( pending < 0 ) {
  27750. // have to stop (switch state, clamp time, fire event)
  27751. if ( this.clampWhenFinished ) this.paused = true;
  27752. else this.enabled = false;
  27753. time = deltaTime > 0 ? duration : 0;
  27754. this._mixer.dispatchEvent( {
  27755. type: 'finished', action: this,
  27756. direction: deltaTime > 0 ? 1 : -1
  27757. } );
  27758. } else {
  27759. // keep running
  27760. if ( pending === 0 ) {
  27761. // entering the last round
  27762. var atStart = deltaTime < 0;
  27763. this._setEndings( atStart, ! atStart, pingPong );
  27764. } else {
  27765. this._setEndings( false, false, pingPong );
  27766. }
  27767. this._loopCount = loopCount;
  27768. this._mixer.dispatchEvent( {
  27769. type: 'loop', action: this, loopDelta: loopDelta
  27770. } );
  27771. }
  27772. }
  27773. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27774. // invert time for the "pong round"
  27775. this.time = time;
  27776. return duration - time;
  27777. }
  27778. }
  27779. this.time = time;
  27780. return time;
  27781. },
  27782. _setEndings: function( atStart, atEnd, pingPong ) {
  27783. var settings = this._interpolantSettings;
  27784. if ( pingPong ) {
  27785. settings.endingStart = ZeroSlopeEnding;
  27786. settings.endingEnd = ZeroSlopeEnding;
  27787. } else {
  27788. // assuming for LoopOnce atStart == atEnd == true
  27789. if ( atStart ) {
  27790. settings.endingStart = this.zeroSlopeAtStart ?
  27791. ZeroSlopeEnding : ZeroCurvatureEnding;
  27792. } else {
  27793. settings.endingStart = WrapAroundEnding;
  27794. }
  27795. if ( atEnd ) {
  27796. settings.endingEnd = this.zeroSlopeAtEnd ?
  27797. ZeroSlopeEnding : ZeroCurvatureEnding;
  27798. } else {
  27799. settings.endingEnd = WrapAroundEnding;
  27800. }
  27801. }
  27802. },
  27803. _scheduleFading: function( duration, weightNow, weightThen ) {
  27804. var mixer = this._mixer, now = mixer.time,
  27805. interpolant = this._weightInterpolant;
  27806. if ( interpolant === null ) {
  27807. interpolant = mixer._lendControlInterpolant();
  27808. this._weightInterpolant = interpolant;
  27809. }
  27810. var times = interpolant.parameterPositions,
  27811. values = interpolant.sampleValues;
  27812. times[ 0 ] = now; values[ 0 ] = weightNow;
  27813. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  27814. return this;
  27815. }
  27816. } );
  27817. /**
  27818. *
  27819. * Player for AnimationClips.
  27820. *
  27821. *
  27822. * @author Ben Houston / http://clara.io/
  27823. * @author David Sarno / http://lighthaus.us/
  27824. * @author tschw
  27825. */
  27826. function AnimationMixer( root ) {
  27827. this._root = root;
  27828. this._initMemoryManager();
  27829. this._accuIndex = 0;
  27830. this.time = 0;
  27831. this.timeScale = 1.0;
  27832. }
  27833. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  27834. _bindAction: function ( action, prototypeAction ) {
  27835. var root = action._localRoot || this._root,
  27836. tracks = action._clip.tracks,
  27837. nTracks = tracks.length,
  27838. bindings = action._propertyBindings,
  27839. interpolants = action._interpolants,
  27840. rootUuid = root.uuid,
  27841. bindingsByRoot = this._bindingsByRootAndName,
  27842. bindingsByName = bindingsByRoot[ rootUuid ];
  27843. if ( bindingsByName === undefined ) {
  27844. bindingsByName = {};
  27845. bindingsByRoot[ rootUuid ] = bindingsByName;
  27846. }
  27847. for ( var i = 0; i !== nTracks; ++ i ) {
  27848. var track = tracks[ i ],
  27849. trackName = track.name,
  27850. binding = bindingsByName[ trackName ];
  27851. if ( binding !== undefined ) {
  27852. bindings[ i ] = binding;
  27853. } else {
  27854. binding = bindings[ i ];
  27855. if ( binding !== undefined ) {
  27856. // existing binding, make sure the cache knows
  27857. if ( binding._cacheIndex === null ) {
  27858. ++ binding.referenceCount;
  27859. this._addInactiveBinding( binding, rootUuid, trackName );
  27860. }
  27861. continue;
  27862. }
  27863. var path = prototypeAction && prototypeAction.
  27864. _propertyBindings[ i ].binding.parsedPath;
  27865. binding = new PropertyMixer(
  27866. PropertyBinding.create( root, trackName, path ),
  27867. track.ValueTypeName, track.getValueSize() );
  27868. ++ binding.referenceCount;
  27869. this._addInactiveBinding( binding, rootUuid, trackName );
  27870. bindings[ i ] = binding;
  27871. }
  27872. interpolants[ i ].resultBuffer = binding.buffer;
  27873. }
  27874. },
  27875. _activateAction: function ( action ) {
  27876. if ( ! this._isActiveAction( action ) ) {
  27877. if ( action._cacheIndex === null ) {
  27878. // this action has been forgotten by the cache, but the user
  27879. // appears to be still using it -> rebind
  27880. var rootUuid = ( action._localRoot || this._root ).uuid,
  27881. clipUuid = action._clip.uuid,
  27882. actionsForClip = this._actionsByClip[ clipUuid ];
  27883. this._bindAction( action,
  27884. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27885. this._addInactiveAction( action, clipUuid, rootUuid );
  27886. }
  27887. var bindings = action._propertyBindings;
  27888. // increment reference counts / sort out state
  27889. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27890. var binding = bindings[ i ];
  27891. if ( binding.useCount ++ === 0 ) {
  27892. this._lendBinding( binding );
  27893. binding.saveOriginalState();
  27894. }
  27895. }
  27896. this._lendAction( action );
  27897. }
  27898. },
  27899. _deactivateAction: function ( action ) {
  27900. if ( this._isActiveAction( action ) ) {
  27901. var bindings = action._propertyBindings;
  27902. // decrement reference counts / sort out state
  27903. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27904. var binding = bindings[ i ];
  27905. if ( -- binding.useCount === 0 ) {
  27906. binding.restoreOriginalState();
  27907. this._takeBackBinding( binding );
  27908. }
  27909. }
  27910. this._takeBackAction( action );
  27911. }
  27912. },
  27913. // Memory manager
  27914. _initMemoryManager: function () {
  27915. this._actions = []; // 'nActiveActions' followed by inactive ones
  27916. this._nActiveActions = 0;
  27917. this._actionsByClip = {};
  27918. // inside:
  27919. // {
  27920. // knownActions: Array< AnimationAction > - used as prototypes
  27921. // actionByRoot: AnimationAction - lookup
  27922. // }
  27923. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27924. this._nActiveBindings = 0;
  27925. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27926. this._controlInterpolants = []; // same game as above
  27927. this._nActiveControlInterpolants = 0;
  27928. var scope = this;
  27929. this.stats = {
  27930. actions: {
  27931. get total() { return scope._actions.length; },
  27932. get inUse() { return scope._nActiveActions; }
  27933. },
  27934. bindings: {
  27935. get total() { return scope._bindings.length; },
  27936. get inUse() { return scope._nActiveBindings; }
  27937. },
  27938. controlInterpolants: {
  27939. get total() { return scope._controlInterpolants.length; },
  27940. get inUse() { return scope._nActiveControlInterpolants; }
  27941. }
  27942. };
  27943. },
  27944. // Memory management for AnimationAction objects
  27945. _isActiveAction: function ( action ) {
  27946. var index = action._cacheIndex;
  27947. return index !== null && index < this._nActiveActions;
  27948. },
  27949. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27950. var actions = this._actions,
  27951. actionsByClip = this._actionsByClip,
  27952. actionsForClip = actionsByClip[ clipUuid ];
  27953. if ( actionsForClip === undefined ) {
  27954. actionsForClip = {
  27955. knownActions: [ action ],
  27956. actionByRoot: {}
  27957. };
  27958. action._byClipCacheIndex = 0;
  27959. actionsByClip[ clipUuid ] = actionsForClip;
  27960. } else {
  27961. var knownActions = actionsForClip.knownActions;
  27962. action._byClipCacheIndex = knownActions.length;
  27963. knownActions.push( action );
  27964. }
  27965. action._cacheIndex = actions.length;
  27966. actions.push( action );
  27967. actionsForClip.actionByRoot[ rootUuid ] = action;
  27968. },
  27969. _removeInactiveAction: function ( action ) {
  27970. var actions = this._actions,
  27971. lastInactiveAction = actions[ actions.length - 1 ],
  27972. cacheIndex = action._cacheIndex;
  27973. lastInactiveAction._cacheIndex = cacheIndex;
  27974. actions[ cacheIndex ] = lastInactiveAction;
  27975. actions.pop();
  27976. action._cacheIndex = null;
  27977. var clipUuid = action._clip.uuid,
  27978. actionsByClip = this._actionsByClip,
  27979. actionsForClip = actionsByClip[ clipUuid ],
  27980. knownActionsForClip = actionsForClip.knownActions,
  27981. lastKnownAction =
  27982. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27983. byClipCacheIndex = action._byClipCacheIndex;
  27984. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27985. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27986. knownActionsForClip.pop();
  27987. action._byClipCacheIndex = null;
  27988. var actionByRoot = actionsForClip.actionByRoot,
  27989. rootUuid = ( action._localRoot || this._root ).uuid;
  27990. delete actionByRoot[ rootUuid ];
  27991. if ( knownActionsForClip.length === 0 ) {
  27992. delete actionsByClip[ clipUuid ];
  27993. }
  27994. this._removeInactiveBindingsForAction( action );
  27995. },
  27996. _removeInactiveBindingsForAction: function ( action ) {
  27997. var bindings = action._propertyBindings;
  27998. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27999. var binding = bindings[ i ];
  28000. if ( -- binding.referenceCount === 0 ) {
  28001. this._removeInactiveBinding( binding );
  28002. }
  28003. }
  28004. },
  28005. _lendAction: function ( action ) {
  28006. // [ active actions | inactive actions ]
  28007. // [ active actions >| inactive actions ]
  28008. // s a
  28009. // <-swap->
  28010. // a s
  28011. var actions = this._actions,
  28012. prevIndex = action._cacheIndex,
  28013. lastActiveIndex = this._nActiveActions ++,
  28014. firstInactiveAction = actions[ lastActiveIndex ];
  28015. action._cacheIndex = lastActiveIndex;
  28016. actions[ lastActiveIndex ] = action;
  28017. firstInactiveAction._cacheIndex = prevIndex;
  28018. actions[ prevIndex ] = firstInactiveAction;
  28019. },
  28020. _takeBackAction: function ( action ) {
  28021. // [ active actions | inactive actions ]
  28022. // [ active actions |< inactive actions ]
  28023. // a s
  28024. // <-swap->
  28025. // s a
  28026. var actions = this._actions,
  28027. prevIndex = action._cacheIndex,
  28028. firstInactiveIndex = -- this._nActiveActions,
  28029. lastActiveAction = actions[ firstInactiveIndex ];
  28030. action._cacheIndex = firstInactiveIndex;
  28031. actions[ firstInactiveIndex ] = action;
  28032. lastActiveAction._cacheIndex = prevIndex;
  28033. actions[ prevIndex ] = lastActiveAction;
  28034. },
  28035. // Memory management for PropertyMixer objects
  28036. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  28037. var bindingsByRoot = this._bindingsByRootAndName,
  28038. bindingByName = bindingsByRoot[ rootUuid ],
  28039. bindings = this._bindings;
  28040. if ( bindingByName === undefined ) {
  28041. bindingByName = {};
  28042. bindingsByRoot[ rootUuid ] = bindingByName;
  28043. }
  28044. bindingByName[ trackName ] = binding;
  28045. binding._cacheIndex = bindings.length;
  28046. bindings.push( binding );
  28047. },
  28048. _removeInactiveBinding: function ( binding ) {
  28049. var bindings = this._bindings,
  28050. propBinding = binding.binding,
  28051. rootUuid = propBinding.rootNode.uuid,
  28052. trackName = propBinding.path,
  28053. bindingsByRoot = this._bindingsByRootAndName,
  28054. bindingByName = bindingsByRoot[ rootUuid ],
  28055. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28056. cacheIndex = binding._cacheIndex;
  28057. lastInactiveBinding._cacheIndex = cacheIndex;
  28058. bindings[ cacheIndex ] = lastInactiveBinding;
  28059. bindings.pop();
  28060. delete bindingByName[ trackName ];
  28061. remove_empty_map: {
  28062. for ( var _ in bindingByName ) break remove_empty_map;
  28063. delete bindingsByRoot[ rootUuid ];
  28064. }
  28065. },
  28066. _lendBinding: function ( binding ) {
  28067. var bindings = this._bindings,
  28068. prevIndex = binding._cacheIndex,
  28069. lastActiveIndex = this._nActiveBindings ++,
  28070. firstInactiveBinding = bindings[ lastActiveIndex ];
  28071. binding._cacheIndex = lastActiveIndex;
  28072. bindings[ lastActiveIndex ] = binding;
  28073. firstInactiveBinding._cacheIndex = prevIndex;
  28074. bindings[ prevIndex ] = firstInactiveBinding;
  28075. },
  28076. _takeBackBinding: function ( binding ) {
  28077. var bindings = this._bindings,
  28078. prevIndex = binding._cacheIndex,
  28079. firstInactiveIndex = -- this._nActiveBindings,
  28080. lastActiveBinding = bindings[ firstInactiveIndex ];
  28081. binding._cacheIndex = firstInactiveIndex;
  28082. bindings[ firstInactiveIndex ] = binding;
  28083. lastActiveBinding._cacheIndex = prevIndex;
  28084. bindings[ prevIndex ] = lastActiveBinding;
  28085. },
  28086. // Memory management of Interpolants for weight and time scale
  28087. _lendControlInterpolant: function () {
  28088. var interpolants = this._controlInterpolants,
  28089. lastActiveIndex = this._nActiveControlInterpolants ++,
  28090. interpolant = interpolants[ lastActiveIndex ];
  28091. if ( interpolant === undefined ) {
  28092. interpolant = new LinearInterpolant(
  28093. new Float32Array( 2 ), new Float32Array( 2 ),
  28094. 1, this._controlInterpolantsResultBuffer );
  28095. interpolant.__cacheIndex = lastActiveIndex;
  28096. interpolants[ lastActiveIndex ] = interpolant;
  28097. }
  28098. return interpolant;
  28099. },
  28100. _takeBackControlInterpolant: function ( interpolant ) {
  28101. var interpolants = this._controlInterpolants,
  28102. prevIndex = interpolant.__cacheIndex,
  28103. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28104. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28105. interpolant.__cacheIndex = firstInactiveIndex;
  28106. interpolants[ firstInactiveIndex ] = interpolant;
  28107. lastActiveInterpolant.__cacheIndex = prevIndex;
  28108. interpolants[ prevIndex ] = lastActiveInterpolant;
  28109. },
  28110. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  28111. // return an action for a clip optionally using a custom root target
  28112. // object (this method allocates a lot of dynamic memory in case a
  28113. // previously unknown clip/root combination is specified)
  28114. clipAction: function ( clip, optionalRoot ) {
  28115. var root = optionalRoot || this._root,
  28116. rootUuid = root.uuid,
  28117. clipObject = typeof clip === 'string' ?
  28118. AnimationClip.findByName( root, clip ) : clip,
  28119. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  28120. actionsForClip = this._actionsByClip[ clipUuid ],
  28121. prototypeAction = null;
  28122. if ( actionsForClip !== undefined ) {
  28123. var existingAction =
  28124. actionsForClip.actionByRoot[ rootUuid ];
  28125. if ( existingAction !== undefined ) {
  28126. return existingAction;
  28127. }
  28128. // we know the clip, so we don't have to parse all
  28129. // the bindings again but can just copy
  28130. prototypeAction = actionsForClip.knownActions[ 0 ];
  28131. // also, take the clip from the prototype action
  28132. if ( clipObject === null )
  28133. clipObject = prototypeAction._clip;
  28134. }
  28135. // clip must be known when specified via string
  28136. if ( clipObject === null ) return null;
  28137. // allocate all resources required to run it
  28138. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  28139. this._bindAction( newAction, prototypeAction );
  28140. // and make the action known to the memory manager
  28141. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28142. return newAction;
  28143. },
  28144. // get an existing action
  28145. existingAction: function ( clip, optionalRoot ) {
  28146. var root = optionalRoot || this._root,
  28147. rootUuid = root.uuid,
  28148. clipObject = typeof clip === 'string' ?
  28149. AnimationClip.findByName( root, clip ) : clip,
  28150. clipUuid = clipObject ? clipObject.uuid : clip,
  28151. actionsForClip = this._actionsByClip[ clipUuid ];
  28152. if ( actionsForClip !== undefined ) {
  28153. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28154. }
  28155. return null;
  28156. },
  28157. // deactivates all previously scheduled actions
  28158. stopAllAction: function () {
  28159. var actions = this._actions,
  28160. nActions = this._nActiveActions,
  28161. bindings = this._bindings,
  28162. nBindings = this._nActiveBindings;
  28163. this._nActiveActions = 0;
  28164. this._nActiveBindings = 0;
  28165. for ( var i = 0; i !== nActions; ++ i ) {
  28166. actions[ i ].reset();
  28167. }
  28168. for ( var i = 0; i !== nBindings; ++ i ) {
  28169. bindings[ i ].useCount = 0;
  28170. }
  28171. return this;
  28172. },
  28173. // advance the time and update apply the animation
  28174. update: function ( deltaTime ) {
  28175. deltaTime *= this.timeScale;
  28176. var actions = this._actions,
  28177. nActions = this._nActiveActions,
  28178. time = this.time += deltaTime,
  28179. timeDirection = Math.sign( deltaTime ),
  28180. accuIndex = this._accuIndex ^= 1;
  28181. // run active actions
  28182. for ( var i = 0; i !== nActions; ++ i ) {
  28183. var action = actions[ i ];
  28184. action._update( time, deltaTime, timeDirection, accuIndex );
  28185. }
  28186. // update scene graph
  28187. var bindings = this._bindings,
  28188. nBindings = this._nActiveBindings;
  28189. for ( var i = 0; i !== nBindings; ++ i ) {
  28190. bindings[ i ].apply( accuIndex );
  28191. }
  28192. return this;
  28193. },
  28194. // return this mixer's root target object
  28195. getRoot: function () {
  28196. return this._root;
  28197. },
  28198. // free all resources specific to a particular clip
  28199. uncacheClip: function ( clip ) {
  28200. var actions = this._actions,
  28201. clipUuid = clip.uuid,
  28202. actionsByClip = this._actionsByClip,
  28203. actionsForClip = actionsByClip[ clipUuid ];
  28204. if ( actionsForClip !== undefined ) {
  28205. // note: just calling _removeInactiveAction would mess up the
  28206. // iteration state and also require updating the state we can
  28207. // just throw away
  28208. var actionsToRemove = actionsForClip.knownActions;
  28209. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28210. var action = actionsToRemove[ i ];
  28211. this._deactivateAction( action );
  28212. var cacheIndex = action._cacheIndex,
  28213. lastInactiveAction = actions[ actions.length - 1 ];
  28214. action._cacheIndex = null;
  28215. action._byClipCacheIndex = null;
  28216. lastInactiveAction._cacheIndex = cacheIndex;
  28217. actions[ cacheIndex ] = lastInactiveAction;
  28218. actions.pop();
  28219. this._removeInactiveBindingsForAction( action );
  28220. }
  28221. delete actionsByClip[ clipUuid ];
  28222. }
  28223. },
  28224. // free all resources specific to a particular root target object
  28225. uncacheRoot: function ( root ) {
  28226. var rootUuid = root.uuid,
  28227. actionsByClip = this._actionsByClip;
  28228. for ( var clipUuid in actionsByClip ) {
  28229. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28230. action = actionByRoot[ rootUuid ];
  28231. if ( action !== undefined ) {
  28232. this._deactivateAction( action );
  28233. this._removeInactiveAction( action );
  28234. }
  28235. }
  28236. var bindingsByRoot = this._bindingsByRootAndName,
  28237. bindingByName = bindingsByRoot[ rootUuid ];
  28238. if ( bindingByName !== undefined ) {
  28239. for ( var trackName in bindingByName ) {
  28240. var binding = bindingByName[ trackName ];
  28241. binding.restoreOriginalState();
  28242. this._removeInactiveBinding( binding );
  28243. }
  28244. }
  28245. },
  28246. // remove a targeted clip from the cache
  28247. uncacheAction: function ( clip, optionalRoot ) {
  28248. var action = this.existingAction( clip, optionalRoot );
  28249. if ( action !== null ) {
  28250. this._deactivateAction( action );
  28251. this._removeInactiveAction( action );
  28252. }
  28253. }
  28254. } );
  28255. /**
  28256. * @author mrdoob / http://mrdoob.com/
  28257. */
  28258. function Uniform( value ) {
  28259. if ( typeof value === 'string' ) {
  28260. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  28261. value = arguments[ 1 ];
  28262. }
  28263. this.value = value;
  28264. }
  28265. Uniform.prototype.clone = function () {
  28266. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28267. };
  28268. /**
  28269. * @author benaadams / https://twitter.com/ben_a_adams
  28270. */
  28271. function InstancedBufferGeometry() {
  28272. BufferGeometry.call( this );
  28273. this.type = 'InstancedBufferGeometry';
  28274. this.maxInstancedCount = undefined;
  28275. }
  28276. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  28277. constructor: InstancedBufferGeometry,
  28278. isInstancedBufferGeometry: true,
  28279. addGroup: function ( start, count, materialIndex ) {
  28280. this.groups.push( {
  28281. start: start,
  28282. count: count,
  28283. materialIndex: materialIndex
  28284. } );
  28285. },
  28286. copy: function ( source ) {
  28287. var index = source.index;
  28288. if ( index !== null ) {
  28289. this.setIndex( index.clone() );
  28290. }
  28291. var attributes = source.attributes;
  28292. for ( var name in attributes ) {
  28293. var attribute = attributes[ name ];
  28294. this.addAttribute( name, attribute.clone() );
  28295. }
  28296. var groups = source.groups;
  28297. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  28298. var group = groups[ i ];
  28299. this.addGroup( group.start, group.count, group.materialIndex );
  28300. }
  28301. return this;
  28302. }
  28303. } );
  28304. /**
  28305. * @author benaadams / https://twitter.com/ben_a_adams
  28306. */
  28307. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  28308. this.uuid = _Math.generateUUID();
  28309. this.data = interleavedBuffer;
  28310. this.itemSize = itemSize;
  28311. this.offset = offset;
  28312. this.normalized = normalized === true;
  28313. }
  28314. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  28315. count: {
  28316. get: function () {
  28317. return this.data.count;
  28318. }
  28319. },
  28320. array: {
  28321. get: function () {
  28322. return this.data.array;
  28323. }
  28324. }
  28325. } );
  28326. Object.assign( InterleavedBufferAttribute.prototype, {
  28327. isInterleavedBufferAttribute: true,
  28328. setX: function ( index, x ) {
  28329. this.data.array[ index * this.data.stride + this.offset ] = x;
  28330. return this;
  28331. },
  28332. setY: function ( index, y ) {
  28333. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  28334. return this;
  28335. },
  28336. setZ: function ( index, z ) {
  28337. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  28338. return this;
  28339. },
  28340. setW: function ( index, w ) {
  28341. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  28342. return this;
  28343. },
  28344. getX: function ( index ) {
  28345. return this.data.array[ index * this.data.stride + this.offset ];
  28346. },
  28347. getY: function ( index ) {
  28348. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  28349. },
  28350. getZ: function ( index ) {
  28351. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  28352. },
  28353. getW: function ( index ) {
  28354. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  28355. },
  28356. setXY: function ( index, x, y ) {
  28357. index = index * this.data.stride + this.offset;
  28358. this.data.array[ index + 0 ] = x;
  28359. this.data.array[ index + 1 ] = y;
  28360. return this;
  28361. },
  28362. setXYZ: function ( index, x, y, z ) {
  28363. index = index * this.data.stride + this.offset;
  28364. this.data.array[ index + 0 ] = x;
  28365. this.data.array[ index + 1 ] = y;
  28366. this.data.array[ index + 2 ] = z;
  28367. return this;
  28368. },
  28369. setXYZW: function ( index, x, y, z, w ) {
  28370. index = index * this.data.stride + this.offset;
  28371. this.data.array[ index + 0 ] = x;
  28372. this.data.array[ index + 1 ] = y;
  28373. this.data.array[ index + 2 ] = z;
  28374. this.data.array[ index + 3 ] = w;
  28375. return this;
  28376. }
  28377. } );
  28378. /**
  28379. * @author benaadams / https://twitter.com/ben_a_adams
  28380. */
  28381. function InterleavedBuffer( array, stride ) {
  28382. this.uuid = _Math.generateUUID();
  28383. this.array = array;
  28384. this.stride = stride;
  28385. this.count = array !== undefined ? array.length / stride : 0;
  28386. this.dynamic = false;
  28387. this.updateRange = { offset: 0, count: - 1 };
  28388. this.onUploadCallback = function () {};
  28389. this.version = 0;
  28390. }
  28391. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  28392. set: function ( value ) {
  28393. if ( value === true ) this.version ++;
  28394. }
  28395. } );
  28396. Object.assign( InterleavedBuffer.prototype, {
  28397. isInterleavedBuffer: true,
  28398. setArray: function ( array ) {
  28399. if ( Array.isArray( array ) ) {
  28400. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  28401. }
  28402. this.count = array !== undefined ? array.length / this.stride : 0;
  28403. this.array = array;
  28404. },
  28405. setDynamic: function ( value ) {
  28406. this.dynamic = value;
  28407. return this;
  28408. },
  28409. copy: function ( source ) {
  28410. this.array = new source.array.constructor( source.array );
  28411. this.count = source.count;
  28412. this.stride = source.stride;
  28413. this.dynamic = source.dynamic;
  28414. return this;
  28415. },
  28416. copyAt: function ( index1, attribute, index2 ) {
  28417. index1 *= this.stride;
  28418. index2 *= attribute.stride;
  28419. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  28420. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  28421. }
  28422. return this;
  28423. },
  28424. set: function ( value, offset ) {
  28425. if ( offset === undefined ) offset = 0;
  28426. this.array.set( value, offset );
  28427. return this;
  28428. },
  28429. clone: function () {
  28430. return new this.constructor().copy( this );
  28431. },
  28432. onUpload: function ( callback ) {
  28433. this.onUploadCallback = callback;
  28434. return this;
  28435. }
  28436. } );
  28437. /**
  28438. * @author benaadams / https://twitter.com/ben_a_adams
  28439. */
  28440. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  28441. InterleavedBuffer.call( this, array, stride );
  28442. this.meshPerAttribute = meshPerAttribute || 1;
  28443. }
  28444. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  28445. constructor: InstancedInterleavedBuffer,
  28446. isInstancedInterleavedBuffer: true,
  28447. copy: function ( source ) {
  28448. InterleavedBuffer.prototype.copy.call( this, source );
  28449. this.meshPerAttribute = source.meshPerAttribute;
  28450. return this;
  28451. }
  28452. } );
  28453. /**
  28454. * @author benaadams / https://twitter.com/ben_a_adams
  28455. */
  28456. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  28457. BufferAttribute.call( this, array, itemSize );
  28458. this.meshPerAttribute = meshPerAttribute || 1;
  28459. }
  28460. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  28461. constructor: InstancedBufferAttribute,
  28462. isInstancedBufferAttribute: true,
  28463. copy: function ( source ) {
  28464. BufferAttribute.prototype.copy.call( this, source );
  28465. this.meshPerAttribute = source.meshPerAttribute;
  28466. return this;
  28467. }
  28468. } );
  28469. /**
  28470. * @author mrdoob / http://mrdoob.com/
  28471. * @author bhouston / http://clara.io/
  28472. * @author stephomi / http://stephaneginier.com/
  28473. */
  28474. function Raycaster( origin, direction, near, far ) {
  28475. this.ray = new Ray( origin, direction );
  28476. // direction is assumed to be normalized (for accurate distance calculations)
  28477. this.near = near || 0;
  28478. this.far = far || Infinity;
  28479. this.params = {
  28480. Mesh: {},
  28481. Line: {},
  28482. LOD: {},
  28483. Points: { threshold: 1 },
  28484. Sprite: {}
  28485. };
  28486. Object.defineProperties( this.params, {
  28487. PointCloud: {
  28488. get: function () {
  28489. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  28490. return this.Points;
  28491. }
  28492. }
  28493. } );
  28494. }
  28495. function ascSort( a, b ) {
  28496. return a.distance - b.distance;
  28497. }
  28498. function intersectObject( object, raycaster, intersects, recursive ) {
  28499. if ( object.visible === false ) return;
  28500. object.raycast( raycaster, intersects );
  28501. if ( recursive === true ) {
  28502. var children = object.children;
  28503. for ( var i = 0, l = children.length; i < l; i ++ ) {
  28504. intersectObject( children[ i ], raycaster, intersects, true );
  28505. }
  28506. }
  28507. }
  28508. Object.assign( Raycaster.prototype, {
  28509. linePrecision: 1,
  28510. set: function ( origin, direction ) {
  28511. // direction is assumed to be normalized (for accurate distance calculations)
  28512. this.ray.set( origin, direction );
  28513. },
  28514. setFromCamera: function ( coords, camera ) {
  28515. if ( ( camera && camera.isPerspectiveCamera ) ) {
  28516. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28517. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28518. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  28519. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28520. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28521. } else {
  28522. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  28523. }
  28524. },
  28525. intersectObject: function ( object, recursive ) {
  28526. var intersects = [];
  28527. intersectObject( object, this, intersects, recursive );
  28528. intersects.sort( ascSort );
  28529. return intersects;
  28530. },
  28531. intersectObjects: function ( objects, recursive ) {
  28532. var intersects = [];
  28533. if ( Array.isArray( objects ) === false ) {
  28534. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  28535. return intersects;
  28536. }
  28537. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  28538. intersectObject( objects[ i ], this, intersects, recursive );
  28539. }
  28540. intersects.sort( ascSort );
  28541. return intersects;
  28542. }
  28543. } );
  28544. /**
  28545. * @author alteredq / http://alteredqualia.com/
  28546. */
  28547. function Clock( autoStart ) {
  28548. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  28549. this.startTime = 0;
  28550. this.oldTime = 0;
  28551. this.elapsedTime = 0;
  28552. this.running = false;
  28553. }
  28554. Object.assign( Clock.prototype, {
  28555. start: function () {
  28556. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  28557. this.oldTime = this.startTime;
  28558. this.elapsedTime = 0;
  28559. this.running = true;
  28560. },
  28561. stop: function () {
  28562. this.getElapsedTime();
  28563. this.running = false;
  28564. this.autoStart = false;
  28565. },
  28566. getElapsedTime: function () {
  28567. this.getDelta();
  28568. return this.elapsedTime;
  28569. },
  28570. getDelta: function () {
  28571. var diff = 0;
  28572. if ( this.autoStart && ! this.running ) {
  28573. this.start();
  28574. return 0;
  28575. }
  28576. if ( this.running ) {
  28577. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  28578. diff = ( newTime - this.oldTime ) / 1000;
  28579. this.oldTime = newTime;
  28580. this.elapsedTime += diff;
  28581. }
  28582. return diff;
  28583. }
  28584. } );
  28585. /**
  28586. * @author bhouston / http://clara.io
  28587. * @author WestLangley / http://github.com/WestLangley
  28588. *
  28589. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28590. *
  28591. * The poles (phi) are at the positive and negative y axis.
  28592. * The equator starts at positive z.
  28593. */
  28594. function Spherical( radius, phi, theta ) {
  28595. this.radius = ( radius !== undefined ) ? radius : 1.0;
  28596. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  28597. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  28598. return this;
  28599. }
  28600. Object.assign( Spherical.prototype, {
  28601. set: function ( radius, phi, theta ) {
  28602. this.radius = radius;
  28603. this.phi = phi;
  28604. this.theta = theta;
  28605. return this;
  28606. },
  28607. clone: function () {
  28608. return new this.constructor().copy( this );
  28609. },
  28610. copy: function ( other ) {
  28611. this.radius = other.radius;
  28612. this.phi = other.phi;
  28613. this.theta = other.theta;
  28614. return this;
  28615. },
  28616. // restrict phi to be betwee EPS and PI-EPS
  28617. makeSafe: function() {
  28618. var EPS = 0.000001;
  28619. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28620. return this;
  28621. },
  28622. setFromVector3: function( vec3 ) {
  28623. this.radius = vec3.length();
  28624. if ( this.radius === 0 ) {
  28625. this.theta = 0;
  28626. this.phi = 0;
  28627. } else {
  28628. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  28629. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  28630. }
  28631. return this;
  28632. }
  28633. } );
  28634. /**
  28635. * @author Mugen87 / https://github.com/Mugen87
  28636. *
  28637. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28638. *
  28639. */
  28640. function Cylindrical( radius, theta, y ) {
  28641. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  28642. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28643. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  28644. return this;
  28645. }
  28646. Object.assign( Cylindrical.prototype, {
  28647. set: function ( radius, theta, y ) {
  28648. this.radius = radius;
  28649. this.theta = theta;
  28650. this.y = y;
  28651. return this;
  28652. },
  28653. clone: function () {
  28654. return new this.constructor().copy( this );
  28655. },
  28656. copy: function ( other ) {
  28657. this.radius = other.radius;
  28658. this.theta = other.theta;
  28659. this.y = other.y;
  28660. return this;
  28661. },
  28662. setFromVector3: function( vec3 ) {
  28663. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  28664. this.theta = Math.atan2( vec3.x, vec3.z );
  28665. this.y = vec3.y;
  28666. return this;
  28667. }
  28668. } );
  28669. /**
  28670. * @author alteredq / http://alteredqualia.com/
  28671. */
  28672. function ImmediateRenderObject( material ) {
  28673. Object3D.call( this );
  28674. this.material = material;
  28675. this.render = function ( renderCallback ) {};
  28676. }
  28677. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  28678. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28679. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28680. /**
  28681. * @author mrdoob / http://mrdoob.com/
  28682. * @author WestLangley / http://github.com/WestLangley
  28683. */
  28684. function VertexNormalsHelper( object, size, hex, linewidth ) {
  28685. this.object = object;
  28686. this.size = ( size !== undefined ) ? size : 1;
  28687. var color = ( hex !== undefined ) ? hex : 0xff0000;
  28688. var width = ( linewidth !== undefined ) ? linewidth : 1;
  28689. //
  28690. var nNormals = 0;
  28691. var objGeometry = this.object.geometry;
  28692. if ( objGeometry && objGeometry.isGeometry ) {
  28693. nNormals = objGeometry.faces.length * 3;
  28694. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  28695. nNormals = objGeometry.attributes.normal.count;
  28696. }
  28697. //
  28698. var geometry = new BufferGeometry();
  28699. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  28700. geometry.addAttribute( 'position', positions );
  28701. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  28702. //
  28703. this.matrixAutoUpdate = false;
  28704. this.update();
  28705. }
  28706. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  28707. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28708. VertexNormalsHelper.prototype.update = ( function () {
  28709. var v1 = new Vector3();
  28710. var v2 = new Vector3();
  28711. var normalMatrix = new Matrix3();
  28712. return function update() {
  28713. var keys = [ 'a', 'b', 'c' ];
  28714. this.object.updateMatrixWorld( true );
  28715. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  28716. var matrixWorld = this.object.matrixWorld;
  28717. var position = this.geometry.attributes.position;
  28718. //
  28719. var objGeometry = this.object.geometry;
  28720. if ( objGeometry && objGeometry.isGeometry ) {
  28721. var vertices = objGeometry.vertices;
  28722. var faces = objGeometry.faces;
  28723. var idx = 0;
  28724. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  28725. var face = faces[ i ];
  28726. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  28727. var vertex = vertices[ face[ keys[ j ] ] ];
  28728. var normal = face.vertexNormals[ j ];
  28729. v1.copy( vertex ).applyMatrix4( matrixWorld );
  28730. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28731. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28732. idx = idx + 1;
  28733. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28734. idx = idx + 1;
  28735. }
  28736. }
  28737. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  28738. var objPos = objGeometry.attributes.position;
  28739. var objNorm = objGeometry.attributes.normal;
  28740. var idx = 0;
  28741. // for simplicity, ignore index and drawcalls, and render every normal
  28742. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  28743. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  28744. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  28745. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28746. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28747. idx = idx + 1;
  28748. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28749. idx = idx + 1;
  28750. }
  28751. }
  28752. position.needsUpdate = true;
  28753. };
  28754. }() );
  28755. /**
  28756. * @author alteredq / http://alteredqualia.com/
  28757. * @author mrdoob / http://mrdoob.com/
  28758. * @author WestLangley / http://github.com/WestLangley
  28759. */
  28760. function SpotLightHelper( light, color ) {
  28761. Object3D.call( this );
  28762. this.light = light;
  28763. this.light.updateMatrixWorld();
  28764. this.matrix = light.matrixWorld;
  28765. this.matrixAutoUpdate = false;
  28766. this.color = color;
  28767. var geometry = new BufferGeometry();
  28768. var positions = [
  28769. 0, 0, 0, 0, 0, 1,
  28770. 0, 0, 0, 1, 0, 1,
  28771. 0, 0, 0, - 1, 0, 1,
  28772. 0, 0, 0, 0, 1, 1,
  28773. 0, 0, 0, 0, - 1, 1
  28774. ];
  28775. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28776. var p1 = ( i / l ) * Math.PI * 2;
  28777. var p2 = ( j / l ) * Math.PI * 2;
  28778. positions.push(
  28779. Math.cos( p1 ), Math.sin( p1 ), 1,
  28780. Math.cos( p2 ), Math.sin( p2 ), 1
  28781. );
  28782. }
  28783. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28784. var material = new LineBasicMaterial( { fog: false } );
  28785. this.cone = new LineSegments( geometry, material );
  28786. this.add( this.cone );
  28787. this.update();
  28788. }
  28789. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  28790. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28791. SpotLightHelper.prototype.dispose = function () {
  28792. this.cone.geometry.dispose();
  28793. this.cone.material.dispose();
  28794. };
  28795. SpotLightHelper.prototype.update = function () {
  28796. var vector = new Vector3();
  28797. var vector2 = new Vector3();
  28798. return function update() {
  28799. this.light.updateMatrixWorld();
  28800. var coneLength = this.light.distance ? this.light.distance : 1000;
  28801. var coneWidth = coneLength * Math.tan( this.light.angle );
  28802. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28803. vector.setFromMatrixPosition( this.light.matrixWorld );
  28804. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28805. this.cone.lookAt( vector2.sub( vector ) );
  28806. if ( this.color !== undefined ) {
  28807. this.cone.material.color.set( this.color );
  28808. } else {
  28809. this.cone.material.color.copy( this.light.color );
  28810. }
  28811. };
  28812. }();
  28813. /**
  28814. * @author Sean Griffin / http://twitter.com/sgrif
  28815. * @author Michael Guerrero / http://realitymeltdown.com
  28816. * @author mrdoob / http://mrdoob.com/
  28817. * @author ikerr / http://verold.com
  28818. * @author Mugen87 / https://github.com/Mugen87
  28819. */
  28820. function getBoneList( object ) {
  28821. var boneList = [];
  28822. if ( object && object.isBone ) {
  28823. boneList.push( object );
  28824. }
  28825. for ( var i = 0; i < object.children.length; i ++ ) {
  28826. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28827. }
  28828. return boneList;
  28829. }
  28830. function SkeletonHelper( object ) {
  28831. var bones = getBoneList( object );
  28832. var geometry = new BufferGeometry();
  28833. var vertices = [];
  28834. var colors = [];
  28835. var color1 = new Color( 0, 0, 1 );
  28836. var color2 = new Color( 0, 1, 0 );
  28837. for ( var i = 0; i < bones.length; i ++ ) {
  28838. var bone = bones[ i ];
  28839. if ( bone.parent && bone.parent.isBone ) {
  28840. vertices.push( 0, 0, 0 );
  28841. vertices.push( 0, 0, 0 );
  28842. colors.push( color1.r, color1.g, color1.b );
  28843. colors.push( color2.r, color2.g, color2.b );
  28844. }
  28845. }
  28846. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28847. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28848. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  28849. LineSegments.call( this, geometry, material );
  28850. this.root = object;
  28851. this.bones = bones;
  28852. this.matrix = object.matrixWorld;
  28853. this.matrixAutoUpdate = false;
  28854. this.onBeforeRender();
  28855. }
  28856. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  28857. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28858. SkeletonHelper.prototype.onBeforeRender = function () {
  28859. var vector = new Vector3();
  28860. var boneMatrix = new Matrix4();
  28861. var matrixWorldInv = new Matrix4();
  28862. return function onBeforeRender() {
  28863. var bones = this.bones;
  28864. var geometry = this.geometry;
  28865. var position = geometry.getAttribute( 'position' );
  28866. matrixWorldInv.getInverse( this.root.matrixWorld );
  28867. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  28868. var bone = bones[ i ];
  28869. if ( bone.parent && bone.parent.isBone ) {
  28870. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  28871. vector.setFromMatrixPosition( boneMatrix );
  28872. position.setXYZ( j, vector.x, vector.y, vector.z );
  28873. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  28874. vector.setFromMatrixPosition( boneMatrix );
  28875. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  28876. j += 2;
  28877. }
  28878. }
  28879. geometry.getAttribute( 'position' ).needsUpdate = true;
  28880. };
  28881. }();
  28882. /**
  28883. * @author alteredq / http://alteredqualia.com/
  28884. * @author mrdoob / http://mrdoob.com/
  28885. */
  28886. function PointLightHelper( light, sphereSize, color ) {
  28887. this.light = light;
  28888. this.light.updateMatrixWorld();
  28889. this.color = color;
  28890. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28891. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  28892. Mesh.call( this, geometry, material );
  28893. this.matrix = this.light.matrixWorld;
  28894. this.matrixAutoUpdate = false;
  28895. this.update();
  28896. /*
  28897. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28898. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28899. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28900. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28901. var d = light.distance;
  28902. if ( d === 0.0 ) {
  28903. this.lightDistance.visible = false;
  28904. } else {
  28905. this.lightDistance.scale.set( d, d, d );
  28906. }
  28907. this.add( this.lightDistance );
  28908. */
  28909. }
  28910. PointLightHelper.prototype = Object.create( Mesh.prototype );
  28911. PointLightHelper.prototype.constructor = PointLightHelper;
  28912. PointLightHelper.prototype.dispose = function () {
  28913. this.geometry.dispose();
  28914. this.material.dispose();
  28915. };
  28916. PointLightHelper.prototype.update = function () {
  28917. if ( this.color !== undefined ) {
  28918. this.material.color.set( this.color );
  28919. } else {
  28920. this.material.color.copy( this.light.color );
  28921. }
  28922. /*
  28923. var d = this.light.distance;
  28924. if ( d === 0.0 ) {
  28925. this.lightDistance.visible = false;
  28926. } else {
  28927. this.lightDistance.visible = true;
  28928. this.lightDistance.scale.set( d, d, d );
  28929. }
  28930. */
  28931. };
  28932. /**
  28933. * @author abelnation / http://github.com/abelnation
  28934. * @author Mugen87 / http://github.com/Mugen87
  28935. * @author WestLangley / http://github.com/WestLangley
  28936. */
  28937. function RectAreaLightHelper( light, color ) {
  28938. Object3D.call( this );
  28939. this.light = light;
  28940. this.light.updateMatrixWorld();
  28941. this.matrix = light.matrixWorld;
  28942. this.matrixAutoUpdate = false;
  28943. this.color = color;
  28944. var material = new LineBasicMaterial( { fog: false } );
  28945. var geometry = new BufferGeometry();
  28946. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  28947. this.line = new Line( geometry, material );
  28948. this.add( this.line );
  28949. this.update();
  28950. }
  28951. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  28952. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28953. RectAreaLightHelper.prototype.dispose = function () {
  28954. this.children[ 0 ].geometry.dispose();
  28955. this.children[ 0 ].material.dispose();
  28956. };
  28957. RectAreaLightHelper.prototype.update = function () {
  28958. // calculate new dimensions of the helper
  28959. var hx = this.light.width * 0.5;
  28960. var hy = this.light.height * 0.5;
  28961. var position = this.line.geometry.attributes.position;
  28962. var array = position.array;
  28963. // update vertices
  28964. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  28965. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  28966. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  28967. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  28968. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  28969. position.needsUpdate = true;
  28970. if ( this.color !== undefined ) {
  28971. this.line.material.color.set( this.color );
  28972. } else {
  28973. this.line.material.color.copy( this.light.color );
  28974. }
  28975. };
  28976. /**
  28977. * @author alteredq / http://alteredqualia.com/
  28978. * @author mrdoob / http://mrdoob.com/
  28979. * @author Mugen87 / https://github.com/Mugen87
  28980. */
  28981. function HemisphereLightHelper( light, size, color ) {
  28982. Object3D.call( this );
  28983. this.light = light;
  28984. this.light.updateMatrixWorld();
  28985. this.matrix = light.matrixWorld;
  28986. this.matrixAutoUpdate = false;
  28987. this.color = color;
  28988. var geometry = new OctahedronBufferGeometry( size );
  28989. geometry.rotateY( Math.PI * 0.5 );
  28990. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  28991. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  28992. var position = geometry.getAttribute( 'position' );
  28993. var colors = new Float32Array( position.count * 3 );
  28994. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28995. this.add( new Mesh( geometry, this.material ) );
  28996. this.update();
  28997. }
  28998. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  28999. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  29000. HemisphereLightHelper.prototype.dispose = function () {
  29001. this.children[ 0 ].geometry.dispose();
  29002. this.children[ 0 ].material.dispose();
  29003. };
  29004. HemisphereLightHelper.prototype.update = function () {
  29005. var vector = new Vector3();
  29006. var color1 = new Color();
  29007. var color2 = new Color();
  29008. return function update() {
  29009. var mesh = this.children[ 0 ];
  29010. if ( this.color !== undefined ) {
  29011. this.material.color.set( this.color );
  29012. } else {
  29013. var colors = mesh.geometry.getAttribute( 'color' );
  29014. color1.copy( this.light.color );
  29015. color2.copy( this.light.groundColor );
  29016. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  29017. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  29018. colors.setXYZ( i, color.r, color.g, color.b );
  29019. }
  29020. colors.needsUpdate = true;
  29021. }
  29022. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29023. };
  29024. }();
  29025. /**
  29026. * @author mrdoob / http://mrdoob.com/
  29027. */
  29028. function GridHelper( size, divisions, color1, color2 ) {
  29029. size = size || 10;
  29030. divisions = divisions || 10;
  29031. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  29032. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  29033. var center = divisions / 2;
  29034. var step = size / divisions;
  29035. var halfSize = size / 2;
  29036. var vertices = [], colors = [];
  29037. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29038. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29039. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29040. var color = i === center ? color1 : color2;
  29041. color.toArray( colors, j ); j += 3;
  29042. color.toArray( colors, j ); j += 3;
  29043. color.toArray( colors, j ); j += 3;
  29044. color.toArray( colors, j ); j += 3;
  29045. }
  29046. var geometry = new BufferGeometry();
  29047. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29048. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29049. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  29050. LineSegments.call( this, geometry, material );
  29051. }
  29052. GridHelper.prototype = Object.create( LineSegments.prototype );
  29053. GridHelper.prototype.constructor = GridHelper;
  29054. /**
  29055. * @author mrdoob / http://mrdoob.com/
  29056. * @author Mugen87 / http://github.com/Mugen87
  29057. * @author Hectate / http://www.github.com/Hectate
  29058. */
  29059. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  29060. radius = radius || 10;
  29061. radials = radials || 16;
  29062. circles = circles || 8;
  29063. divisions = divisions || 64;
  29064. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  29065. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  29066. var vertices = [];
  29067. var colors = [];
  29068. var x, z;
  29069. var v, i, j, r, color;
  29070. // create the radials
  29071. for ( i = 0; i <= radials; i ++ ) {
  29072. v = ( i / radials ) * ( Math.PI * 2 );
  29073. x = Math.sin( v ) * radius;
  29074. z = Math.cos( v ) * radius;
  29075. vertices.push( 0, 0, 0 );
  29076. vertices.push( x, 0, z );
  29077. color = ( i & 1 ) ? color1 : color2;
  29078. colors.push( color.r, color.g, color.b );
  29079. colors.push( color.r, color.g, color.b );
  29080. }
  29081. // create the circles
  29082. for ( i = 0; i <= circles; i ++ ) {
  29083. color = ( i & 1 ) ? color1 : color2;
  29084. r = radius - ( radius / circles * i );
  29085. for ( j = 0; j < divisions; j ++ ) {
  29086. // first vertex
  29087. v = ( j / divisions ) * ( Math.PI * 2 );
  29088. x = Math.sin( v ) * r;
  29089. z = Math.cos( v ) * r;
  29090. vertices.push( x, 0, z );
  29091. colors.push( color.r, color.g, color.b );
  29092. // second vertex
  29093. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29094. x = Math.sin( v ) * r;
  29095. z = Math.cos( v ) * r;
  29096. vertices.push( x, 0, z );
  29097. colors.push( color.r, color.g, color.b );
  29098. }
  29099. }
  29100. var geometry = new BufferGeometry();
  29101. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29102. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29103. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  29104. LineSegments.call( this, geometry, material );
  29105. }
  29106. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  29107. PolarGridHelper.prototype.constructor = PolarGridHelper;
  29108. /**
  29109. * @author mrdoob / http://mrdoob.com/
  29110. * @author WestLangley / http://github.com/WestLangley
  29111. */
  29112. function FaceNormalsHelper( object, size, hex, linewidth ) {
  29113. // FaceNormalsHelper only supports THREE.Geometry
  29114. this.object = object;
  29115. this.size = ( size !== undefined ) ? size : 1;
  29116. var color = ( hex !== undefined ) ? hex : 0xffff00;
  29117. var width = ( linewidth !== undefined ) ? linewidth : 1;
  29118. //
  29119. var nNormals = 0;
  29120. var objGeometry = this.object.geometry;
  29121. if ( objGeometry && objGeometry.isGeometry ) {
  29122. nNormals = objGeometry.faces.length;
  29123. } else {
  29124. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  29125. }
  29126. //
  29127. var geometry = new BufferGeometry();
  29128. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  29129. geometry.addAttribute( 'position', positions );
  29130. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  29131. //
  29132. this.matrixAutoUpdate = false;
  29133. this.update();
  29134. }
  29135. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  29136. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  29137. FaceNormalsHelper.prototype.update = ( function () {
  29138. var v1 = new Vector3();
  29139. var v2 = new Vector3();
  29140. var normalMatrix = new Matrix3();
  29141. return function update() {
  29142. this.object.updateMatrixWorld( true );
  29143. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  29144. var matrixWorld = this.object.matrixWorld;
  29145. var position = this.geometry.attributes.position;
  29146. //
  29147. var objGeometry = this.object.geometry;
  29148. var vertices = objGeometry.vertices;
  29149. var faces = objGeometry.faces;
  29150. var idx = 0;
  29151. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  29152. var face = faces[ i ];
  29153. var normal = face.normal;
  29154. v1.copy( vertices[ face.a ] )
  29155. .add( vertices[ face.b ] )
  29156. .add( vertices[ face.c ] )
  29157. .divideScalar( 3 )
  29158. .applyMatrix4( matrixWorld );
  29159. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29160. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29161. idx = idx + 1;
  29162. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29163. idx = idx + 1;
  29164. }
  29165. position.needsUpdate = true;
  29166. };
  29167. }() );
  29168. /**
  29169. * @author alteredq / http://alteredqualia.com/
  29170. * @author mrdoob / http://mrdoob.com/
  29171. * @author WestLangley / http://github.com/WestLangley
  29172. */
  29173. function DirectionalLightHelper( light, size, color ) {
  29174. Object3D.call( this );
  29175. this.light = light;
  29176. this.light.updateMatrixWorld();
  29177. this.matrix = light.matrixWorld;
  29178. this.matrixAutoUpdate = false;
  29179. this.color = color;
  29180. if ( size === undefined ) size = 1;
  29181. var geometry = new BufferGeometry();
  29182. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  29183. - size, size, 0,
  29184. size, size, 0,
  29185. size, - size, 0,
  29186. - size, - size, 0,
  29187. - size, size, 0
  29188. ], 3 ) );
  29189. var material = new LineBasicMaterial( { fog: false } );
  29190. this.lightPlane = new Line( geometry, material );
  29191. this.add( this.lightPlane );
  29192. geometry = new BufferGeometry();
  29193. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29194. this.targetLine = new Line( geometry, material );
  29195. this.add( this.targetLine );
  29196. this.update();
  29197. }
  29198. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  29199. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  29200. DirectionalLightHelper.prototype.dispose = function () {
  29201. this.lightPlane.geometry.dispose();
  29202. this.lightPlane.material.dispose();
  29203. this.targetLine.geometry.dispose();
  29204. this.targetLine.material.dispose();
  29205. };
  29206. DirectionalLightHelper.prototype.update = function () {
  29207. var v1 = new Vector3();
  29208. var v2 = new Vector3();
  29209. var v3 = new Vector3();
  29210. return function update() {
  29211. v1.setFromMatrixPosition( this.light.matrixWorld );
  29212. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29213. v3.subVectors( v2, v1 );
  29214. this.lightPlane.lookAt( v3 );
  29215. if ( this.color !== undefined ) {
  29216. this.lightPlane.material.color.set( this.color );
  29217. this.targetLine.material.color.set( this.color );
  29218. } else {
  29219. this.lightPlane.material.color.copy( this.light.color );
  29220. this.targetLine.material.color.copy( this.light.color );
  29221. }
  29222. this.targetLine.lookAt( v3 );
  29223. this.targetLine.scale.z = v3.length();
  29224. };
  29225. }();
  29226. /**
  29227. * @author alteredq / http://alteredqualia.com/
  29228. * @author Mugen87 / https://github.com/Mugen87
  29229. *
  29230. * - shows frustum, line of sight and up of the camera
  29231. * - suitable for fast updates
  29232. * - based on frustum visualization in lightgl.js shadowmap example
  29233. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29234. */
  29235. function CameraHelper( camera ) {
  29236. var geometry = new BufferGeometry();
  29237. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  29238. var vertices = [];
  29239. var colors = [];
  29240. var pointMap = {};
  29241. // colors
  29242. var colorFrustum = new Color( 0xffaa00 );
  29243. var colorCone = new Color( 0xff0000 );
  29244. var colorUp = new Color( 0x00aaff );
  29245. var colorTarget = new Color( 0xffffff );
  29246. var colorCross = new Color( 0x333333 );
  29247. // near
  29248. addLine( "n1", "n2", colorFrustum );
  29249. addLine( "n2", "n4", colorFrustum );
  29250. addLine( "n4", "n3", colorFrustum );
  29251. addLine( "n3", "n1", colorFrustum );
  29252. // far
  29253. addLine( "f1", "f2", colorFrustum );
  29254. addLine( "f2", "f4", colorFrustum );
  29255. addLine( "f4", "f3", colorFrustum );
  29256. addLine( "f3", "f1", colorFrustum );
  29257. // sides
  29258. addLine( "n1", "f1", colorFrustum );
  29259. addLine( "n2", "f2", colorFrustum );
  29260. addLine( "n3", "f3", colorFrustum );
  29261. addLine( "n4", "f4", colorFrustum );
  29262. // cone
  29263. addLine( "p", "n1", colorCone );
  29264. addLine( "p", "n2", colorCone );
  29265. addLine( "p", "n3", colorCone );
  29266. addLine( "p", "n4", colorCone );
  29267. // up
  29268. addLine( "u1", "u2", colorUp );
  29269. addLine( "u2", "u3", colorUp );
  29270. addLine( "u3", "u1", colorUp );
  29271. // target
  29272. addLine( "c", "t", colorTarget );
  29273. addLine( "p", "c", colorCross );
  29274. // cross
  29275. addLine( "cn1", "cn2", colorCross );
  29276. addLine( "cn3", "cn4", colorCross );
  29277. addLine( "cf1", "cf2", colorCross );
  29278. addLine( "cf3", "cf4", colorCross );
  29279. function addLine( a, b, color ) {
  29280. addPoint( a, color );
  29281. addPoint( b, color );
  29282. }
  29283. function addPoint( id, color ) {
  29284. vertices.push( 0, 0, 0 );
  29285. colors.push( color.r, color.g, color.b );
  29286. if ( pointMap[ id ] === undefined ) {
  29287. pointMap[ id ] = [];
  29288. }
  29289. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29290. }
  29291. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29292. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29293. LineSegments.call( this, geometry, material );
  29294. this.camera = camera;
  29295. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29296. this.matrix = camera.matrixWorld;
  29297. this.matrixAutoUpdate = false;
  29298. this.pointMap = pointMap;
  29299. this.update();
  29300. }
  29301. CameraHelper.prototype = Object.create( LineSegments.prototype );
  29302. CameraHelper.prototype.constructor = CameraHelper;
  29303. CameraHelper.prototype.update = function () {
  29304. var geometry, pointMap;
  29305. var vector = new Vector3();
  29306. var camera = new Camera();
  29307. function setPoint( point, x, y, z ) {
  29308. vector.set( x, y, z ).unproject( camera );
  29309. var points = pointMap[ point ];
  29310. if ( points !== undefined ) {
  29311. var position = geometry.getAttribute( 'position' );
  29312. for ( var i = 0, l = points.length; i < l; i ++ ) {
  29313. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  29314. }
  29315. }
  29316. }
  29317. return function update() {
  29318. geometry = this.geometry;
  29319. pointMap = this.pointMap;
  29320. var w = 1, h = 1;
  29321. // we need just camera projection matrix
  29322. // world matrix must be identity
  29323. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  29324. // center / target
  29325. setPoint( "c", 0, 0, - 1 );
  29326. setPoint( "t", 0, 0, 1 );
  29327. // near
  29328. setPoint( "n1", - w, - h, - 1 );
  29329. setPoint( "n2", w, - h, - 1 );
  29330. setPoint( "n3", - w, h, - 1 );
  29331. setPoint( "n4", w, h, - 1 );
  29332. // far
  29333. setPoint( "f1", - w, - h, 1 );
  29334. setPoint( "f2", w, - h, 1 );
  29335. setPoint( "f3", - w, h, 1 );
  29336. setPoint( "f4", w, h, 1 );
  29337. // up
  29338. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  29339. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  29340. setPoint( "u3", 0, h * 2, - 1 );
  29341. // cross
  29342. setPoint( "cf1", - w, 0, 1 );
  29343. setPoint( "cf2", w, 0, 1 );
  29344. setPoint( "cf3", 0, - h, 1 );
  29345. setPoint( "cf4", 0, h, 1 );
  29346. setPoint( "cn1", - w, 0, - 1 );
  29347. setPoint( "cn2", w, 0, - 1 );
  29348. setPoint( "cn3", 0, - h, - 1 );
  29349. setPoint( "cn4", 0, h, - 1 );
  29350. geometry.getAttribute( 'position' ).needsUpdate = true;
  29351. };
  29352. }();
  29353. /**
  29354. * @author mrdoob / http://mrdoob.com/
  29355. * @author Mugen87 / http://github.com/Mugen87
  29356. */
  29357. function BoxHelper( object, color ) {
  29358. this.object = object;
  29359. if ( color === undefined ) color = 0xffff00;
  29360. 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 ] );
  29361. var positions = new Float32Array( 8 * 3 );
  29362. var geometry = new BufferGeometry();
  29363. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29364. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29365. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  29366. this.matrixAutoUpdate = false;
  29367. this.update();
  29368. }
  29369. BoxHelper.prototype = Object.create( LineSegments.prototype );
  29370. BoxHelper.prototype.constructor = BoxHelper;
  29371. BoxHelper.prototype.update = ( function () {
  29372. var box = new Box3();
  29373. return function update( object ) {
  29374. if ( object !== undefined ) {
  29375. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29376. }
  29377. if ( this.object !== undefined ) {
  29378. box.setFromObject( this.object );
  29379. }
  29380. if ( box.isEmpty() ) return;
  29381. var min = box.min;
  29382. var max = box.max;
  29383. /*
  29384. 5____4
  29385. 1/___0/|
  29386. | 6__|_7
  29387. 2/___3/
  29388. 0: max.x, max.y, max.z
  29389. 1: min.x, max.y, max.z
  29390. 2: min.x, min.y, max.z
  29391. 3: max.x, min.y, max.z
  29392. 4: max.x, max.y, min.z
  29393. 5: min.x, max.y, min.z
  29394. 6: min.x, min.y, min.z
  29395. 7: max.x, min.y, min.z
  29396. */
  29397. var position = this.geometry.attributes.position;
  29398. var array = position.array;
  29399. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29400. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29401. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29402. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29403. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29404. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29405. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29406. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29407. position.needsUpdate = true;
  29408. this.geometry.computeBoundingSphere();
  29409. };
  29410. } )();
  29411. BoxHelper.prototype.setFromObject = function ( object ) {
  29412. this.object = object;
  29413. this.update();
  29414. return this;
  29415. };
  29416. /**
  29417. * @author WestLangley / http://github.com/WestLangley
  29418. */
  29419. function Box3Helper( box, hex ) {
  29420. this.type = 'Box3Helper';
  29421. this.box = box;
  29422. var color = ( hex !== undefined ) ? hex : 0xffff00;
  29423. 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 ] );
  29424. 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 ];
  29425. var geometry = new BufferGeometry();
  29426. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29427. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29428. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  29429. this.geometry.computeBoundingSphere();
  29430. this.onBeforeRender();
  29431. }
  29432. Box3Helper.prototype = Object.create( LineSegments.prototype );
  29433. Box3Helper.prototype.constructor = Box3Helper;
  29434. Box3Helper.prototype.onBeforeRender = function () {
  29435. var box = this.box;
  29436. if ( box.isEmpty() ) return;
  29437. box.getCenter( this.position );
  29438. box.getSize( this.scale );
  29439. this.scale.multiplyScalar( 0.5 );
  29440. };
  29441. /**
  29442. * @author WestLangley / http://github.com/WestLangley
  29443. */
  29444. function PlaneHelper( plane, size, hex ) {
  29445. this.type = 'PlaneHelper';
  29446. this.plane = plane;
  29447. this.size = ( size === undefined ) ? 1 : size;
  29448. var color = ( hex !== undefined ) ? hex : 0xffff00;
  29449. 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 ];
  29450. var geometry = new BufferGeometry();
  29451. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29452. geometry.computeBoundingSphere();
  29453. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  29454. //
  29455. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  29456. var geometry2 = new BufferGeometry();
  29457. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29458. geometry2.computeBoundingSphere();
  29459. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  29460. //
  29461. this.onBeforeRender();
  29462. }
  29463. PlaneHelper.prototype = Object.create( Line.prototype );
  29464. PlaneHelper.prototype.constructor = PlaneHelper;
  29465. PlaneHelper.prototype.onBeforeRender = function () {
  29466. var scale = - this.plane.constant;
  29467. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  29468. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  29469. this.lookAt( this.plane.normal );
  29470. this.updateMatrixWorld();
  29471. };
  29472. /**
  29473. * @author WestLangley / http://github.com/WestLangley
  29474. * @author zz85 / http://github.com/zz85
  29475. * @author bhouston / http://clara.io
  29476. *
  29477. * Creates an arrow for visualizing directions
  29478. *
  29479. * Parameters:
  29480. * dir - Vector3
  29481. * origin - Vector3
  29482. * length - Number
  29483. * color - color in hex value
  29484. * headLength - Number
  29485. * headWidth - Number
  29486. */
  29487. var lineGeometry;
  29488. var coneGeometry;
  29489. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  29490. // dir is assumed to be normalized
  29491. Object3D.call( this );
  29492. if ( color === undefined ) color = 0xffff00;
  29493. if ( length === undefined ) length = 1;
  29494. if ( headLength === undefined ) headLength = 0.2 * length;
  29495. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29496. if ( lineGeometry === undefined ) {
  29497. lineGeometry = new BufferGeometry();
  29498. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29499. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  29500. coneGeometry.translate( 0, - 0.5, 0 );
  29501. }
  29502. this.position.copy( origin );
  29503. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  29504. this.line.matrixAutoUpdate = false;
  29505. this.add( this.line );
  29506. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  29507. this.cone.matrixAutoUpdate = false;
  29508. this.add( this.cone );
  29509. this.setDirection( dir );
  29510. this.setLength( length, headLength, headWidth );
  29511. }
  29512. ArrowHelper.prototype = Object.create( Object3D.prototype );
  29513. ArrowHelper.prototype.constructor = ArrowHelper;
  29514. ArrowHelper.prototype.setDirection = ( function () {
  29515. var axis = new Vector3();
  29516. var radians;
  29517. return function setDirection( dir ) {
  29518. // dir is assumed to be normalized
  29519. if ( dir.y > 0.99999 ) {
  29520. this.quaternion.set( 0, 0, 0, 1 );
  29521. } else if ( dir.y < - 0.99999 ) {
  29522. this.quaternion.set( 1, 0, 0, 0 );
  29523. } else {
  29524. axis.set( dir.z, 0, - dir.x ).normalize();
  29525. radians = Math.acos( dir.y );
  29526. this.quaternion.setFromAxisAngle( axis, radians );
  29527. }
  29528. };
  29529. }() );
  29530. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  29531. if ( headLength === undefined ) headLength = 0.2 * length;
  29532. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29533. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  29534. this.line.updateMatrix();
  29535. this.cone.scale.set( headWidth, headLength, headWidth );
  29536. this.cone.position.y = length;
  29537. this.cone.updateMatrix();
  29538. };
  29539. ArrowHelper.prototype.setColor = function ( color ) {
  29540. this.line.material.color.copy( color );
  29541. this.cone.material.color.copy( color );
  29542. };
  29543. /**
  29544. * @author sroucheray / http://sroucheray.org/
  29545. * @author mrdoob / http://mrdoob.com/
  29546. */
  29547. function AxisHelper( size ) {
  29548. size = size || 1;
  29549. var vertices = [
  29550. 0, 0, 0, size, 0, 0,
  29551. 0, 0, 0, 0, size, 0,
  29552. 0, 0, 0, 0, 0, size
  29553. ];
  29554. var colors = [
  29555. 1, 0, 0, 1, 0.6, 0,
  29556. 0, 1, 0, 0.6, 1, 0,
  29557. 0, 0, 1, 0, 0.6, 1
  29558. ];
  29559. var geometry = new BufferGeometry();
  29560. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29561. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29562. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  29563. LineSegments.call( this, geometry, material );
  29564. }
  29565. AxisHelper.prototype = Object.create( LineSegments.prototype );
  29566. AxisHelper.prototype.constructor = AxisHelper;
  29567. /**
  29568. * @author zz85 https://github.com/zz85
  29569. *
  29570. * Centripetal CatmullRom Curve - which is useful for avoiding
  29571. * cusps and self-intersections in non-uniform catmull rom curves.
  29572. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  29573. *
  29574. * curve.type accepts centripetal(default), chordal and catmullrom
  29575. * curve.tension is used for catmullrom which defaults to 0.5
  29576. */
  29577. /*
  29578. Based on an optimized c++ solution in
  29579. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  29580. - http://ideone.com/NoEbVM
  29581. This CubicPoly class could be used for reusing some variables and calculations,
  29582. but for three.js curve use, it could be possible inlined and flatten into a single function call
  29583. which can be placed in CurveUtils.
  29584. */
  29585. function CubicPoly() {
  29586. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  29587. /*
  29588. * Compute coefficients for a cubic polynomial
  29589. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  29590. * such that
  29591. * p(0) = x0, p(1) = x1
  29592. * and
  29593. * p'(0) = t0, p'(1) = t1.
  29594. */
  29595. function init( x0, x1, t0, t1 ) {
  29596. c0 = x0;
  29597. c1 = t0;
  29598. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  29599. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  29600. }
  29601. return {
  29602. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  29603. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  29604. },
  29605. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  29606. // compute tangents when parameterized in [t1,t2]
  29607. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  29608. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  29609. // rescale tangents for parametrization in [0,1]
  29610. t1 *= dt1;
  29611. t2 *= dt1;
  29612. init( x1, x2, t1, t2 );
  29613. },
  29614. calc: function ( t ) {
  29615. var t2 = t * t;
  29616. var t3 = t2 * t;
  29617. return c0 + c1 * t + c2 * t2 + c3 * t3;
  29618. }
  29619. };
  29620. }
  29621. //
  29622. var tmp = new Vector3();
  29623. var px = new CubicPoly();
  29624. var py = new CubicPoly();
  29625. var pz = new CubicPoly();
  29626. function CatmullRomCurve3( points ) {
  29627. Curve.call( this );
  29628. if ( points.length < 2 ) console.warn( 'THREE.CatmullRomCurve3: Points array needs at least two entries.' );
  29629. this.points = points || [];
  29630. this.closed = false;
  29631. }
  29632. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  29633. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  29634. CatmullRomCurve3.prototype.getPoint = function ( t ) {
  29635. var points = this.points;
  29636. var l = points.length;
  29637. var point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  29638. var intPoint = Math.floor( point );
  29639. var weight = point - intPoint;
  29640. if ( this.closed ) {
  29641. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  29642. } else if ( weight === 0 && intPoint === l - 1 ) {
  29643. intPoint = l - 2;
  29644. weight = 1;
  29645. }
  29646. var p0, p1, p2, p3; // 4 points
  29647. if ( this.closed || intPoint > 0 ) {
  29648. p0 = points[ ( intPoint - 1 ) % l ];
  29649. } else {
  29650. // extrapolate first point
  29651. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  29652. p0 = tmp;
  29653. }
  29654. p1 = points[ intPoint % l ];
  29655. p2 = points[ ( intPoint + 1 ) % l ];
  29656. if ( this.closed || intPoint + 2 < l ) {
  29657. p3 = points[ ( intPoint + 2 ) % l ];
  29658. } else {
  29659. // extrapolate last point
  29660. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  29661. p3 = tmp;
  29662. }
  29663. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  29664. // init Centripetal / Chordal Catmull-Rom
  29665. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  29666. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  29667. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  29668. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  29669. // safety check for repeated points
  29670. if ( dt1 < 1e-4 ) dt1 = 1.0;
  29671. if ( dt0 < 1e-4 ) dt0 = dt1;
  29672. if ( dt2 < 1e-4 ) dt2 = dt1;
  29673. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  29674. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  29675. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  29676. } else if ( this.type === 'catmullrom' ) {
  29677. var tension = this.tension !== undefined ? this.tension : 0.5;
  29678. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  29679. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  29680. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  29681. }
  29682. return new Vector3( px.calc( weight ), py.calc( weight ), pz.calc( weight ) );
  29683. };
  29684. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  29685. Curve.call( this );
  29686. this.v0 = v0;
  29687. this.v1 = v1;
  29688. this.v2 = v2;
  29689. this.v3 = v3;
  29690. }
  29691. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  29692. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  29693. CubicBezierCurve3.prototype.getPoint = function ( t ) {
  29694. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  29695. return new Vector3(
  29696. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  29697. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  29698. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  29699. );
  29700. };
  29701. function QuadraticBezierCurve3( v0, v1, v2 ) {
  29702. Curve.call( this );
  29703. this.v0 = v0;
  29704. this.v1 = v1;
  29705. this.v2 = v2;
  29706. }
  29707. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  29708. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  29709. QuadraticBezierCurve3.prototype.getPoint = function ( t ) {
  29710. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  29711. return new Vector3(
  29712. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  29713. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  29714. QuadraticBezier( t, v0.z, v1.z, v2.z )
  29715. );
  29716. };
  29717. function LineCurve3( v1, v2 ) {
  29718. Curve.call( this );
  29719. this.v1 = v1;
  29720. this.v2 = v2;
  29721. }
  29722. LineCurve3.prototype = Object.create( Curve.prototype );
  29723. LineCurve3.prototype.constructor = LineCurve3;
  29724. LineCurve3.prototype.getPoint = function ( t ) {
  29725. if ( t === 1 ) {
  29726. return this.v2.clone();
  29727. }
  29728. var vector = new Vector3();
  29729. vector.subVectors( this.v2, this.v1 ); // diff
  29730. vector.multiplyScalar( t );
  29731. vector.add( this.v1 );
  29732. return vector;
  29733. };
  29734. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  29735. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  29736. }
  29737. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  29738. ArcCurve.prototype.constructor = ArcCurve;
  29739. /**
  29740. * @author alteredq / http://alteredqualia.com/
  29741. */
  29742. var SceneUtils = {
  29743. createMultiMaterialObject: function ( geometry, materials ) {
  29744. var group = new Group();
  29745. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  29746. group.add( new Mesh( geometry, materials[ i ] ) );
  29747. }
  29748. return group;
  29749. },
  29750. detach: function ( child, parent, scene ) {
  29751. child.applyMatrix( parent.matrixWorld );
  29752. parent.remove( child );
  29753. scene.add( child );
  29754. },
  29755. attach: function ( child, scene, parent ) {
  29756. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  29757. scene.remove( child );
  29758. parent.add( child );
  29759. }
  29760. };
  29761. /**
  29762. * @author mrdoob / http://mrdoob.com/
  29763. */
  29764. function Face4( a, b, c, d, normal, color, materialIndex ) {
  29765. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  29766. return new Face3( a, b, c, normal, color, materialIndex );
  29767. }
  29768. var LineStrip = 0;
  29769. var LinePieces = 1;
  29770. function MeshFaceMaterial( materials ) {
  29771. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  29772. return materials;
  29773. }
  29774. function MultiMaterial( materials ) {
  29775. if ( materials === undefined ) materials = [];
  29776. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  29777. materials.isMultiMaterial = true;
  29778. materials.materials = materials;
  29779. materials.clone = function () {
  29780. return materials.slice();
  29781. };
  29782. return materials;
  29783. }
  29784. function PointCloud( geometry, material ) {
  29785. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29786. return new Points( geometry, material );
  29787. }
  29788. function Particle( material ) {
  29789. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29790. return new Sprite( material );
  29791. }
  29792. function ParticleSystem( geometry, material ) {
  29793. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29794. return new Points( geometry, material );
  29795. }
  29796. function PointCloudMaterial( parameters ) {
  29797. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29798. return new PointsMaterial( parameters );
  29799. }
  29800. function ParticleBasicMaterial( parameters ) {
  29801. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29802. return new PointsMaterial( parameters );
  29803. }
  29804. function ParticleSystemMaterial( parameters ) {
  29805. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29806. return new PointsMaterial( parameters );
  29807. }
  29808. function Vertex( x, y, z ) {
  29809. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29810. return new Vector3( x, y, z );
  29811. }
  29812. //
  29813. function DynamicBufferAttribute( array, itemSize ) {
  29814. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  29815. return new BufferAttribute( array, itemSize ).setDynamic( true );
  29816. }
  29817. function Int8Attribute( array, itemSize ) {
  29818. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29819. return new Int8BufferAttribute( array, itemSize );
  29820. }
  29821. function Uint8Attribute( array, itemSize ) {
  29822. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29823. return new Uint8BufferAttribute( array, itemSize );
  29824. }
  29825. function Uint8ClampedAttribute( array, itemSize ) {
  29826. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29827. return new Uint8ClampedBufferAttribute( array, itemSize );
  29828. }
  29829. function Int16Attribute( array, itemSize ) {
  29830. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29831. return new Int16BufferAttribute( array, itemSize );
  29832. }
  29833. function Uint16Attribute( array, itemSize ) {
  29834. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29835. return new Uint16BufferAttribute( array, itemSize );
  29836. }
  29837. function Int32Attribute( array, itemSize ) {
  29838. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29839. return new Int32BufferAttribute( array, itemSize );
  29840. }
  29841. function Uint32Attribute( array, itemSize ) {
  29842. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29843. return new Uint32BufferAttribute( array, itemSize );
  29844. }
  29845. function Float32Attribute( array, itemSize ) {
  29846. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29847. return new Float32BufferAttribute( array, itemSize );
  29848. }
  29849. function Float64Attribute( array, itemSize ) {
  29850. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29851. return new Float64BufferAttribute( array, itemSize );
  29852. }
  29853. //
  29854. Curve.create = function ( construct, getPoint ) {
  29855. console.log( 'THREE.Curve.create() has been deprecated' );
  29856. construct.prototype = Object.create( Curve.prototype );
  29857. construct.prototype.constructor = construct;
  29858. construct.prototype.getPoint = getPoint;
  29859. return construct;
  29860. };
  29861. //
  29862. function ClosedSplineCurve3( points ) {
  29863. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29864. CatmullRomCurve3.call( this, points );
  29865. this.type = 'catmullrom';
  29866. this.closed = true;
  29867. }
  29868. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29869. //
  29870. function SplineCurve3( points ) {
  29871. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29872. CatmullRomCurve3.call( this, points );
  29873. this.type = 'catmullrom';
  29874. }
  29875. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29876. //
  29877. function Spline( points ) {
  29878. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  29879. CatmullRomCurve3.call( this, points );
  29880. this.type = 'catmullrom';
  29881. }
  29882. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  29883. Object.assign( Spline.prototype, {
  29884. initFromArray: function ( a ) {
  29885. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  29886. },
  29887. getControlPointsArray: function ( optionalTarget ) {
  29888. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  29889. },
  29890. reparametrizeByArcLength: function ( samplingCoef ) {
  29891. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  29892. }
  29893. } );
  29894. //
  29895. function BoundingBoxHelper( object, color ) {
  29896. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29897. return new BoxHelper( object, color );
  29898. }
  29899. function EdgesHelper( object, hex ) {
  29900. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29901. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29902. }
  29903. GridHelper.prototype.setColors = function () {
  29904. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29905. };
  29906. SkeletonHelper.prototype.update = function () {
  29907. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  29908. };
  29909. function WireframeHelper( object, hex ) {
  29910. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29911. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29912. }
  29913. //
  29914. function XHRLoader( manager ) {
  29915. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29916. return new FileLoader( manager );
  29917. }
  29918. function BinaryTextureLoader( manager ) {
  29919. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  29920. return new DataTextureLoader( manager );
  29921. }
  29922. //
  29923. Object.assign( Box2.prototype, {
  29924. center: function ( optionalTarget ) {
  29925. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29926. return this.getCenter( optionalTarget );
  29927. },
  29928. empty: function () {
  29929. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29930. return this.isEmpty();
  29931. },
  29932. isIntersectionBox: function ( box ) {
  29933. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29934. return this.intersectsBox( box );
  29935. },
  29936. size: function ( optionalTarget ) {
  29937. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29938. return this.getSize( optionalTarget );
  29939. }
  29940. } );
  29941. Object.assign( Box3.prototype, {
  29942. center: function ( optionalTarget ) {
  29943. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29944. return this.getCenter( optionalTarget );
  29945. },
  29946. empty: function () {
  29947. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29948. return this.isEmpty();
  29949. },
  29950. isIntersectionBox: function ( box ) {
  29951. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29952. return this.intersectsBox( box );
  29953. },
  29954. isIntersectionSphere: function ( sphere ) {
  29955. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29956. return this.intersectsSphere( sphere );
  29957. },
  29958. size: function ( optionalTarget ) {
  29959. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29960. return this.getSize( optionalTarget );
  29961. }
  29962. } );
  29963. Line3.prototype.center = function ( optionalTarget ) {
  29964. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29965. return this.getCenter( optionalTarget );
  29966. };
  29967. _Math.random16 = function () {
  29968. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  29969. return Math.random();
  29970. };
  29971. Object.assign( Matrix3.prototype, {
  29972. flattenToArrayOffset: function ( array, offset ) {
  29973. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29974. return this.toArray( array, offset );
  29975. },
  29976. multiplyVector3: function ( vector ) {
  29977. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29978. return vector.applyMatrix3( this );
  29979. },
  29980. multiplyVector3Array: function ( a ) {
  29981. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  29982. },
  29983. applyToBuffer: function( buffer, offset, length ) {
  29984. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29985. return this.applyToBufferAttribute( buffer );
  29986. },
  29987. applyToVector3Array: function( array, offset, length ) {
  29988. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  29989. }
  29990. } );
  29991. Object.assign( Matrix4.prototype, {
  29992. extractPosition: function ( m ) {
  29993. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29994. return this.copyPosition( m );
  29995. },
  29996. flattenToArrayOffset: function ( array, offset ) {
  29997. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29998. return this.toArray( array, offset );
  29999. },
  30000. getPosition: function () {
  30001. var v1;
  30002. return function getPosition() {
  30003. if ( v1 === undefined ) v1 = new Vector3();
  30004. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  30005. return v1.setFromMatrixColumn( this, 3 );
  30006. };
  30007. }(),
  30008. setRotationFromQuaternion: function ( q ) {
  30009. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  30010. return this.makeRotationFromQuaternion( q );
  30011. },
  30012. multiplyToArray: function () {
  30013. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  30014. },
  30015. multiplyVector3: function ( vector ) {
  30016. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30017. return vector.applyMatrix4( this );
  30018. },
  30019. multiplyVector4: function ( vector ) {
  30020. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30021. return vector.applyMatrix4( this );
  30022. },
  30023. multiplyVector3Array: function ( a ) {
  30024. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  30025. },
  30026. rotateAxis: function ( v ) {
  30027. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  30028. v.transformDirection( this );
  30029. },
  30030. crossVector: function ( vector ) {
  30031. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30032. return vector.applyMatrix4( this );
  30033. },
  30034. translate: function () {
  30035. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  30036. },
  30037. rotateX: function () {
  30038. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  30039. },
  30040. rotateY: function () {
  30041. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  30042. },
  30043. rotateZ: function () {
  30044. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  30045. },
  30046. rotateByAxis: function () {
  30047. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  30048. },
  30049. applyToBuffer: function( buffer, offset, length ) {
  30050. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  30051. return this.applyToBufferAttribute( buffer );
  30052. },
  30053. applyToVector3Array: function( array, offset, length ) {
  30054. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  30055. },
  30056. makeFrustum: function( left, right, bottom, top, near, far ) {
  30057. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  30058. return this.makePerspective( left, right, top, bottom, near, far );
  30059. }
  30060. } );
  30061. Plane.prototype.isIntersectionLine = function ( line ) {
  30062. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  30063. return this.intersectsLine( line );
  30064. };
  30065. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  30066. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  30067. return vector.applyQuaternion( this );
  30068. };
  30069. Object.assign( Ray.prototype, {
  30070. isIntersectionBox: function ( box ) {
  30071. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30072. return this.intersectsBox( box );
  30073. },
  30074. isIntersectionPlane: function ( plane ) {
  30075. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  30076. return this.intersectsPlane( plane );
  30077. },
  30078. isIntersectionSphere: function ( sphere ) {
  30079. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30080. return this.intersectsSphere( sphere );
  30081. }
  30082. } );
  30083. Object.assign( Shape.prototype, {
  30084. extrude: function ( options ) {
  30085. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  30086. return new ExtrudeGeometry( this, options );
  30087. },
  30088. makeGeometry: function ( options ) {
  30089. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  30090. return new ShapeGeometry( this, options );
  30091. }
  30092. } );
  30093. Object.assign( Vector2.prototype, {
  30094. fromAttribute: function ( attribute, index, offset ) {
  30095. console.error( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30096. return this.fromBufferAttribute( attribute, index, offset );
  30097. }
  30098. } );
  30099. Object.assign( Vector3.prototype, {
  30100. setEulerFromRotationMatrix: function () {
  30101. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  30102. },
  30103. setEulerFromQuaternion: function () {
  30104. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  30105. },
  30106. getPositionFromMatrix: function ( m ) {
  30107. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  30108. return this.setFromMatrixPosition( m );
  30109. },
  30110. getScaleFromMatrix: function ( m ) {
  30111. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  30112. return this.setFromMatrixScale( m );
  30113. },
  30114. getColumnFromMatrix: function ( index, matrix ) {
  30115. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  30116. return this.setFromMatrixColumn( matrix, index );
  30117. },
  30118. applyProjection: function ( m ) {
  30119. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  30120. return this.applyMatrix4( m );
  30121. },
  30122. fromAttribute: function ( attribute, index, offset ) {
  30123. console.error( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30124. return this.fromBufferAttribute( attribute, index, offset );
  30125. }
  30126. } );
  30127. Object.assign( Vector4.prototype, {
  30128. fromAttribute: function ( attribute, index, offset ) {
  30129. console.error( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30130. return this.fromBufferAttribute( attribute, index, offset );
  30131. }
  30132. } );
  30133. //
  30134. Geometry.prototype.computeTangents = function () {
  30135. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  30136. };
  30137. Object.assign( Object3D.prototype, {
  30138. getChildByName: function ( name ) {
  30139. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  30140. return this.getObjectByName( name );
  30141. },
  30142. renderDepth: function () {
  30143. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  30144. },
  30145. translate: function ( distance, axis ) {
  30146. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  30147. return this.translateOnAxis( axis, distance );
  30148. }
  30149. } );
  30150. Object.defineProperties( Object3D.prototype, {
  30151. eulerOrder: {
  30152. get: function () {
  30153. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30154. return this.rotation.order;
  30155. },
  30156. set: function ( value ) {
  30157. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30158. this.rotation.order = value;
  30159. }
  30160. },
  30161. useQuaternion: {
  30162. get: function () {
  30163. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30164. },
  30165. set: function () {
  30166. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30167. }
  30168. }
  30169. } );
  30170. Object.defineProperties( LOD.prototype, {
  30171. objects: {
  30172. get: function () {
  30173. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  30174. return this.levels;
  30175. }
  30176. }
  30177. } );
  30178. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  30179. get: function () {
  30180. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30181. },
  30182. set: function () {
  30183. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30184. }
  30185. } );
  30186. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  30187. get: function () {
  30188. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30189. return this.arcLengthDivisions;
  30190. },
  30191. set: function ( value ) {
  30192. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30193. this.arcLengthDivisions = value;
  30194. }
  30195. } );
  30196. //
  30197. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  30198. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  30199. "Use .setFocalLength and .filmGauge for a photographic setup." );
  30200. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  30201. this.setFocalLength( focalLength );
  30202. };
  30203. //
  30204. Object.defineProperties( Light.prototype, {
  30205. onlyShadow: {
  30206. set: function () {
  30207. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  30208. }
  30209. },
  30210. shadowCameraFov: {
  30211. set: function ( value ) {
  30212. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  30213. this.shadow.camera.fov = value;
  30214. }
  30215. },
  30216. shadowCameraLeft: {
  30217. set: function ( value ) {
  30218. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  30219. this.shadow.camera.left = value;
  30220. }
  30221. },
  30222. shadowCameraRight: {
  30223. set: function ( value ) {
  30224. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  30225. this.shadow.camera.right = value;
  30226. }
  30227. },
  30228. shadowCameraTop: {
  30229. set: function ( value ) {
  30230. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  30231. this.shadow.camera.top = value;
  30232. }
  30233. },
  30234. shadowCameraBottom: {
  30235. set: function ( value ) {
  30236. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  30237. this.shadow.camera.bottom = value;
  30238. }
  30239. },
  30240. shadowCameraNear: {
  30241. set: function ( value ) {
  30242. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  30243. this.shadow.camera.near = value;
  30244. }
  30245. },
  30246. shadowCameraFar: {
  30247. set: function ( value ) {
  30248. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  30249. this.shadow.camera.far = value;
  30250. }
  30251. },
  30252. shadowCameraVisible: {
  30253. set: function () {
  30254. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  30255. }
  30256. },
  30257. shadowBias: {
  30258. set: function ( value ) {
  30259. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  30260. this.shadow.bias = value;
  30261. }
  30262. },
  30263. shadowDarkness: {
  30264. set: function () {
  30265. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  30266. }
  30267. },
  30268. shadowMapWidth: {
  30269. set: function ( value ) {
  30270. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  30271. this.shadow.mapSize.width = value;
  30272. }
  30273. },
  30274. shadowMapHeight: {
  30275. set: function ( value ) {
  30276. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  30277. this.shadow.mapSize.height = value;
  30278. }
  30279. }
  30280. } );
  30281. //
  30282. Object.defineProperties( BufferAttribute.prototype, {
  30283. length: {
  30284. get: function () {
  30285. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  30286. return this.array.length;
  30287. }
  30288. }
  30289. } );
  30290. Object.assign( BufferGeometry.prototype, {
  30291. addIndex: function ( index ) {
  30292. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  30293. this.setIndex( index );
  30294. },
  30295. addDrawCall: function ( start, count, indexOffset ) {
  30296. if ( indexOffset !== undefined ) {
  30297. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  30298. }
  30299. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30300. this.addGroup( start, count );
  30301. },
  30302. clearDrawCalls: function () {
  30303. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30304. this.clearGroups();
  30305. },
  30306. computeTangents: function () {
  30307. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  30308. },
  30309. computeOffsets: function () {
  30310. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30311. }
  30312. } );
  30313. Object.defineProperties( BufferGeometry.prototype, {
  30314. drawcalls: {
  30315. get: function () {
  30316. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30317. return this.groups;
  30318. }
  30319. },
  30320. offsets: {
  30321. get: function () {
  30322. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30323. return this.groups;
  30324. }
  30325. }
  30326. } );
  30327. //
  30328. Object.defineProperties( Uniform.prototype, {
  30329. dynamic: {
  30330. set: function () {
  30331. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  30332. }
  30333. },
  30334. onUpdate: {
  30335. value: function () {
  30336. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30337. return this;
  30338. }
  30339. }
  30340. } );
  30341. //
  30342. Object.defineProperties( Material.prototype, {
  30343. wrapAround: {
  30344. get: function () {
  30345. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30346. },
  30347. set: function () {
  30348. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30349. }
  30350. },
  30351. wrapRGB: {
  30352. get: function () {
  30353. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30354. return new Color();
  30355. }
  30356. },
  30357. shading: {
  30358. get: function () {
  30359. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30360. },
  30361. set: function ( value ) {
  30362. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30363. this.flatShading = ( value === FlatShading );
  30364. }
  30365. }
  30366. } );
  30367. Object.defineProperties( MeshPhongMaterial.prototype, {
  30368. metal: {
  30369. get: function () {
  30370. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  30371. return false;
  30372. },
  30373. set: function () {
  30374. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  30375. }
  30376. }
  30377. } );
  30378. Object.defineProperties( ShaderMaterial.prototype, {
  30379. derivatives: {
  30380. get: function () {
  30381. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30382. return this.extensions.derivatives;
  30383. },
  30384. set: function ( value ) {
  30385. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30386. this.extensions.derivatives = value;
  30387. }
  30388. }
  30389. } );
  30390. //
  30391. Object.assign( WebGLRenderer.prototype, {
  30392. getCurrentRenderTarget: function () {
  30393. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30394. return this.getRenderTarget();
  30395. },
  30396. getMaxAnisotropy: function () {
  30397. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30398. return this.capabilities.getMaxAnisotropy();
  30399. },
  30400. getPrecision: function () {
  30401. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30402. return this.capabilities.precision;
  30403. },
  30404. supportsFloatTextures: function () {
  30405. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30406. return this.extensions.get( 'OES_texture_float' );
  30407. },
  30408. supportsHalfFloatTextures: function () {
  30409. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30410. return this.extensions.get( 'OES_texture_half_float' );
  30411. },
  30412. supportsStandardDerivatives: function () {
  30413. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30414. return this.extensions.get( 'OES_standard_derivatives' );
  30415. },
  30416. supportsCompressedTextureS3TC: function () {
  30417. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30418. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30419. },
  30420. supportsCompressedTexturePVRTC: function () {
  30421. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30422. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30423. },
  30424. supportsBlendMinMax: function () {
  30425. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30426. return this.extensions.get( 'EXT_blend_minmax' );
  30427. },
  30428. supportsVertexTextures: function () {
  30429. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30430. return this.capabilities.vertexTextures;
  30431. },
  30432. supportsInstancedArrays: function () {
  30433. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30434. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30435. },
  30436. enableScissorTest: function ( boolean ) {
  30437. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30438. this.setScissorTest( boolean );
  30439. },
  30440. initMaterial: function () {
  30441. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  30442. },
  30443. addPrePlugin: function () {
  30444. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  30445. },
  30446. addPostPlugin: function () {
  30447. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  30448. },
  30449. updateShadowMap: function () {
  30450. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  30451. }
  30452. } );
  30453. Object.defineProperties( WebGLRenderer.prototype, {
  30454. shadowMapEnabled: {
  30455. get: function () {
  30456. return this.shadowMap.enabled;
  30457. },
  30458. set: function ( value ) {
  30459. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  30460. this.shadowMap.enabled = value;
  30461. }
  30462. },
  30463. shadowMapType: {
  30464. get: function () {
  30465. return this.shadowMap.type;
  30466. },
  30467. set: function ( value ) {
  30468. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  30469. this.shadowMap.type = value;
  30470. }
  30471. },
  30472. shadowMapCullFace: {
  30473. get: function () {
  30474. return this.shadowMap.cullFace;
  30475. },
  30476. set: function ( value ) {
  30477. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  30478. this.shadowMap.cullFace = value;
  30479. }
  30480. }
  30481. } );
  30482. Object.defineProperties( WebGLShadowMap.prototype, {
  30483. cullFace: {
  30484. get: function () {
  30485. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  30486. },
  30487. set: function ( cullFace ) {
  30488. var value = ( cullFace !== CullFaceBack );
  30489. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  30490. this.renderReverseSided = value;
  30491. }
  30492. }
  30493. } );
  30494. //
  30495. Object.defineProperties( WebGLRenderTarget.prototype, {
  30496. wrapS: {
  30497. get: function () {
  30498. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30499. return this.texture.wrapS;
  30500. },
  30501. set: function ( value ) {
  30502. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  30503. this.texture.wrapS = value;
  30504. }
  30505. },
  30506. wrapT: {
  30507. get: function () {
  30508. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30509. return this.texture.wrapT;
  30510. },
  30511. set: function ( value ) {
  30512. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  30513. this.texture.wrapT = value;
  30514. }
  30515. },
  30516. magFilter: {
  30517. get: function () {
  30518. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30519. return this.texture.magFilter;
  30520. },
  30521. set: function ( value ) {
  30522. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  30523. this.texture.magFilter = value;
  30524. }
  30525. },
  30526. minFilter: {
  30527. get: function () {
  30528. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30529. return this.texture.minFilter;
  30530. },
  30531. set: function ( value ) {
  30532. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  30533. this.texture.minFilter = value;
  30534. }
  30535. },
  30536. anisotropy: {
  30537. get: function () {
  30538. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30539. return this.texture.anisotropy;
  30540. },
  30541. set: function ( value ) {
  30542. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  30543. this.texture.anisotropy = value;
  30544. }
  30545. },
  30546. offset: {
  30547. get: function () {
  30548. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30549. return this.texture.offset;
  30550. },
  30551. set: function ( value ) {
  30552. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  30553. this.texture.offset = value;
  30554. }
  30555. },
  30556. repeat: {
  30557. get: function () {
  30558. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30559. return this.texture.repeat;
  30560. },
  30561. set: function ( value ) {
  30562. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  30563. this.texture.repeat = value;
  30564. }
  30565. },
  30566. format: {
  30567. get: function () {
  30568. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30569. return this.texture.format;
  30570. },
  30571. set: function ( value ) {
  30572. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  30573. this.texture.format = value;
  30574. }
  30575. },
  30576. type: {
  30577. get: function () {
  30578. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30579. return this.texture.type;
  30580. },
  30581. set: function ( value ) {
  30582. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30583. this.texture.type = value;
  30584. }
  30585. },
  30586. generateMipmaps: {
  30587. get: function () {
  30588. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30589. return this.texture.generateMipmaps;
  30590. },
  30591. set: function ( value ) {
  30592. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30593. this.texture.generateMipmaps = value;
  30594. }
  30595. }
  30596. } );
  30597. //
  30598. Audio.prototype.load = function ( file ) {
  30599. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30600. var scope = this;
  30601. var audioLoader = new AudioLoader();
  30602. audioLoader.load( file, function ( buffer ) {
  30603. scope.setBuffer( buffer );
  30604. } );
  30605. return this;
  30606. };
  30607. AudioAnalyser.prototype.getData = function () {
  30608. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30609. return this.getFrequencyData();
  30610. };
  30611. //
  30612. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  30613. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  30614. return this.update( renderer, scene );
  30615. };
  30616. //
  30617. var GeometryUtils = {
  30618. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  30619. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  30620. var matrix;
  30621. if ( geometry2.isMesh ) {
  30622. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30623. matrix = geometry2.matrix;
  30624. geometry2 = geometry2.geometry;
  30625. }
  30626. geometry1.merge( geometry2, matrix, materialIndexOffset );
  30627. },
  30628. center: function ( geometry ) {
  30629. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  30630. return geometry.center();
  30631. }
  30632. };
  30633. var ImageUtils = {
  30634. crossOrigin: undefined,
  30635. loadTexture: function ( url, mapping, onLoad, onError ) {
  30636. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30637. var loader = new TextureLoader();
  30638. loader.setCrossOrigin( this.crossOrigin );
  30639. var texture = loader.load( url, onLoad, undefined, onError );
  30640. if ( mapping ) texture.mapping = mapping;
  30641. return texture;
  30642. },
  30643. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  30644. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30645. var loader = new CubeTextureLoader();
  30646. loader.setCrossOrigin( this.crossOrigin );
  30647. var texture = loader.load( urls, onLoad, undefined, onError );
  30648. if ( mapping ) texture.mapping = mapping;
  30649. return texture;
  30650. },
  30651. loadCompressedTexture: function () {
  30652. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30653. },
  30654. loadCompressedTextureCube: function () {
  30655. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30656. }
  30657. };
  30658. //
  30659. function Projector() {
  30660. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  30661. this.projectVector = function ( vector, camera ) {
  30662. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  30663. vector.project( camera );
  30664. };
  30665. this.unprojectVector = function ( vector, camera ) {
  30666. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  30667. vector.unproject( camera );
  30668. };
  30669. this.pickingRay = function () {
  30670. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  30671. };
  30672. }
  30673. //
  30674. function CanvasRenderer() {
  30675. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  30676. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  30677. this.clear = function () {};
  30678. this.render = function () {};
  30679. this.setClearColor = function () {};
  30680. this.setSize = function () {};
  30681. }
  30682. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  30683. exports.WebGLRenderTarget = WebGLRenderTarget;
  30684. exports.WebGLRenderer = WebGLRenderer;
  30685. exports.ShaderLib = ShaderLib;
  30686. exports.UniformsLib = UniformsLib;
  30687. exports.UniformsUtils = UniformsUtils;
  30688. exports.ShaderChunk = ShaderChunk;
  30689. exports.FogExp2 = FogExp2;
  30690. exports.Fog = Fog;
  30691. exports.Scene = Scene;
  30692. exports.LensFlare = LensFlare;
  30693. exports.Sprite = Sprite;
  30694. exports.LOD = LOD;
  30695. exports.SkinnedMesh = SkinnedMesh;
  30696. exports.Skeleton = Skeleton;
  30697. exports.Bone = Bone;
  30698. exports.Mesh = Mesh;
  30699. exports.LineSegments = LineSegments;
  30700. exports.LineLoop = LineLoop;
  30701. exports.Line = Line;
  30702. exports.Points = Points;
  30703. exports.Group = Group;
  30704. exports.VideoTexture = VideoTexture;
  30705. exports.DataTexture = DataTexture;
  30706. exports.CompressedTexture = CompressedTexture;
  30707. exports.CubeTexture = CubeTexture;
  30708. exports.CanvasTexture = CanvasTexture;
  30709. exports.DepthTexture = DepthTexture;
  30710. exports.Texture = Texture;
  30711. exports.CompressedTextureLoader = CompressedTextureLoader;
  30712. exports.DataTextureLoader = DataTextureLoader;
  30713. exports.CubeTextureLoader = CubeTextureLoader;
  30714. exports.TextureLoader = TextureLoader;
  30715. exports.ObjectLoader = ObjectLoader;
  30716. exports.MaterialLoader = MaterialLoader;
  30717. exports.BufferGeometryLoader = BufferGeometryLoader;
  30718. exports.DefaultLoadingManager = DefaultLoadingManager;
  30719. exports.LoadingManager = LoadingManager;
  30720. exports.JSONLoader = JSONLoader;
  30721. exports.ImageLoader = ImageLoader;
  30722. exports.FontLoader = FontLoader;
  30723. exports.FileLoader = FileLoader;
  30724. exports.Loader = Loader;
  30725. exports.Cache = Cache;
  30726. exports.AudioLoader = AudioLoader;
  30727. exports.SpotLightShadow = SpotLightShadow;
  30728. exports.SpotLight = SpotLight;
  30729. exports.PointLight = PointLight;
  30730. exports.RectAreaLight = RectAreaLight;
  30731. exports.HemisphereLight = HemisphereLight;
  30732. exports.DirectionalLightShadow = DirectionalLightShadow;
  30733. exports.DirectionalLight = DirectionalLight;
  30734. exports.AmbientLight = AmbientLight;
  30735. exports.LightShadow = LightShadow;
  30736. exports.Light = Light;
  30737. exports.StereoCamera = StereoCamera;
  30738. exports.PerspectiveCamera = PerspectiveCamera;
  30739. exports.OrthographicCamera = OrthographicCamera;
  30740. exports.CubeCamera = CubeCamera;
  30741. exports.ArrayCamera = ArrayCamera;
  30742. exports.Camera = Camera;
  30743. exports.AudioListener = AudioListener;
  30744. exports.PositionalAudio = PositionalAudio;
  30745. exports.AudioContext = AudioContext;
  30746. exports.AudioAnalyser = AudioAnalyser;
  30747. exports.Audio = Audio;
  30748. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30749. exports.StringKeyframeTrack = StringKeyframeTrack;
  30750. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30751. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30752. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  30753. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  30754. exports.PropertyMixer = PropertyMixer;
  30755. exports.PropertyBinding = PropertyBinding;
  30756. exports.KeyframeTrack = KeyframeTrack;
  30757. exports.AnimationUtils = AnimationUtils;
  30758. exports.AnimationObjectGroup = AnimationObjectGroup;
  30759. exports.AnimationMixer = AnimationMixer;
  30760. exports.AnimationClip = AnimationClip;
  30761. exports.Uniform = Uniform;
  30762. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30763. exports.BufferGeometry = BufferGeometry;
  30764. exports.GeometryIdCount = GeometryIdCount;
  30765. exports.Geometry = Geometry;
  30766. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30767. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30768. exports.InterleavedBuffer = InterleavedBuffer;
  30769. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  30770. exports.Face3 = Face3;
  30771. exports.Object3D = Object3D;
  30772. exports.Raycaster = Raycaster;
  30773. exports.Layers = Layers;
  30774. exports.EventDispatcher = EventDispatcher;
  30775. exports.Clock = Clock;
  30776. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30777. exports.LinearInterpolant = LinearInterpolant;
  30778. exports.DiscreteInterpolant = DiscreteInterpolant;
  30779. exports.CubicInterpolant = CubicInterpolant;
  30780. exports.Interpolant = Interpolant;
  30781. exports.Triangle = Triangle;
  30782. exports.Math = _Math;
  30783. exports.Spherical = Spherical;
  30784. exports.Cylindrical = Cylindrical;
  30785. exports.Plane = Plane;
  30786. exports.Frustum = Frustum;
  30787. exports.Sphere = Sphere;
  30788. exports.Ray = Ray;
  30789. exports.Matrix4 = Matrix4;
  30790. exports.Matrix3 = Matrix3;
  30791. exports.Box3 = Box3;
  30792. exports.Box2 = Box2;
  30793. exports.Line3 = Line3;
  30794. exports.Euler = Euler;
  30795. exports.Vector4 = Vector4;
  30796. exports.Vector3 = Vector3;
  30797. exports.Vector2 = Vector2;
  30798. exports.Quaternion = Quaternion;
  30799. exports.Color = Color;
  30800. exports.ImmediateRenderObject = ImmediateRenderObject;
  30801. exports.VertexNormalsHelper = VertexNormalsHelper;
  30802. exports.SpotLightHelper = SpotLightHelper;
  30803. exports.SkeletonHelper = SkeletonHelper;
  30804. exports.PointLightHelper = PointLightHelper;
  30805. exports.RectAreaLightHelper = RectAreaLightHelper;
  30806. exports.HemisphereLightHelper = HemisphereLightHelper;
  30807. exports.GridHelper = GridHelper;
  30808. exports.PolarGridHelper = PolarGridHelper;
  30809. exports.FaceNormalsHelper = FaceNormalsHelper;
  30810. exports.DirectionalLightHelper = DirectionalLightHelper;
  30811. exports.CameraHelper = CameraHelper;
  30812. exports.BoxHelper = BoxHelper;
  30813. exports.Box3Helper = Box3Helper;
  30814. exports.PlaneHelper = PlaneHelper;
  30815. exports.ArrowHelper = ArrowHelper;
  30816. exports.AxisHelper = AxisHelper;
  30817. exports.CatmullRomCurve3 = CatmullRomCurve3;
  30818. exports.CubicBezierCurve3 = CubicBezierCurve3;
  30819. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30820. exports.LineCurve3 = LineCurve3;
  30821. exports.ArcCurve = ArcCurve;
  30822. exports.EllipseCurve = EllipseCurve;
  30823. exports.SplineCurve = SplineCurve;
  30824. exports.CubicBezierCurve = CubicBezierCurve;
  30825. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30826. exports.LineCurve = LineCurve;
  30827. exports.Shape = Shape;
  30828. exports.Path = Path;
  30829. exports.ShapePath = ShapePath;
  30830. exports.Font = Font;
  30831. exports.CurvePath = CurvePath;
  30832. exports.Curve = Curve;
  30833. exports.ShapeUtils = ShapeUtils;
  30834. exports.SceneUtils = SceneUtils;
  30835. exports.WebGLUtils = WebGLUtils;
  30836. exports.WireframeGeometry = WireframeGeometry;
  30837. exports.ParametricGeometry = ParametricGeometry;
  30838. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  30839. exports.TetrahedronGeometry = TetrahedronGeometry;
  30840. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30841. exports.OctahedronGeometry = OctahedronGeometry;
  30842. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30843. exports.IcosahedronGeometry = IcosahedronGeometry;
  30844. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  30845. exports.DodecahedronGeometry = DodecahedronGeometry;
  30846. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  30847. exports.PolyhedronGeometry = PolyhedronGeometry;
  30848. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30849. exports.TubeGeometry = TubeGeometry;
  30850. exports.TubeBufferGeometry = TubeBufferGeometry;
  30851. exports.TorusKnotGeometry = TorusKnotGeometry;
  30852. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30853. exports.TorusGeometry = TorusGeometry;
  30854. exports.TorusBufferGeometry = TorusBufferGeometry;
  30855. exports.TextGeometry = TextGeometry;
  30856. exports.TextBufferGeometry = TextBufferGeometry;
  30857. exports.SphereGeometry = SphereGeometry;
  30858. exports.SphereBufferGeometry = SphereBufferGeometry;
  30859. exports.RingGeometry = RingGeometry;
  30860. exports.RingBufferGeometry = RingBufferGeometry;
  30861. exports.PlaneGeometry = PlaneGeometry;
  30862. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30863. exports.LatheGeometry = LatheGeometry;
  30864. exports.LatheBufferGeometry = LatheBufferGeometry;
  30865. exports.ShapeGeometry = ShapeGeometry;
  30866. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30867. exports.ExtrudeGeometry = ExtrudeGeometry;
  30868. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  30869. exports.EdgesGeometry = EdgesGeometry;
  30870. exports.ConeGeometry = ConeGeometry;
  30871. exports.ConeBufferGeometry = ConeBufferGeometry;
  30872. exports.CylinderGeometry = CylinderGeometry;
  30873. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  30874. exports.CircleGeometry = CircleGeometry;
  30875. exports.CircleBufferGeometry = CircleBufferGeometry;
  30876. exports.BoxGeometry = BoxGeometry;
  30877. exports.BoxBufferGeometry = BoxBufferGeometry;
  30878. exports.ShadowMaterial = ShadowMaterial;
  30879. exports.SpriteMaterial = SpriteMaterial;
  30880. exports.RawShaderMaterial = RawShaderMaterial;
  30881. exports.ShaderMaterial = ShaderMaterial;
  30882. exports.PointsMaterial = PointsMaterial;
  30883. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30884. exports.MeshStandardMaterial = MeshStandardMaterial;
  30885. exports.MeshPhongMaterial = MeshPhongMaterial;
  30886. exports.MeshToonMaterial = MeshToonMaterial;
  30887. exports.MeshNormalMaterial = MeshNormalMaterial;
  30888. exports.MeshLambertMaterial = MeshLambertMaterial;
  30889. exports.MeshDepthMaterial = MeshDepthMaterial;
  30890. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  30891. exports.MeshBasicMaterial = MeshBasicMaterial;
  30892. exports.LineDashedMaterial = LineDashedMaterial;
  30893. exports.LineBasicMaterial = LineBasicMaterial;
  30894. exports.Material = Material;
  30895. exports.Float64BufferAttribute = Float64BufferAttribute;
  30896. exports.Float32BufferAttribute = Float32BufferAttribute;
  30897. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30898. exports.Int32BufferAttribute = Int32BufferAttribute;
  30899. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30900. exports.Int16BufferAttribute = Int16BufferAttribute;
  30901. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30902. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30903. exports.Int8BufferAttribute = Int8BufferAttribute;
  30904. exports.BufferAttribute = BufferAttribute;
  30905. exports.REVISION = REVISION;
  30906. exports.MOUSE = MOUSE;
  30907. exports.CullFaceNone = CullFaceNone;
  30908. exports.CullFaceBack = CullFaceBack;
  30909. exports.CullFaceFront = CullFaceFront;
  30910. exports.CullFaceFrontBack = CullFaceFrontBack;
  30911. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  30912. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  30913. exports.BasicShadowMap = BasicShadowMap;
  30914. exports.PCFShadowMap = PCFShadowMap;
  30915. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30916. exports.FrontSide = FrontSide;
  30917. exports.BackSide = BackSide;
  30918. exports.DoubleSide = DoubleSide;
  30919. exports.FlatShading = FlatShading;
  30920. exports.SmoothShading = SmoothShading;
  30921. exports.NoColors = NoColors;
  30922. exports.FaceColors = FaceColors;
  30923. exports.VertexColors = VertexColors;
  30924. exports.NoBlending = NoBlending;
  30925. exports.NormalBlending = NormalBlending;
  30926. exports.AdditiveBlending = AdditiveBlending;
  30927. exports.SubtractiveBlending = SubtractiveBlending;
  30928. exports.MultiplyBlending = MultiplyBlending;
  30929. exports.CustomBlending = CustomBlending;
  30930. exports.AddEquation = AddEquation;
  30931. exports.SubtractEquation = SubtractEquation;
  30932. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30933. exports.MinEquation = MinEquation;
  30934. exports.MaxEquation = MaxEquation;
  30935. exports.ZeroFactor = ZeroFactor;
  30936. exports.OneFactor = OneFactor;
  30937. exports.SrcColorFactor = SrcColorFactor;
  30938. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30939. exports.SrcAlphaFactor = SrcAlphaFactor;
  30940. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30941. exports.DstAlphaFactor = DstAlphaFactor;
  30942. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30943. exports.DstColorFactor = DstColorFactor;
  30944. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30945. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30946. exports.NeverDepth = NeverDepth;
  30947. exports.AlwaysDepth = AlwaysDepth;
  30948. exports.LessDepth = LessDepth;
  30949. exports.LessEqualDepth = LessEqualDepth;
  30950. exports.EqualDepth = EqualDepth;
  30951. exports.GreaterEqualDepth = GreaterEqualDepth;
  30952. exports.GreaterDepth = GreaterDepth;
  30953. exports.NotEqualDepth = NotEqualDepth;
  30954. exports.MultiplyOperation = MultiplyOperation;
  30955. exports.MixOperation = MixOperation;
  30956. exports.AddOperation = AddOperation;
  30957. exports.NoToneMapping = NoToneMapping;
  30958. exports.LinearToneMapping = LinearToneMapping;
  30959. exports.ReinhardToneMapping = ReinhardToneMapping;
  30960. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  30961. exports.CineonToneMapping = CineonToneMapping;
  30962. exports.UVMapping = UVMapping;
  30963. exports.CubeReflectionMapping = CubeReflectionMapping;
  30964. exports.CubeRefractionMapping = CubeRefractionMapping;
  30965. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  30966. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  30967. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  30968. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  30969. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  30970. exports.RepeatWrapping = RepeatWrapping;
  30971. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  30972. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30973. exports.NearestFilter = NearestFilter;
  30974. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30975. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30976. exports.LinearFilter = LinearFilter;
  30977. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30978. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30979. exports.UnsignedByteType = UnsignedByteType;
  30980. exports.ByteType = ByteType;
  30981. exports.ShortType = ShortType;
  30982. exports.UnsignedShortType = UnsignedShortType;
  30983. exports.IntType = IntType;
  30984. exports.UnsignedIntType = UnsignedIntType;
  30985. exports.FloatType = FloatType;
  30986. exports.HalfFloatType = HalfFloatType;
  30987. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30988. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30989. exports.UnsignedShort565Type = UnsignedShort565Type;
  30990. exports.UnsignedInt248Type = UnsignedInt248Type;
  30991. exports.AlphaFormat = AlphaFormat;
  30992. exports.RGBFormat = RGBFormat;
  30993. exports.RGBAFormat = RGBAFormat;
  30994. exports.LuminanceFormat = LuminanceFormat;
  30995. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30996. exports.RGBEFormat = RGBEFormat;
  30997. exports.DepthFormat = DepthFormat;
  30998. exports.DepthStencilFormat = DepthStencilFormat;
  30999. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  31000. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  31001. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  31002. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  31003. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  31004. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  31005. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  31006. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  31007. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  31008. exports.LoopOnce = LoopOnce;
  31009. exports.LoopRepeat = LoopRepeat;
  31010. exports.LoopPingPong = LoopPingPong;
  31011. exports.InterpolateDiscrete = InterpolateDiscrete;
  31012. exports.InterpolateLinear = InterpolateLinear;
  31013. exports.InterpolateSmooth = InterpolateSmooth;
  31014. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  31015. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  31016. exports.WrapAroundEnding = WrapAroundEnding;
  31017. exports.TrianglesDrawMode = TrianglesDrawMode;
  31018. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  31019. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  31020. exports.LinearEncoding = LinearEncoding;
  31021. exports.sRGBEncoding = sRGBEncoding;
  31022. exports.GammaEncoding = GammaEncoding;
  31023. exports.RGBEEncoding = RGBEEncoding;
  31024. exports.LogLuvEncoding = LogLuvEncoding;
  31025. exports.RGBM7Encoding = RGBM7Encoding;
  31026. exports.RGBM16Encoding = RGBM16Encoding;
  31027. exports.RGBDEncoding = RGBDEncoding;
  31028. exports.BasicDepthPacking = BasicDepthPacking;
  31029. exports.RGBADepthPacking = RGBADepthPacking;
  31030. exports.CubeGeometry = BoxGeometry;
  31031. exports.Face4 = Face4;
  31032. exports.LineStrip = LineStrip;
  31033. exports.LinePieces = LinePieces;
  31034. exports.MeshFaceMaterial = MeshFaceMaterial;
  31035. exports.MultiMaterial = MultiMaterial;
  31036. exports.PointCloud = PointCloud;
  31037. exports.Particle = Particle;
  31038. exports.ParticleSystem = ParticleSystem;
  31039. exports.PointCloudMaterial = PointCloudMaterial;
  31040. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  31041. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  31042. exports.Vertex = Vertex;
  31043. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  31044. exports.Int8Attribute = Int8Attribute;
  31045. exports.Uint8Attribute = Uint8Attribute;
  31046. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  31047. exports.Int16Attribute = Int16Attribute;
  31048. exports.Uint16Attribute = Uint16Attribute;
  31049. exports.Int32Attribute = Int32Attribute;
  31050. exports.Uint32Attribute = Uint32Attribute;
  31051. exports.Float32Attribute = Float32Attribute;
  31052. exports.Float64Attribute = Float64Attribute;
  31053. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  31054. exports.SplineCurve3 = SplineCurve3;
  31055. exports.Spline = Spline;
  31056. exports.BoundingBoxHelper = BoundingBoxHelper;
  31057. exports.EdgesHelper = EdgesHelper;
  31058. exports.WireframeHelper = WireframeHelper;
  31059. exports.XHRLoader = XHRLoader;
  31060. exports.BinaryTextureLoader = BinaryTextureLoader;
  31061. exports.GeometryUtils = GeometryUtils;
  31062. exports.ImageUtils = ImageUtils;
  31063. exports.Projector = Projector;
  31064. exports.CanvasRenderer = CanvasRenderer;
  31065. Object.defineProperty(exports, '__esModule', { value: true });
  31066. })));
  31067. },{}],42:[function(_dereq_,module,exports){
  31068. /**
  31069. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  31070. * @author Tony Parisi / http://www.tonyparisi.com/
  31071. */
  31072. THREE.ColladaLoader = function () {
  31073. var COLLADA = null;
  31074. var scene = null;
  31075. var visualScene;
  31076. var kinematicsModel;
  31077. var readyCallbackFunc = null;
  31078. var sources = {};
  31079. var images = {};
  31080. var animations = {};
  31081. var controllers = {};
  31082. var geometries = {};
  31083. var materials = {};
  31084. var effects = {};
  31085. var cameras = {};
  31086. var lights = {};
  31087. var animData;
  31088. var kinematics;
  31089. var visualScenes;
  31090. var kinematicsModels;
  31091. var baseUrl;
  31092. var morphs;
  31093. var skins;
  31094. var flip_uv = true;
  31095. var options = {
  31096. // Force Geometry to always be centered at the local origin of the
  31097. // containing Mesh.
  31098. centerGeometry: false,
  31099. // Axis conversion is done for geometries, animations, and controllers.
  31100. // If we ever pull cameras or lights out of the COLLADA file, they'll
  31101. // need extra work.
  31102. convertUpAxis: false,
  31103. subdivideFaces: true,
  31104. upAxis: 'Y',
  31105. // For reflective or refractive materials we'll use this cubemap
  31106. defaultEnvMap: null
  31107. };
  31108. var colladaUnit = 1.0;
  31109. var colladaUp = 'Y';
  31110. var upConversion = null;
  31111. function load ( url, readyCallback, progressCallback, failCallback ) {
  31112. var length = 0;
  31113. if ( document.implementation && document.implementation.createDocument ) {
  31114. var request = new XMLHttpRequest();
  31115. request.onreadystatechange = function() {
  31116. if ( request.readyState === 4 ) {
  31117. if ( request.status === 0 || request.status === 200 ) {
  31118. if ( request.response ) {
  31119. readyCallbackFunc = readyCallback;
  31120. parse( request.response, undefined, url );
  31121. } else {
  31122. if ( failCallback ) {
  31123. failCallback( { type: 'error', url: url } );
  31124. } else {
  31125. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  31126. }
  31127. }
  31128. }else{
  31129. if( failCallback ){
  31130. failCallback( { type: 'error', url: url } );
  31131. }else{
  31132. console.error( 'ColladaLoader: Couldn\'t load "' + url + '" (' + request.status + ')' );
  31133. }
  31134. }
  31135. } else if ( request.readyState === 3 ) {
  31136. if ( progressCallback ) {
  31137. if ( length === 0 ) {
  31138. length = request.getResponseHeader( "Content-Length" );
  31139. }
  31140. progressCallback( { total: length, loaded: request.responseText.length } );
  31141. }
  31142. }
  31143. };
  31144. request.open( "GET", url, true );
  31145. request.send( null );
  31146. } else {
  31147. alert( "Don't know how to parse XML!" );
  31148. }
  31149. }
  31150. function parse( text, callBack, url ) {
  31151. COLLADA = new DOMParser().parseFromString( text, 'text/xml' );
  31152. callBack = callBack || readyCallbackFunc;
  31153. if ( url !== undefined ) {
  31154. var parts = url.split( '/' );
  31155. parts.pop();
  31156. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  31157. }
  31158. parseAsset();
  31159. setUpConversion();
  31160. images = parseLib( "library_images image", _Image, "image" );
  31161. materials = parseLib( "library_materials material", Material, "material" );
  31162. effects = parseLib( "library_effects effect", Effect, "effect" );
  31163. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  31164. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  31165. lights = parseLib( "library_lights light", Light, "light" );
  31166. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  31167. animations = parseLib( "library_animations animation", Animation, "animation" );
  31168. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  31169. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  31170. morphs = [];
  31171. skins = [];
  31172. visualScene = parseScene();
  31173. scene = new THREE.Group();
  31174. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  31175. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  31176. }
  31177. // unit conversion
  31178. scene.scale.multiplyScalar( colladaUnit );
  31179. createAnimations();
  31180. kinematicsModel = parseKinematicsModel();
  31181. createKinematics();
  31182. var result = {
  31183. scene: scene,
  31184. morphs: morphs,
  31185. skins: skins,
  31186. animations: animData,
  31187. kinematics: kinematics,
  31188. dae: {
  31189. images: images,
  31190. materials: materials,
  31191. cameras: cameras,
  31192. lights: lights,
  31193. effects: effects,
  31194. geometries: geometries,
  31195. controllers: controllers,
  31196. animations: animations,
  31197. visualScenes: visualScenes,
  31198. visualScene: visualScene,
  31199. scene: visualScene,
  31200. kinematicsModels: kinematicsModels,
  31201. kinematicsModel: kinematicsModel
  31202. }
  31203. };
  31204. if ( callBack ) {
  31205. callBack( result );
  31206. }
  31207. return result;
  31208. }
  31209. function parseAsset () {
  31210. var elements = COLLADA.querySelectorAll('asset');
  31211. var element = elements[0];
  31212. if ( element && element.childNodes ) {
  31213. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31214. var child = element.childNodes[ i ];
  31215. switch ( child.nodeName ) {
  31216. case 'unit':
  31217. var meter = child.getAttribute( 'meter' );
  31218. if ( meter ) {
  31219. colladaUnit = parseFloat( meter );
  31220. }
  31221. break;
  31222. case 'up_axis':
  31223. colladaUp = child.textContent.charAt(0);
  31224. break;
  31225. }
  31226. }
  31227. }
  31228. }
  31229. function parseLib ( q, classSpec, prefix ) {
  31230. var elements = COLLADA.querySelectorAll(q);
  31231. var lib = {};
  31232. var i = 0;
  31233. var elementsLength = elements.length;
  31234. for ( var j = 0; j < elementsLength; j ++ ) {
  31235. var element = elements[j];
  31236. var daeElement = ( new classSpec() ).parse( element );
  31237. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  31238. lib[ daeElement.id ] = daeElement;
  31239. }
  31240. return lib;
  31241. }
  31242. function parseScene() {
  31243. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  31244. if ( sceneElement ) {
  31245. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  31246. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  31247. } else {
  31248. return null;
  31249. }
  31250. }
  31251. function parseKinematicsModel() {
  31252. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  31253. if ( kinematicsModelElement ) {
  31254. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  31255. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  31256. } else {
  31257. return null;
  31258. }
  31259. }
  31260. function createAnimations() {
  31261. animData = [];
  31262. // fill in the keys
  31263. recurseHierarchy( scene );
  31264. }
  31265. function recurseHierarchy( node ) {
  31266. var n = visualScene.getChildById( node.colladaId, true ),
  31267. newData = null;
  31268. if ( n && n.keys ) {
  31269. newData = {
  31270. fps: 60,
  31271. hierarchy: [ {
  31272. node: n,
  31273. keys: n.keys,
  31274. sids: n.sids
  31275. } ],
  31276. node: node,
  31277. name: 'animation_' + node.name,
  31278. length: 0
  31279. };
  31280. animData.push(newData);
  31281. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  31282. newData.length = Math.max( newData.length, n.keys[i].time );
  31283. }
  31284. } else {
  31285. newData = {
  31286. hierarchy: [ {
  31287. keys: [],
  31288. sids: []
  31289. } ]
  31290. }
  31291. }
  31292. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  31293. var d = recurseHierarchy( node.children[i] );
  31294. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  31295. newData.hierarchy.push( {
  31296. keys: [],
  31297. sids: []
  31298. } );
  31299. }
  31300. }
  31301. return newData;
  31302. }
  31303. function calcAnimationBounds () {
  31304. var start = 1000000;
  31305. var end = -start;
  31306. var frames = 0;
  31307. var ID;
  31308. for ( var id in animations ) {
  31309. var animation = animations[ id ];
  31310. ID = ID || animation.id;
  31311. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  31312. var sampler = animation.sampler[ i ];
  31313. sampler.create();
  31314. start = Math.min( start, sampler.startTime );
  31315. end = Math.max( end, sampler.endTime );
  31316. frames = Math.max( frames, sampler.input.length );
  31317. }
  31318. }
  31319. return { start:start, end:end, frames:frames,ID:ID };
  31320. }
  31321. function createMorph ( geometry, ctrl ) {
  31322. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  31323. if ( !morphCtrl || !morphCtrl.morph ) {
  31324. console.log("could not find morph controller!");
  31325. return;
  31326. }
  31327. var morph = morphCtrl.morph;
  31328. for ( var i = 0; i < morph.targets.length; i ++ ) {
  31329. var target_id = morph.targets[ i ];
  31330. var daeGeometry = geometries[ target_id ];
  31331. if ( !daeGeometry.mesh ||
  31332. !daeGeometry.mesh.primitives ||
  31333. !daeGeometry.mesh.primitives.length ) {
  31334. continue;
  31335. }
  31336. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  31337. if ( target.vertices.length === geometry.vertices.length ) {
  31338. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  31339. }
  31340. }
  31341. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  31342. }
  31343. function createSkin ( geometry, ctrl, applyBindShape ) {
  31344. var skinCtrl = controllers[ ctrl.url ];
  31345. if ( !skinCtrl || !skinCtrl.skin ) {
  31346. console.log( "could not find skin controller!" );
  31347. return;
  31348. }
  31349. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  31350. console.log( "could not find the skeleton for the skin!" );
  31351. return;
  31352. }
  31353. var skin = skinCtrl.skin;
  31354. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  31355. var hierarchy = [];
  31356. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  31357. var bones = [];
  31358. geometry.skinWeights = [];
  31359. geometry.skinIndices = [];
  31360. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  31361. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  31362. /*
  31363. geometry.animation = {
  31364. name: 'take_001',
  31365. fps: 30,
  31366. length: 2,
  31367. JIT: true,
  31368. hierarchy: hierarchy
  31369. };
  31370. */
  31371. if ( applyBindShape ) {
  31372. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  31373. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  31374. }
  31375. }
  31376. }
  31377. function setupSkeleton ( node, bones, frame, parent ) {
  31378. node.world = node.world || new THREE.Matrix4();
  31379. node.localworld = node.localworld || new THREE.Matrix4();
  31380. node.world.copy( node.matrix );
  31381. node.localworld.copy( node.matrix );
  31382. if ( node.channels && node.channels.length ) {
  31383. var channel = node.channels[ 0 ];
  31384. var m = channel.sampler.output[ frame ];
  31385. if ( m instanceof THREE.Matrix4 ) {
  31386. node.world.copy( m );
  31387. node.localworld.copy(m);
  31388. if (frame === 0)
  31389. node.matrix.copy(m);
  31390. }
  31391. }
  31392. if ( parent ) {
  31393. node.world.multiplyMatrices( parent, node.world );
  31394. }
  31395. bones.push( node );
  31396. for ( var i = 0; i < node.nodes.length; i ++ ) {
  31397. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  31398. }
  31399. }
  31400. function setupSkinningMatrices ( bones, skin ) {
  31401. // FIXME: this is dumb...
  31402. for ( var i = 0; i < bones.length; i ++ ) {
  31403. var bone = bones[ i ];
  31404. var found = -1;
  31405. if ( bone.type != 'JOINT' ) continue;
  31406. for ( var j = 0; j < skin.joints.length; j ++ ) {
  31407. if ( bone.sid === skin.joints[ j ] ) {
  31408. found = j;
  31409. break;
  31410. }
  31411. }
  31412. if ( found >= 0 ) {
  31413. var inv = skin.invBindMatrices[ found ];
  31414. bone.invBindMatrix = inv;
  31415. bone.skinningMatrix = new THREE.Matrix4();
  31416. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  31417. bone.animatrix = new THREE.Matrix4();
  31418. bone.animatrix.copy(bone.localworld);
  31419. bone.weights = [];
  31420. for ( var j = 0; j < skin.weights.length; j ++ ) {
  31421. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  31422. var w = skin.weights[ j ][ k ];
  31423. if ( w.joint === found ) {
  31424. bone.weights.push( w );
  31425. }
  31426. }
  31427. }
  31428. } else {
  31429. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  31430. bone.skinningMatrix = new THREE.Matrix4();
  31431. bone.weights = [];
  31432. }
  31433. }
  31434. }
  31435. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  31436. function flattenSkeleton(skeleton) {
  31437. var list = [];
  31438. var walk = function(parentid, node, list) {
  31439. var bone = {};
  31440. bone.name = node.sid;
  31441. bone.parent = parentid;
  31442. bone.matrix = node.matrix;
  31443. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  31444. bone.matrix.decompose(data[0], data[1], data[2]);
  31445. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  31446. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  31447. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  31448. list.push(bone);
  31449. for (var i in node.nodes) {
  31450. walk(node.sid, node.nodes[i], list);
  31451. }
  31452. };
  31453. walk(-1, skeleton, list);
  31454. return list;
  31455. }
  31456. //Move the vertices into the pose that is proper for the start of the animation
  31457. function skinToBindPose(geometry,skeleton,skinController) {
  31458. var bones = [];
  31459. setupSkeleton( skeleton, bones, -1 );
  31460. setupSkinningMatrices( bones, skinController.skin );
  31461. var v = new THREE.Vector3();
  31462. var skinned = [];
  31463. for (var i = 0; i < geometry.vertices.length; i ++) {
  31464. skinned.push(new THREE.Vector3());
  31465. }
  31466. for ( i = 0; i < bones.length; i ++ ) {
  31467. if ( bones[ i ].type != 'JOINT' ) continue;
  31468. for ( var j = 0; j < bones[ i ].weights.length; j ++ ) {
  31469. var w = bones[ i ].weights[ j ];
  31470. var vidx = w.index;
  31471. var weight = w.weight;
  31472. var o = geometry.vertices[vidx];
  31473. var s = skinned[vidx];
  31474. v.x = o.x;
  31475. v.y = o.y;
  31476. v.z = o.z;
  31477. v.applyMatrix4( bones[i].skinningMatrix );
  31478. s.x += (v.x * weight);
  31479. s.y += (v.y * weight);
  31480. s.z += (v.z * weight);
  31481. }
  31482. }
  31483. for (var i = 0; i < geometry.vertices.length; i ++) {
  31484. geometry.vertices[i] = skinned[i];
  31485. }
  31486. }
  31487. function applySkin( geometry, instanceCtrl, frame ) {
  31488. if ( frame === undefined ) frame = 40;
  31489. var skinController = controllers[ instanceCtrl.url ];
  31490. if ( !skinController || !skinController.skin ) {
  31491. console.log( 'ColladaLoader: Could not find skin controller.' );
  31492. return;
  31493. }
  31494. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  31495. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  31496. return;
  31497. }
  31498. var animationBounds = calcAnimationBounds();
  31499. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  31500. //flatten the skeleton into a list of bones
  31501. var bonelist = flattenSkeleton(skeleton);
  31502. var joints = skinController.skin.joints;
  31503. //sort that list so that the order reflects the order in the joint list
  31504. var sortedbones = [];
  31505. for (var i = 0; i < joints.length; i ++) {
  31506. for (var j = 0; j < bonelist.length; j ++) {
  31507. if (bonelist[j].name === joints[i]) {
  31508. sortedbones[i] = bonelist[j];
  31509. }
  31510. }
  31511. }
  31512. //hook up the parents by index instead of name
  31513. for (var i = 0; i < sortedbones.length; i ++) {
  31514. for (var j = 0; j < sortedbones.length; j ++) {
  31515. if (sortedbones[i].parent === sortedbones[j].name) {
  31516. sortedbones[i].parent = j;
  31517. }
  31518. }
  31519. }
  31520. var i, j, w, vidx, weight;
  31521. var v = new THREE.Vector3(), o, s;
  31522. // move vertices to bind shape
  31523. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  31524. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  31525. }
  31526. var skinIndices = [];
  31527. var skinWeights = [];
  31528. var weights = skinController.skin.weights;
  31529. // hook up the skin weights
  31530. // TODO - this might be a good place to choose greatest 4 weights
  31531. for ( var i =0; i < weights.length; i ++ ) {
  31532. var indicies = new THREE.Vector4(weights[i][0] ? weights[i][0].joint : 0,weights[i][1] ? weights[i][1].joint : 0,weights[i][2] ? weights[i][2].joint : 0,weights[i][3] ? weights[i][3].joint : 0);
  31533. var weight = new THREE.Vector4(weights[i][0] ? weights[i][0].weight : 0,weights[i][1] ? weights[i][1].weight : 0,weights[i][2] ? weights[i][2].weight : 0,weights[i][3] ? weights[i][3].weight : 0);
  31534. skinIndices.push(indicies);
  31535. skinWeights.push(weight);
  31536. }
  31537. geometry.skinIndices = skinIndices;
  31538. geometry.skinWeights = skinWeights;
  31539. geometry.bones = sortedbones;
  31540. // process animation, or simply pose the rig if no animation
  31541. //create an animation for the animated bones
  31542. //NOTE: this has no effect when using morphtargets
  31543. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  31544. for (var j = 0; j < sortedbones.length; j ++) {
  31545. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  31546. }
  31547. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  31548. skinToBindPose(geometry, skeleton, skinController);
  31549. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  31550. var bones = [];
  31551. var skinned = [];
  31552. // process the frame and setup the rig with a fresh
  31553. // transform, possibly from the bone's animation channel(s)
  31554. setupSkeleton( skeleton, bones, frame );
  31555. setupSkinningMatrices( bones, skinController.skin );
  31556. for (var i = 0; i < bones.length; i ++) {
  31557. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  31558. if (animationdata.hierarchy[j].name === bones[i].sid) {
  31559. var key = {};
  31560. key.time = (frame / 30);
  31561. key.matrix = bones[i].animatrix;
  31562. if (frame === 0)
  31563. bones[i].matrix = key.matrix;
  31564. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  31565. key.matrix.decompose(data[0], data[1], data[2]);
  31566. key.pos = [ data[0].x,data[0].y,data[0].z ];
  31567. key.scl = [ data[2].x,data[2].y,data[2].z ];
  31568. key.rot = data[1];
  31569. animationdata.hierarchy[j].keys.push(key);
  31570. }
  31571. }
  31572. }
  31573. geometry.animation = animationdata;
  31574. }
  31575. }
  31576. function createKinematics() {
  31577. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  31578. kinematics = undefined;
  31579. return;
  31580. }
  31581. var jointMap = {};
  31582. var _addToMap = function( jointIndex, parentVisualElement ) {
  31583. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  31584. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  31585. var joint = kinematicsModel.joints[ jointIndex ];
  31586. scene.traverse(function( node ) {
  31587. if ( node.colladaId == parentVisualElementId ) {
  31588. jointMap[ jointIndex ] = {
  31589. node: node,
  31590. transforms: colladaNode.transforms,
  31591. joint: joint,
  31592. position: joint.zeroPosition
  31593. };
  31594. }
  31595. });
  31596. };
  31597. kinematics = {
  31598. joints: kinematicsModel && kinematicsModel.joints,
  31599. getJointValue: function( jointIndex ) {
  31600. var jointData = jointMap[ jointIndex ];
  31601. if ( jointData ) {
  31602. return jointData.position;
  31603. } else {
  31604. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  31605. }
  31606. },
  31607. setJointValue: function( jointIndex, value ) {
  31608. var jointData = jointMap[ jointIndex ];
  31609. if ( jointData ) {
  31610. var joint = jointData.joint;
  31611. if ( value > joint.limits.max || value < joint.limits.min ) {
  31612. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  31613. } else if ( joint.static ) {
  31614. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  31615. } else {
  31616. var threejsNode = jointData.node;
  31617. var axis = joint.axis;
  31618. var transforms = jointData.transforms;
  31619. var matrix = new THREE.Matrix4();
  31620. var m1 = new THREE.Matrix4();
  31621. for (i = 0; i < transforms.length; i ++ ) {
  31622. var transform = transforms[ i ];
  31623. // kinda ghetto joint detection
  31624. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  31625. // apply actual joint value here
  31626. switch ( joint.type ) {
  31627. case 'revolute':
  31628. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  31629. break;
  31630. case 'prismatic':
  31631. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  31632. break;
  31633. default:
  31634. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  31635. break;
  31636. }
  31637. } else {
  31638. switch ( transform.type ) {
  31639. case 'matrix':
  31640. matrix.multiply( transform.obj );
  31641. break;
  31642. case 'translate':
  31643. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  31644. break;
  31645. case 'rotate':
  31646. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  31647. break;
  31648. }
  31649. }
  31650. }
  31651. // apply the matrix to the threejs node
  31652. var elementsFloat32Arr = matrix.elements;
  31653. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  31654. var elementsRowMajor = [
  31655. elements[ 0 ],
  31656. elements[ 4 ],
  31657. elements[ 8 ],
  31658. elements[ 12 ],
  31659. elements[ 1 ],
  31660. elements[ 5 ],
  31661. elements[ 9 ],
  31662. elements[ 13 ],
  31663. elements[ 2 ],
  31664. elements[ 6 ],
  31665. elements[ 10 ],
  31666. elements[ 14 ],
  31667. elements[ 3 ],
  31668. elements[ 7 ],
  31669. elements[ 11 ],
  31670. elements[ 15 ]
  31671. ];
  31672. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  31673. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  31674. jointMap[ jointIndex ].position = value;
  31675. }
  31676. } else {
  31677. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  31678. }
  31679. }
  31680. };
  31681. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  31682. if ( element ) {
  31683. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31684. var child = element.childNodes[ i ];
  31685. if ( child.nodeType != 1 ) continue;
  31686. switch ( child.nodeName ) {
  31687. case 'bind_joint_axis':
  31688. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  31689. var axis = child.querySelector('axis param').textContent;
  31690. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  31691. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  31692. if ( visualTargetElement ) {
  31693. var parentVisualElement = visualTargetElement.parentElement;
  31694. _addToMap(jointIndex, parentVisualElement);
  31695. }
  31696. break;
  31697. default:
  31698. break;
  31699. }
  31700. }
  31701. }
  31702. }
  31703. function createSceneGraph ( node, parent ) {
  31704. var obj = new THREE.Object3D();
  31705. var skinned = false;
  31706. var skinController;
  31707. var morphController;
  31708. var i, j;
  31709. // FIXME: controllers
  31710. for ( i = 0; i < node.controllers.length; i ++ ) {
  31711. var controller = controllers[ node.controllers[ i ].url ];
  31712. switch ( controller.type ) {
  31713. case 'skin':
  31714. if ( geometries[ controller.skin.source ] ) {
  31715. var inst_geom = new InstanceGeometry();
  31716. inst_geom.url = controller.skin.source;
  31717. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31718. node.geometries.push( inst_geom );
  31719. skinned = true;
  31720. skinController = node.controllers[ i ];
  31721. } else if ( controllers[ controller.skin.source ] ) {
  31722. // urgh: controller can be chained
  31723. // handle the most basic case...
  31724. var second = controllers[ controller.skin.source ];
  31725. morphController = second;
  31726. // skinController = node.controllers[i];
  31727. if ( second.morph && geometries[ second.morph.source ] ) {
  31728. var inst_geom = new InstanceGeometry();
  31729. inst_geom.url = second.morph.source;
  31730. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31731. node.geometries.push( inst_geom );
  31732. }
  31733. }
  31734. break;
  31735. case 'morph':
  31736. if ( geometries[ controller.morph.source ] ) {
  31737. var inst_geom = new InstanceGeometry();
  31738. inst_geom.url = controller.morph.source;
  31739. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31740. node.geometries.push( inst_geom );
  31741. morphController = node.controllers[ i ];
  31742. }
  31743. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  31744. default:
  31745. break;
  31746. }
  31747. }
  31748. // geometries
  31749. var double_sided_materials = {};
  31750. for ( i = 0; i < node.geometries.length; i ++ ) {
  31751. var instance_geometry = node.geometries[i];
  31752. var instance_materials = instance_geometry.instance_material;
  31753. var geometry = geometries[ instance_geometry.url ];
  31754. var used_materials = {};
  31755. var used_materials_array = [];
  31756. var num_materials = 0;
  31757. var first_material;
  31758. if ( geometry ) {
  31759. if ( !geometry.mesh || !geometry.mesh.primitives )
  31760. continue;
  31761. if ( obj.name.length === 0 ) {
  31762. obj.name = geometry.id;
  31763. }
  31764. // collect used fx for this geometry-instance
  31765. if ( instance_materials ) {
  31766. for ( j = 0; j < instance_materials.length; j ++ ) {
  31767. var instance_material = instance_materials[ j ];
  31768. var mat = materials[ instance_material.target ];
  31769. var effect_id = mat.instance_effect.url;
  31770. var shader = effects[ effect_id ].shader;
  31771. var material3js = shader.material;
  31772. if ( geometry.doubleSided ) {
  31773. if ( !( instance_material.symbol in double_sided_materials ) ) {
  31774. var _copied_material = material3js.clone();
  31775. _copied_material.side = THREE.DoubleSide;
  31776. double_sided_materials[ instance_material.symbol ] = _copied_material;
  31777. }
  31778. material3js = double_sided_materials[ instance_material.symbol ];
  31779. }
  31780. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  31781. used_materials[ instance_material.symbol ] = num_materials;
  31782. used_materials_array.push( material3js );
  31783. first_material = material3js;
  31784. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  31785. num_materials ++;
  31786. }
  31787. }
  31788. var mesh;
  31789. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  31790. var geom = geometry.mesh.geometry3js;
  31791. if ( num_materials > 1 ) {
  31792. material = new THREE.MultiMaterial( used_materials_array );
  31793. for ( j = 0; j < geom.faces.length; j ++ ) {
  31794. var face = geom.faces[ j ];
  31795. face.materialIndex = used_materials[ face.daeMaterial ]
  31796. }
  31797. }
  31798. if ( skinController !== undefined ) {
  31799. applySkin( geom, skinController );
  31800. if ( geom.morphTargets.length > 0 ) {
  31801. material.morphTargets = true;
  31802. material.skinning = false;
  31803. } else {
  31804. material.morphTargets = false;
  31805. material.skinning = true;
  31806. }
  31807. mesh = new THREE.SkinnedMesh( geom, material, false );
  31808. //mesh.skeleton = skinController.skeleton;
  31809. //mesh.skinController = controllers[ skinController.url ];
  31810. //mesh.skinInstanceController = skinController;
  31811. mesh.name = 'skin_' + skins.length;
  31812. //mesh.animationHandle.setKey(0);
  31813. skins.push( mesh );
  31814. } else if ( morphController !== undefined ) {
  31815. createMorph( geom, morphController );
  31816. material.morphTargets = true;
  31817. mesh = new THREE.Mesh( geom, material );
  31818. mesh.name = 'morph_' + morphs.length;
  31819. morphs.push( mesh );
  31820. } else {
  31821. if ( geom.isLineStrip === true ) {
  31822. mesh = new THREE.Line( geom );
  31823. } else {
  31824. mesh = new THREE.Mesh( geom, material );
  31825. }
  31826. }
  31827. obj.add(mesh);
  31828. }
  31829. }
  31830. for ( i = 0; i < node.cameras.length; i ++ ) {
  31831. var instance_camera = node.cameras[i];
  31832. var cparams = cameras[instance_camera.url];
  31833. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  31834. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  31835. obj.add(cam);
  31836. }
  31837. for ( i = 0; i < node.lights.length; i ++ ) {
  31838. var light = null;
  31839. var instance_light = node.lights[i];
  31840. var lparams = lights[instance_light.url];
  31841. if ( lparams && lparams.technique ) {
  31842. var color = lparams.color.getHex();
  31843. var intensity = lparams.intensity;
  31844. var distance = lparams.distance;
  31845. var angle = lparams.falloff_angle;
  31846. switch ( lparams.technique ) {
  31847. case 'directional':
  31848. light = new THREE.DirectionalLight( color, intensity, distance );
  31849. light.position.set(0, 0, 1);
  31850. break;
  31851. case 'point':
  31852. light = new THREE.PointLight( color, intensity, distance );
  31853. break;
  31854. case 'spot':
  31855. light = new THREE.SpotLight( color, intensity, distance, angle );
  31856. light.position.set(0, 0, 1);
  31857. break;
  31858. case 'ambient':
  31859. light = new THREE.AmbientLight( color );
  31860. break;
  31861. }
  31862. }
  31863. if (light) {
  31864. obj.add(light);
  31865. }
  31866. }
  31867. obj.name = node.name || node.id || "";
  31868. obj.colladaId = node.id || "";
  31869. obj.layer = node.layer || "";
  31870. obj.matrix = node.matrix;
  31871. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  31872. if ( options.centerGeometry && obj.geometry ) {
  31873. var delta = obj.geometry.center();
  31874. delta.multiply( obj.scale );
  31875. delta.applyQuaternion( obj.quaternion );
  31876. obj.position.sub( delta );
  31877. }
  31878. for ( i = 0; i < node.nodes.length; i ++ ) {
  31879. obj.add( createSceneGraph( node.nodes[i], node ) );
  31880. }
  31881. return obj;
  31882. }
  31883. function getJointId( skin, id ) {
  31884. for ( var i = 0; i < skin.joints.length; i ++ ) {
  31885. if ( skin.joints[ i ] === id ) {
  31886. return i;
  31887. }
  31888. }
  31889. }
  31890. function getLibraryNode( id ) {
  31891. var nodes = COLLADA.querySelectorAll('library_nodes node');
  31892. for ( var i = 0; i < nodes.length; i++ ) {
  31893. var attObj = nodes[i].attributes.getNamedItem('id');
  31894. if ( attObj && attObj.value === id ) {
  31895. return nodes[i];
  31896. }
  31897. }
  31898. return undefined;
  31899. }
  31900. function getChannelsForNode ( node ) {
  31901. var channels = [];
  31902. var startTime = 1000000;
  31903. var endTime = -1000000;
  31904. for ( var id in animations ) {
  31905. var animation = animations[id];
  31906. for ( var i = 0; i < animation.channel.length; i ++ ) {
  31907. var channel = animation.channel[i];
  31908. var sampler = animation.sampler[i];
  31909. var id = channel.target.split('/')[0];
  31910. if ( id == node.id ) {
  31911. sampler.create();
  31912. channel.sampler = sampler;
  31913. startTime = Math.min(startTime, sampler.startTime);
  31914. endTime = Math.max(endTime, sampler.endTime);
  31915. channels.push(channel);
  31916. }
  31917. }
  31918. }
  31919. if ( channels.length ) {
  31920. node.startTime = startTime;
  31921. node.endTime = endTime;
  31922. }
  31923. return channels;
  31924. }
  31925. function calcFrameDuration( node ) {
  31926. var minT = 10000000;
  31927. for ( var i = 0; i < node.channels.length; i ++ ) {
  31928. var sampler = node.channels[i].sampler;
  31929. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  31930. var t0 = sampler.input[ j ];
  31931. var t1 = sampler.input[ j + 1 ];
  31932. minT = Math.min( minT, t1 - t0 );
  31933. }
  31934. }
  31935. return minT;
  31936. }
  31937. function calcMatrixAt( node, t ) {
  31938. var animated = {};
  31939. var i, j;
  31940. for ( i = 0; i < node.channels.length; i ++ ) {
  31941. var channel = node.channels[ i ];
  31942. animated[ channel.sid ] = channel;
  31943. }
  31944. var matrix = new THREE.Matrix4();
  31945. for ( i = 0; i < node.transforms.length; i ++ ) {
  31946. var transform = node.transforms[ i ];
  31947. var channel = animated[ transform.sid ];
  31948. if ( channel !== undefined ) {
  31949. var sampler = channel.sampler;
  31950. var value;
  31951. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  31952. if ( sampler.input[ j + 1 ] > t ) {
  31953. value = sampler.output[ j ];
  31954. //console.log(value.flatten)
  31955. break;
  31956. }
  31957. }
  31958. if ( value !== undefined ) {
  31959. if ( value instanceof THREE.Matrix4 ) {
  31960. matrix.multiplyMatrices( matrix, value );
  31961. } else {
  31962. // FIXME: handle other types
  31963. matrix.multiplyMatrices( matrix, transform.matrix );
  31964. }
  31965. } else {
  31966. matrix.multiplyMatrices( matrix, transform.matrix );
  31967. }
  31968. } else {
  31969. matrix.multiplyMatrices( matrix, transform.matrix );
  31970. }
  31971. }
  31972. return matrix;
  31973. }
  31974. function bakeAnimations ( node ) {
  31975. if ( node.channels && node.channels.length ) {
  31976. var keys = [],
  31977. sids = [];
  31978. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  31979. var channel = node.channels[i],
  31980. fullSid = channel.fullSid,
  31981. sampler = channel.sampler,
  31982. input = sampler.input,
  31983. transform = node.getTransformBySid( channel.sid ),
  31984. member;
  31985. if ( channel.arrIndices ) {
  31986. member = [];
  31987. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  31988. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  31989. }
  31990. } else {
  31991. member = getConvertedMember( channel.member );
  31992. }
  31993. if ( transform ) {
  31994. if ( sids.indexOf( fullSid ) === -1 ) {
  31995. sids.push( fullSid );
  31996. }
  31997. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  31998. var time = input[j],
  31999. data = sampler.getData( transform.type, j, member ),
  32000. key = findKey( keys, time );
  32001. if ( !key ) {
  32002. key = new Key( time );
  32003. var timeNdx = findTimeNdx( keys, time );
  32004. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  32005. }
  32006. key.addTarget( fullSid, transform, member, data );
  32007. }
  32008. } else {
  32009. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  32010. }
  32011. }
  32012. // post process
  32013. for ( var i = 0; i < sids.length; i ++ ) {
  32014. var sid = sids[ i ];
  32015. for ( var j = 0; j < keys.length; j ++ ) {
  32016. var key = keys[ j ];
  32017. if ( !key.hasTarget( sid ) ) {
  32018. interpolateKeys( keys, key, j, sid );
  32019. }
  32020. }
  32021. }
  32022. node.keys = keys;
  32023. node.sids = sids;
  32024. }
  32025. }
  32026. function findKey ( keys, time) {
  32027. var retVal = null;
  32028. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  32029. var key = keys[i];
  32030. if ( key.time === time ) {
  32031. retVal = key;
  32032. } else if ( key.time > time ) {
  32033. break;
  32034. }
  32035. }
  32036. return retVal;
  32037. }
  32038. function findTimeNdx ( keys, time) {
  32039. var ndx = -1;
  32040. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  32041. var key = keys[i];
  32042. if ( key.time >= time ) {
  32043. ndx = i;
  32044. }
  32045. }
  32046. return ndx;
  32047. }
  32048. function interpolateKeys ( keys, key, ndx, fullSid ) {
  32049. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  32050. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  32051. if ( prevKey && nextKey ) {
  32052. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  32053. prevTarget = prevKey.getTarget( fullSid ),
  32054. nextData = nextKey.getTarget( fullSid ).data,
  32055. prevData = prevTarget.data,
  32056. data;
  32057. if ( prevTarget.type === 'matrix' ) {
  32058. data = prevData;
  32059. } else if ( prevData.length ) {
  32060. data = [];
  32061. for ( var i = 0; i < prevData.length; ++ i ) {
  32062. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  32063. }
  32064. } else {
  32065. data = prevData + ( nextData - prevData ) * scale;
  32066. }
  32067. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  32068. }
  32069. }
  32070. // Get next key with given sid
  32071. function getNextKeyWith( keys, fullSid, ndx ) {
  32072. for ( ; ndx < keys.length; ndx ++ ) {
  32073. var key = keys[ ndx ];
  32074. if ( key.hasTarget( fullSid ) ) {
  32075. return key;
  32076. }
  32077. }
  32078. return null;
  32079. }
  32080. // Get previous key with given sid
  32081. function getPrevKeyWith( keys, fullSid, ndx ) {
  32082. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  32083. for ( ; ndx >= 0; ndx -- ) {
  32084. var key = keys[ ndx ];
  32085. if ( key.hasTarget( fullSid ) ) {
  32086. return key;
  32087. }
  32088. }
  32089. return null;
  32090. }
  32091. function _Image() {
  32092. this.id = "";
  32093. this.init_from = "";
  32094. }
  32095. _Image.prototype.parse = function(element) {
  32096. this.id = element.getAttribute('id');
  32097. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32098. var child = element.childNodes[ i ];
  32099. if ( child.nodeName === 'init_from' ) {
  32100. this.init_from = child.textContent;
  32101. }
  32102. }
  32103. return this;
  32104. };
  32105. function Controller() {
  32106. this.id = "";
  32107. this.name = "";
  32108. this.type = "";
  32109. this.skin = null;
  32110. this.morph = null;
  32111. }
  32112. Controller.prototype.parse = function( element ) {
  32113. this.id = element.getAttribute('id');
  32114. this.name = element.getAttribute('name');
  32115. this.type = "none";
  32116. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32117. var child = element.childNodes[ i ];
  32118. switch ( child.nodeName ) {
  32119. case 'skin':
  32120. this.skin = (new Skin()).parse(child);
  32121. this.type = child.nodeName;
  32122. break;
  32123. case 'morph':
  32124. this.morph = (new Morph()).parse(child);
  32125. this.type = child.nodeName;
  32126. break;
  32127. default:
  32128. break;
  32129. }
  32130. }
  32131. return this;
  32132. };
  32133. function Morph() {
  32134. this.method = null;
  32135. this.source = null;
  32136. this.targets = null;
  32137. this.weights = null;
  32138. }
  32139. Morph.prototype.parse = function( element ) {
  32140. var sources = {};
  32141. var inputs = [];
  32142. var i;
  32143. this.method = element.getAttribute( 'method' );
  32144. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  32145. for ( i = 0; i < element.childNodes.length; i ++ ) {
  32146. var child = element.childNodes[ i ];
  32147. if ( child.nodeType != 1 ) continue;
  32148. switch ( child.nodeName ) {
  32149. case 'source':
  32150. var source = ( new Source() ).parse( child );
  32151. sources[ source.id ] = source;
  32152. break;
  32153. case 'targets':
  32154. inputs = this.parseInputs( child );
  32155. break;
  32156. default:
  32157. console.log( child.nodeName );
  32158. break;
  32159. }
  32160. }
  32161. for ( i = 0; i < inputs.length; i ++ ) {
  32162. var input = inputs[ i ];
  32163. var source = sources[ input.source ];
  32164. switch ( input.semantic ) {
  32165. case 'MORPH_TARGET':
  32166. this.targets = source.read();
  32167. break;
  32168. case 'MORPH_WEIGHT':
  32169. this.weights = source.read();
  32170. break;
  32171. default:
  32172. break;
  32173. }
  32174. }
  32175. return this;
  32176. };
  32177. Morph.prototype.parseInputs = function(element) {
  32178. var inputs = [];
  32179. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32180. var child = element.childNodes[i];
  32181. if ( child.nodeType != 1) continue;
  32182. switch ( child.nodeName ) {
  32183. case 'input':
  32184. inputs.push( (new Input()).parse(child) );
  32185. break;
  32186. default:
  32187. break;
  32188. }
  32189. }
  32190. return inputs;
  32191. };
  32192. function Skin() {
  32193. this.source = "";
  32194. this.bindShapeMatrix = null;
  32195. this.invBindMatrices = [];
  32196. this.joints = [];
  32197. this.weights = [];
  32198. }
  32199. Skin.prototype.parse = function( element ) {
  32200. var sources = {};
  32201. var joints, weights;
  32202. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  32203. this.invBindMatrices = [];
  32204. this.joints = [];
  32205. this.weights = [];
  32206. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32207. var child = element.childNodes[i];
  32208. if ( child.nodeType != 1 ) continue;
  32209. switch ( child.nodeName ) {
  32210. case 'bind_shape_matrix':
  32211. var f = _floats(child.textContent);
  32212. this.bindShapeMatrix = getConvertedMat4( f );
  32213. break;
  32214. case 'source':
  32215. var src = new Source().parse(child);
  32216. sources[ src.id ] = src;
  32217. break;
  32218. case 'joints':
  32219. joints = child;
  32220. break;
  32221. case 'vertex_weights':
  32222. weights = child;
  32223. break;
  32224. default:
  32225. console.log( child.nodeName );
  32226. break;
  32227. }
  32228. }
  32229. this.parseJoints( joints, sources );
  32230. this.parseWeights( weights, sources );
  32231. return this;
  32232. };
  32233. Skin.prototype.parseJoints = function ( element, sources ) {
  32234. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32235. var child = element.childNodes[ i ];
  32236. if ( child.nodeType != 1 ) continue;
  32237. switch ( child.nodeName ) {
  32238. case 'input':
  32239. var input = ( new Input() ).parse( child );
  32240. var source = sources[ input.source ];
  32241. if ( input.semantic === 'JOINT' ) {
  32242. this.joints = source.read();
  32243. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  32244. this.invBindMatrices = source.read();
  32245. }
  32246. break;
  32247. default:
  32248. break;
  32249. }
  32250. }
  32251. };
  32252. Skin.prototype.parseWeights = function ( element, sources ) {
  32253. var v, vcount, inputs = [];
  32254. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32255. var child = element.childNodes[ i ];
  32256. if ( child.nodeType != 1 ) continue;
  32257. switch ( child.nodeName ) {
  32258. case 'input':
  32259. inputs.push( ( new Input() ).parse( child ) );
  32260. break;
  32261. case 'v':
  32262. v = _ints( child.textContent );
  32263. break;
  32264. case 'vcount':
  32265. vcount = _ints( child.textContent );
  32266. break;
  32267. default:
  32268. break;
  32269. }
  32270. }
  32271. var index = 0;
  32272. for ( var i = 0; i < vcount.length; i ++ ) {
  32273. var numBones = vcount[i];
  32274. var vertex_weights = [];
  32275. for ( var j = 0; j < numBones; j ++ ) {
  32276. var influence = {};
  32277. for ( var k = 0; k < inputs.length; k ++ ) {
  32278. var input = inputs[ k ];
  32279. var value = v[ index + input.offset ];
  32280. switch ( input.semantic ) {
  32281. case 'JOINT':
  32282. influence.joint = value;//this.joints[value];
  32283. break;
  32284. case 'WEIGHT':
  32285. influence.weight = sources[ input.source ].data[ value ];
  32286. break;
  32287. default:
  32288. break;
  32289. }
  32290. }
  32291. vertex_weights.push( influence );
  32292. index += inputs.length;
  32293. }
  32294. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  32295. vertex_weights[ j ].index = i;
  32296. }
  32297. this.weights.push( vertex_weights );
  32298. }
  32299. };
  32300. function VisualScene () {
  32301. this.id = "";
  32302. this.name = "";
  32303. this.nodes = [];
  32304. this.scene = new THREE.Group();
  32305. }
  32306. VisualScene.prototype.getChildById = function( id, recursive ) {
  32307. for ( var i = 0; i < this.nodes.length; i ++ ) {
  32308. var node = this.nodes[ i ].getChildById( id, recursive );
  32309. if ( node ) {
  32310. return node;
  32311. }
  32312. }
  32313. return null;
  32314. };
  32315. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  32316. for ( var i = 0; i < this.nodes.length; i ++ ) {
  32317. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  32318. if ( node ) {
  32319. return node;
  32320. }
  32321. }
  32322. return null;
  32323. };
  32324. VisualScene.prototype.parse = function( element ) {
  32325. this.id = element.getAttribute( 'id' );
  32326. this.name = element.getAttribute( 'name' );
  32327. this.nodes = [];
  32328. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32329. var child = element.childNodes[ i ];
  32330. if ( child.nodeType != 1 ) continue;
  32331. switch ( child.nodeName ) {
  32332. case 'node':
  32333. this.nodes.push( ( new Node() ).parse( child ) );
  32334. break;
  32335. default:
  32336. break;
  32337. }
  32338. }
  32339. return this;
  32340. };
  32341. function Node() {
  32342. this.id = "";
  32343. this.name = "";
  32344. this.sid = "";
  32345. this.nodes = [];
  32346. this.controllers = [];
  32347. this.transforms = [];
  32348. this.geometries = [];
  32349. this.channels = [];
  32350. this.matrix = new THREE.Matrix4();
  32351. }
  32352. Node.prototype.getChannelForTransform = function( transformSid ) {
  32353. for ( var i = 0; i < this.channels.length; i ++ ) {
  32354. var channel = this.channels[i];
  32355. var parts = channel.target.split('/');
  32356. var id = parts.shift();
  32357. var sid = parts.shift();
  32358. var dotSyntax = (sid.indexOf(".") >= 0);
  32359. var arrSyntax = (sid.indexOf("(") >= 0);
  32360. var arrIndices;
  32361. if ( dotSyntax ) {
  32362. parts = sid.split(".");
  32363. sid = parts.shift();
  32364. } else if ( arrSyntax ) {
  32365. arrIndices = sid.split("(");
  32366. sid = arrIndices.shift();
  32367. for ( var j = 0; j < arrIndices.length; j ++ ) {
  32368. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  32369. }
  32370. }
  32371. if ( sid === transformSid ) {
  32372. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  32373. return channel;
  32374. }
  32375. }
  32376. return null;
  32377. };
  32378. Node.prototype.getChildById = function ( id, recursive ) {
  32379. if ( this.id === id ) {
  32380. return this;
  32381. }
  32382. if ( recursive ) {
  32383. for ( var i = 0; i < this.nodes.length; i ++ ) {
  32384. var n = this.nodes[ i ].getChildById( id, recursive );
  32385. if ( n ) {
  32386. return n;
  32387. }
  32388. }
  32389. }
  32390. return null;
  32391. };
  32392. Node.prototype.getChildBySid = function ( sid, recursive ) {
  32393. if ( this.sid === sid ) {
  32394. return this;
  32395. }
  32396. if ( recursive ) {
  32397. for ( var i = 0; i < this.nodes.length; i ++ ) {
  32398. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  32399. if ( n ) {
  32400. return n;
  32401. }
  32402. }
  32403. }
  32404. return null;
  32405. };
  32406. Node.prototype.getTransformBySid = function ( sid ) {
  32407. for ( var i = 0; i < this.transforms.length; i ++ ) {
  32408. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  32409. }
  32410. return null;
  32411. };
  32412. Node.prototype.parse = function( element ) {
  32413. var url;
  32414. this.id = element.getAttribute('id');
  32415. this.sid = element.getAttribute('sid');
  32416. this.name = element.getAttribute('name');
  32417. this.type = element.getAttribute('type');
  32418. this.layer = element.getAttribute('layer');
  32419. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  32420. this.nodes = [];
  32421. this.transforms = [];
  32422. this.geometries = [];
  32423. this.cameras = [];
  32424. this.lights = [];
  32425. this.controllers = [];
  32426. this.matrix = new THREE.Matrix4();
  32427. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32428. var child = element.childNodes[ i ];
  32429. if ( child.nodeType != 1 ) continue;
  32430. switch ( child.nodeName ) {
  32431. case 'node':
  32432. this.nodes.push( ( new Node() ).parse( child ) );
  32433. break;
  32434. case 'instance_camera':
  32435. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  32436. break;
  32437. case 'instance_controller':
  32438. this.controllers.push( ( new InstanceController() ).parse( child ) );
  32439. break;
  32440. case 'instance_geometry':
  32441. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  32442. break;
  32443. case 'instance_light':
  32444. this.lights.push( ( new InstanceLight() ).parse( child ) );
  32445. break;
  32446. case 'instance_node':
  32447. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  32448. var iNode = getLibraryNode( url );
  32449. if ( iNode ) {
  32450. this.nodes.push( ( new Node() ).parse( iNode )) ;
  32451. }
  32452. break;
  32453. case 'rotate':
  32454. case 'translate':
  32455. case 'scale':
  32456. case 'matrix':
  32457. case 'lookat':
  32458. case 'skew':
  32459. this.transforms.push( ( new Transform() ).parse( child ) );
  32460. break;
  32461. case 'extra':
  32462. break;
  32463. default:
  32464. console.log( child.nodeName );
  32465. break;
  32466. }
  32467. }
  32468. this.channels = getChannelsForNode( this );
  32469. bakeAnimations( this );
  32470. this.updateMatrix();
  32471. return this;
  32472. };
  32473. Node.prototype.updateMatrix = function () {
  32474. this.matrix.identity();
  32475. for ( var i = 0; i < this.transforms.length; i ++ ) {
  32476. this.transforms[ i ].apply( this.matrix );
  32477. }
  32478. };
  32479. function Transform () {
  32480. this.sid = "";
  32481. this.type = "";
  32482. this.data = [];
  32483. this.obj = null;
  32484. }
  32485. Transform.prototype.parse = function ( element ) {
  32486. this.sid = element.getAttribute( 'sid' );
  32487. this.type = element.nodeName;
  32488. this.data = _floats( element.textContent );
  32489. this.convert();
  32490. return this;
  32491. };
  32492. Transform.prototype.convert = function () {
  32493. switch ( this.type ) {
  32494. case 'matrix':
  32495. this.obj = getConvertedMat4( this.data );
  32496. break;
  32497. case 'rotate':
  32498. this.angle = THREE.Math.degToRad( this.data[3] );
  32499. case 'translate':
  32500. fixCoords( this.data, -1 );
  32501. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  32502. break;
  32503. case 'scale':
  32504. fixCoords( this.data, 1 );
  32505. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  32506. break;
  32507. default:
  32508. console.log( 'Can not convert Transform of type ' + this.type );
  32509. break;
  32510. }
  32511. };
  32512. Transform.prototype.apply = function () {
  32513. var m1 = new THREE.Matrix4();
  32514. return function ( matrix ) {
  32515. switch ( this.type ) {
  32516. case 'matrix':
  32517. matrix.multiply( this.obj );
  32518. break;
  32519. case 'translate':
  32520. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  32521. break;
  32522. case 'rotate':
  32523. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  32524. break;
  32525. case 'scale':
  32526. matrix.scale( this.obj );
  32527. break;
  32528. }
  32529. };
  32530. }();
  32531. Transform.prototype.update = function ( data, member ) {
  32532. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  32533. switch ( this.type ) {
  32534. case 'matrix':
  32535. if ( ! member ) {
  32536. this.obj.copy( data );
  32537. } else if ( member.length === 1 ) {
  32538. switch ( member[ 0 ] ) {
  32539. case 0:
  32540. this.obj.n11 = data[ 0 ];
  32541. this.obj.n21 = data[ 1 ];
  32542. this.obj.n31 = data[ 2 ];
  32543. this.obj.n41 = data[ 3 ];
  32544. break;
  32545. case 1:
  32546. this.obj.n12 = data[ 0 ];
  32547. this.obj.n22 = data[ 1 ];
  32548. this.obj.n32 = data[ 2 ];
  32549. this.obj.n42 = data[ 3 ];
  32550. break;
  32551. case 2:
  32552. this.obj.n13 = data[ 0 ];
  32553. this.obj.n23 = data[ 1 ];
  32554. this.obj.n33 = data[ 2 ];
  32555. this.obj.n43 = data[ 3 ];
  32556. break;
  32557. case 3:
  32558. this.obj.n14 = data[ 0 ];
  32559. this.obj.n24 = data[ 1 ];
  32560. this.obj.n34 = data[ 2 ];
  32561. this.obj.n44 = data[ 3 ];
  32562. break;
  32563. }
  32564. } else if ( member.length === 2 ) {
  32565. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  32566. this.obj[ propName ] = data;
  32567. } else {
  32568. console.log('Incorrect addressing of matrix in transform.');
  32569. }
  32570. break;
  32571. case 'translate':
  32572. case 'scale':
  32573. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  32574. member = members[ member[ 0 ] ];
  32575. }
  32576. switch ( member ) {
  32577. case 'X':
  32578. this.obj.x = data;
  32579. break;
  32580. case 'Y':
  32581. this.obj.y = data;
  32582. break;
  32583. case 'Z':
  32584. this.obj.z = data;
  32585. break;
  32586. default:
  32587. this.obj.x = data[ 0 ];
  32588. this.obj.y = data[ 1 ];
  32589. this.obj.z = data[ 2 ];
  32590. break;
  32591. }
  32592. break;
  32593. case 'rotate':
  32594. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  32595. member = members[ member[ 0 ] ];
  32596. }
  32597. switch ( member ) {
  32598. case 'X':
  32599. this.obj.x = data;
  32600. break;
  32601. case 'Y':
  32602. this.obj.y = data;
  32603. break;
  32604. case 'Z':
  32605. this.obj.z = data;
  32606. break;
  32607. case 'ANGLE':
  32608. this.angle = THREE.Math.degToRad( data );
  32609. break;
  32610. default:
  32611. this.obj.x = data[ 0 ];
  32612. this.obj.y = data[ 1 ];
  32613. this.obj.z = data[ 2 ];
  32614. this.angle = THREE.Math.degToRad( data[ 3 ] );
  32615. break;
  32616. }
  32617. break;
  32618. }
  32619. };
  32620. function InstanceController() {
  32621. this.url = "";
  32622. this.skeleton = [];
  32623. this.instance_material = [];
  32624. }
  32625. InstanceController.prototype.parse = function ( element ) {
  32626. this.url = element.getAttribute('url').replace(/^#/, '');
  32627. this.skeleton = [];
  32628. this.instance_material = [];
  32629. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32630. var child = element.childNodes[ i ];
  32631. if ( child.nodeType !== 1 ) continue;
  32632. switch ( child.nodeName ) {
  32633. case 'skeleton':
  32634. this.skeleton.push( child.textContent.replace(/^#/, '') );
  32635. break;
  32636. case 'bind_material':
  32637. var instances = child.querySelectorAll('instance_material');
  32638. for ( var j = 0; j < instances.length; j ++ ) {
  32639. var instance = instances[j];
  32640. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  32641. }
  32642. break;
  32643. case 'extra':
  32644. break;
  32645. default:
  32646. break;
  32647. }
  32648. }
  32649. return this;
  32650. };
  32651. function InstanceMaterial () {
  32652. this.symbol = "";
  32653. this.target = "";
  32654. }
  32655. InstanceMaterial.prototype.parse = function ( element ) {
  32656. this.symbol = element.getAttribute('symbol');
  32657. this.target = element.getAttribute('target').replace(/^#/, '');
  32658. return this;
  32659. };
  32660. function InstanceGeometry() {
  32661. this.url = "";
  32662. this.instance_material = [];
  32663. }
  32664. InstanceGeometry.prototype.parse = function ( element ) {
  32665. this.url = element.getAttribute('url').replace(/^#/, '');
  32666. this.instance_material = [];
  32667. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32668. var child = element.childNodes[i];
  32669. if ( child.nodeType != 1 ) continue;
  32670. if ( child.nodeName === 'bind_material' ) {
  32671. var instances = child.querySelectorAll('instance_material');
  32672. for ( var j = 0; j < instances.length; j ++ ) {
  32673. var instance = instances[j];
  32674. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  32675. }
  32676. break;
  32677. }
  32678. }
  32679. return this;
  32680. };
  32681. function Geometry() {
  32682. this.id = "";
  32683. this.mesh = null;
  32684. }
  32685. Geometry.prototype.parse = function ( element ) {
  32686. this.id = element.getAttribute('id');
  32687. extractDoubleSided( this, element );
  32688. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32689. var child = element.childNodes[i];
  32690. switch ( child.nodeName ) {
  32691. case 'mesh':
  32692. this.mesh = (new Mesh(this)).parse(child);
  32693. break;
  32694. case 'extra':
  32695. // console.log( child );
  32696. break;
  32697. default:
  32698. break;
  32699. }
  32700. }
  32701. return this;
  32702. };
  32703. function Mesh( geometry ) {
  32704. this.geometry = geometry.id;
  32705. this.primitives = [];
  32706. this.vertices = null;
  32707. this.geometry3js = null;
  32708. }
  32709. Mesh.prototype.parse = function ( element ) {
  32710. this.primitives = [];
  32711. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32712. var child = element.childNodes[ i ];
  32713. switch ( child.nodeName ) {
  32714. case 'source':
  32715. _source( child );
  32716. break;
  32717. case 'vertices':
  32718. this.vertices = ( new Vertices() ).parse( child );
  32719. break;
  32720. case 'linestrips':
  32721. this.primitives.push( ( new LineStrips().parse( child ) ) );
  32722. break;
  32723. case 'triangles':
  32724. this.primitives.push( ( new Triangles().parse( child ) ) );
  32725. break;
  32726. case 'polygons':
  32727. this.primitives.push( ( new Polygons().parse( child ) ) );
  32728. break;
  32729. case 'polylist':
  32730. this.primitives.push( ( new Polylist().parse( child ) ) );
  32731. break;
  32732. default:
  32733. break;
  32734. }
  32735. }
  32736. this.geometry3js = new THREE.Geometry();
  32737. if ( this.vertices === null ) {
  32738. // TODO (mrdoob): Study case when this is null (carrier.dae)
  32739. return this;
  32740. }
  32741. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  32742. for ( var i = 0; i < vertexData.length; i += 3 ) {
  32743. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  32744. }
  32745. for ( var i = 0; i < this.primitives.length; i ++ ) {
  32746. var primitive = this.primitives[ i ];
  32747. primitive.setVertices( this.vertices );
  32748. this.handlePrimitive( primitive, this.geometry3js );
  32749. }
  32750. if ( this.geometry3js.calcNormals ) {
  32751. this.geometry3js.computeVertexNormals();
  32752. delete this.geometry3js.calcNormals;
  32753. }
  32754. return this;
  32755. };
  32756. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  32757. if ( primitive instanceof LineStrips ) {
  32758. // TODO: Handle indices. Maybe easier with BufferGeometry?
  32759. geom.isLineStrip = true;
  32760. return;
  32761. }
  32762. var j, k, pList = primitive.p, inputs = primitive.inputs;
  32763. var input, index, idx32;
  32764. var source, numParams;
  32765. var vcount, vcIndex = 0, maxOffset = 0;
  32766. var texture_sets = [];
  32767. for ( j = 0; j < inputs.length; j ++ ) {
  32768. input = inputs[ j ];
  32769. var offset = input.offset + 1;
  32770. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  32771. switch ( input.semantic ) {
  32772. case 'TEXCOORD':
  32773. texture_sets.push( input.set );
  32774. break;
  32775. }
  32776. }
  32777. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  32778. var p = pList[ pCount ], i = 0;
  32779. while ( i < p.length ) {
  32780. var vs = [];
  32781. var ns = [];
  32782. var ts = null;
  32783. var cs = [];
  32784. if ( primitive.vcount ) {
  32785. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  32786. } else {
  32787. vcount = p.length / maxOffset;
  32788. }
  32789. for ( j = 0; j < vcount; j ++ ) {
  32790. for ( k = 0; k < inputs.length; k ++ ) {
  32791. input = inputs[ k ];
  32792. source = sources[ input.source ];
  32793. index = p[ i + ( j * maxOffset ) + input.offset ];
  32794. numParams = source.accessor.params.length;
  32795. idx32 = index * numParams;
  32796. switch ( input.semantic ) {
  32797. case 'VERTEX':
  32798. vs.push( index );
  32799. break;
  32800. case 'NORMAL':
  32801. ns.push( getConvertedVec3( source.data, idx32 ) );
  32802. break;
  32803. case 'TEXCOORD':
  32804. ts = ts || { };
  32805. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  32806. // invert the V
  32807. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  32808. break;
  32809. case 'COLOR':
  32810. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32811. break;
  32812. default:
  32813. break;
  32814. }
  32815. }
  32816. }
  32817. if ( ns.length === 0 ) {
  32818. // check the vertices inputs
  32819. input = this.vertices.input.NORMAL;
  32820. if ( input ) {
  32821. source = sources[ input.source ];
  32822. numParams = source.accessor.params.length;
  32823. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32824. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  32825. }
  32826. } else {
  32827. geom.calcNormals = true;
  32828. }
  32829. }
  32830. if ( !ts ) {
  32831. ts = { };
  32832. // check the vertices inputs
  32833. input = this.vertices.input.TEXCOORD;
  32834. if ( input ) {
  32835. texture_sets.push( input.set );
  32836. source = sources[ input.source ];
  32837. numParams = source.accessor.params.length;
  32838. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32839. idx32 = vs[ ndx ] * numParams;
  32840. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  32841. // invert the V
  32842. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  32843. }
  32844. }
  32845. }
  32846. if ( cs.length === 0 ) {
  32847. // check the vertices inputs
  32848. input = this.vertices.input.COLOR;
  32849. if ( input ) {
  32850. source = sources[ input.source ];
  32851. numParams = source.accessor.params.length;
  32852. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32853. idx32 = vs[ ndx ] * numParams;
  32854. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32855. }
  32856. }
  32857. }
  32858. var face = null, faces = [], uv, uvArr;
  32859. if ( vcount === 3 ) {
  32860. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  32861. } else if ( vcount === 4 ) {
  32862. faces.push( new THREE.Face3( vs[0], vs[1], vs[3], ns.length ? [ ns[0].clone(), ns[1].clone(), ns[3].clone() ] : [], cs.length ? [ cs[0], cs[1], cs[3] ] : new THREE.Color() ) );
  32863. faces.push( new THREE.Face3( vs[1], vs[2], vs[3], ns.length ? [ ns[1].clone(), ns[2].clone(), ns[3].clone() ] : [], cs.length ? [ cs[1], cs[2], cs[3] ] : new THREE.Color() ) );
  32864. } else if ( vcount > 4 && options.subdivideFaces ) {
  32865. var clr = cs.length ? cs : new THREE.Color(),
  32866. vec1, vec2, vec3, v1, v2, norm;
  32867. // subdivide into multiple Face3s
  32868. for ( k = 1; k < vcount - 1; ) {
  32869. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], ns.length ? [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ] : [], clr ) );
  32870. }
  32871. }
  32872. if ( faces.length ) {
  32873. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  32874. face = faces[ndx];
  32875. face.daeMaterial = primitive.material;
  32876. geom.faces.push( face );
  32877. for ( k = 0; k < texture_sets.length; k ++ ) {
  32878. uv = ts[ texture_sets[k] ];
  32879. if ( vcount > 4 ) {
  32880. // Grab the right UVs for the vertices in this face
  32881. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  32882. } else if ( vcount === 4 ) {
  32883. if ( ndx === 0 ) {
  32884. uvArr = [ uv[0], uv[1], uv[3] ];
  32885. } else {
  32886. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  32887. }
  32888. } else {
  32889. uvArr = [ uv[0], uv[1], uv[2] ];
  32890. }
  32891. if ( geom.faceVertexUvs[k] === undefined ) {
  32892. geom.faceVertexUvs[k] = [];
  32893. }
  32894. geom.faceVertexUvs[k].push( uvArr );
  32895. }
  32896. }
  32897. } else {
  32898. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  32899. }
  32900. i += maxOffset * vcount;
  32901. }
  32902. }
  32903. };
  32904. function Polygons () {
  32905. this.material = "";
  32906. this.count = 0;
  32907. this.inputs = [];
  32908. this.vcount = null;
  32909. this.p = [];
  32910. this.geometry = new THREE.Geometry();
  32911. }
  32912. Polygons.prototype.setVertices = function ( vertices ) {
  32913. for ( var i = 0; i < this.inputs.length; i ++ ) {
  32914. if ( this.inputs[ i ].source === vertices.id ) {
  32915. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  32916. }
  32917. }
  32918. };
  32919. Polygons.prototype.parse = function ( element ) {
  32920. this.material = element.getAttribute( 'material' );
  32921. this.count = _attr_as_int( element, 'count', 0 );
  32922. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32923. var child = element.childNodes[ i ];
  32924. switch ( child.nodeName ) {
  32925. case 'input':
  32926. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  32927. break;
  32928. case 'vcount':
  32929. this.vcount = _ints( child.textContent );
  32930. break;
  32931. case 'p':
  32932. this.p.push( _ints( child.textContent ) );
  32933. break;
  32934. case 'ph':
  32935. console.warn( 'polygon holes not yet supported!' );
  32936. break;
  32937. default:
  32938. break;
  32939. }
  32940. }
  32941. return this;
  32942. };
  32943. function Polylist () {
  32944. Polygons.call( this );
  32945. this.vcount = [];
  32946. }
  32947. Polylist.prototype = Object.create( Polygons.prototype );
  32948. Polylist.prototype.constructor = Polylist;
  32949. function LineStrips() {
  32950. Polygons.call( this );
  32951. this.vcount = 1;
  32952. }
  32953. LineStrips.prototype = Object.create( Polygons.prototype );
  32954. LineStrips.prototype.constructor = LineStrips;
  32955. function Triangles () {
  32956. Polygons.call( this );
  32957. this.vcount = 3;
  32958. }
  32959. Triangles.prototype = Object.create( Polygons.prototype );
  32960. Triangles.prototype.constructor = Triangles;
  32961. function Accessor() {
  32962. this.source = "";
  32963. this.count = 0;
  32964. this.stride = 0;
  32965. this.params = [];
  32966. }
  32967. Accessor.prototype.parse = function ( element ) {
  32968. this.params = [];
  32969. this.source = element.getAttribute( 'source' );
  32970. this.count = _attr_as_int( element, 'count', 0 );
  32971. this.stride = _attr_as_int( element, 'stride', 0 );
  32972. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32973. var child = element.childNodes[ i ];
  32974. if ( child.nodeName === 'param' ) {
  32975. var param = {};
  32976. param[ 'name' ] = child.getAttribute( 'name' );
  32977. param[ 'type' ] = child.getAttribute( 'type' );
  32978. this.params.push( param );
  32979. }
  32980. }
  32981. return this;
  32982. };
  32983. function Vertices() {
  32984. this.input = {};
  32985. }
  32986. Vertices.prototype.parse = function ( element ) {
  32987. this.id = element.getAttribute('id');
  32988. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32989. if ( element.childNodes[i].nodeName === 'input' ) {
  32990. var input = ( new Input() ).parse( element.childNodes[ i ] );
  32991. this.input[ input.semantic ] = input;
  32992. }
  32993. }
  32994. return this;
  32995. };
  32996. function Input () {
  32997. this.semantic = "";
  32998. this.offset = 0;
  32999. this.source = "";
  33000. this.set = 0;
  33001. }
  33002. Input.prototype.parse = function ( element ) {
  33003. this.semantic = element.getAttribute('semantic');
  33004. this.source = element.getAttribute('source').replace(/^#/, '');
  33005. this.set = _attr_as_int(element, 'set', -1);
  33006. this.offset = _attr_as_int(element, 'offset', 0);
  33007. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  33008. this.set = 0;
  33009. }
  33010. return this;
  33011. };
  33012. function Source ( id ) {
  33013. this.id = id;
  33014. this.type = null;
  33015. }
  33016. Source.prototype.parse = function ( element ) {
  33017. this.id = element.getAttribute( 'id' );
  33018. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33019. var child = element.childNodes[i];
  33020. switch ( child.nodeName ) {
  33021. case 'bool_array':
  33022. this.data = _bools( child.textContent );
  33023. this.type = child.nodeName;
  33024. break;
  33025. case 'float_array':
  33026. this.data = _floats( child.textContent );
  33027. this.type = child.nodeName;
  33028. break;
  33029. case 'int_array':
  33030. this.data = _ints( child.textContent );
  33031. this.type = child.nodeName;
  33032. break;
  33033. case 'IDREF_array':
  33034. case 'Name_array':
  33035. this.data = _strings( child.textContent );
  33036. this.type = child.nodeName;
  33037. break;
  33038. case 'technique_common':
  33039. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  33040. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  33041. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  33042. break;
  33043. }
  33044. }
  33045. break;
  33046. default:
  33047. // console.log(child.nodeName);
  33048. break;
  33049. }
  33050. }
  33051. return this;
  33052. };
  33053. Source.prototype.read = function () {
  33054. var result = [];
  33055. //for (var i = 0; i < this.accessor.params.length; i++) {
  33056. var param = this.accessor.params[ 0 ];
  33057. //console.log(param.name + " " + param.type);
  33058. switch ( param.type ) {
  33059. case 'IDREF':
  33060. case 'Name': case 'name':
  33061. case 'float':
  33062. return this.data;
  33063. case 'float4x4':
  33064. for ( var j = 0; j < this.data.length; j += 16 ) {
  33065. var s = this.data.slice( j, j + 16 );
  33066. var m = getConvertedMat4( s );
  33067. result.push( m );
  33068. }
  33069. break;
  33070. default:
  33071. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  33072. break;
  33073. }
  33074. //}
  33075. return result;
  33076. };
  33077. function Material () {
  33078. this.id = "";
  33079. this.name = "";
  33080. this.instance_effect = null;
  33081. }
  33082. Material.prototype.parse = function ( element ) {
  33083. this.id = element.getAttribute( 'id' );
  33084. this.name = element.getAttribute( 'name' );
  33085. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33086. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  33087. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  33088. break;
  33089. }
  33090. }
  33091. return this;
  33092. };
  33093. function ColorOrTexture () {
  33094. this.color = new THREE.Color();
  33095. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  33096. this.color.a = 1.0;
  33097. this.texture = null;
  33098. this.texcoord = null;
  33099. this.texOpts = null;
  33100. }
  33101. ColorOrTexture.prototype.isColor = function () {
  33102. return ( this.texture === null );
  33103. };
  33104. ColorOrTexture.prototype.isTexture = function () {
  33105. return ( this.texture != null );
  33106. };
  33107. ColorOrTexture.prototype.parse = function ( element ) {
  33108. if (element.nodeName === 'transparent') {
  33109. this.opaque = element.getAttribute('opaque');
  33110. }
  33111. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33112. var child = element.childNodes[ i ];
  33113. if ( child.nodeType != 1 ) continue;
  33114. switch ( child.nodeName ) {
  33115. case 'color':
  33116. var rgba = _floats( child.textContent );
  33117. this.color = new THREE.Color();
  33118. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  33119. this.color.a = rgba[3];
  33120. break;
  33121. case 'texture':
  33122. this.texture = child.getAttribute('texture');
  33123. this.texcoord = child.getAttribute('texcoord');
  33124. // Defaults from:
  33125. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  33126. this.texOpts = {
  33127. offsetU: 0,
  33128. offsetV: 0,
  33129. repeatU: 1,
  33130. repeatV: 1,
  33131. wrapU: 1,
  33132. wrapV: 1
  33133. };
  33134. this.parseTexture( child );
  33135. break;
  33136. default:
  33137. break;
  33138. }
  33139. }
  33140. return this;
  33141. };
  33142. ColorOrTexture.prototype.parseTexture = function ( element ) {
  33143. if ( ! element.childNodes ) return this;
  33144. // This should be supported by Maya, 3dsMax, and MotionBuilder
  33145. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  33146. element = element.childNodes[1];
  33147. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  33148. element = element.childNodes[1];
  33149. }
  33150. }
  33151. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33152. var child = element.childNodes[ i ];
  33153. switch ( child.nodeName ) {
  33154. case 'offsetU':
  33155. case 'offsetV':
  33156. case 'repeatU':
  33157. case 'repeatV':
  33158. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  33159. break;
  33160. case 'wrapU':
  33161. case 'wrapV':
  33162. // some dae have a value of true which becomes NaN via parseInt
  33163. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  33164. this.texOpts[ child.nodeName ] = 1;
  33165. } else {
  33166. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  33167. }
  33168. break;
  33169. default:
  33170. this.texOpts[ child.nodeName ] = child.textContent;
  33171. break;
  33172. }
  33173. }
  33174. return this;
  33175. };
  33176. function Shader ( type, effect ) {
  33177. this.type = type;
  33178. this.effect = effect;
  33179. this.material = null;
  33180. }
  33181. Shader.prototype.parse = function ( element ) {
  33182. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33183. var child = element.childNodes[ i ];
  33184. if ( child.nodeType != 1 ) continue;
  33185. switch ( child.nodeName ) {
  33186. case 'emission':
  33187. case 'diffuse':
  33188. case 'specular':
  33189. case 'transparent':
  33190. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  33191. break;
  33192. case 'bump':
  33193. // If 'bumptype' is 'heightfield', create a 'bump' property
  33194. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  33195. // (Default to 'bump')
  33196. var bumpType = child.getAttribute( 'bumptype' );
  33197. if ( bumpType ) {
  33198. if ( bumpType.toLowerCase() === "heightfield" ) {
  33199. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  33200. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  33201. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  33202. } else {
  33203. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  33204. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  33205. }
  33206. } else {
  33207. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  33208. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  33209. }
  33210. break;
  33211. case 'shininess':
  33212. case 'reflectivity':
  33213. case 'index_of_refraction':
  33214. case 'transparency':
  33215. var f = child.querySelectorAll('float');
  33216. if ( f.length > 0 )
  33217. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  33218. break;
  33219. default:
  33220. break;
  33221. }
  33222. }
  33223. this.create();
  33224. return this;
  33225. };
  33226. Shader.prototype.create = function() {
  33227. var props = {};
  33228. var transparent = false;
  33229. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  33230. // convert transparent color RBG to average value
  33231. var transparentColor = this['transparent'];
  33232. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  33233. if (transparencyLevel > 0) {
  33234. transparent = true;
  33235. props[ 'transparent' ] = true;
  33236. props[ 'opacity' ] = 1 - transparencyLevel;
  33237. }
  33238. }
  33239. var keys = {
  33240. 'diffuse':'map',
  33241. 'ambient':'lightMap',
  33242. 'specular':'specularMap',
  33243. 'emission':'emissionMap',
  33244. 'bump':'bumpMap',
  33245. 'normal':'normalMap'
  33246. };
  33247. for ( var prop in this ) {
  33248. switch ( prop ) {
  33249. case 'ambient':
  33250. case 'emission':
  33251. case 'diffuse':
  33252. case 'specular':
  33253. case 'bump':
  33254. case 'normal':
  33255. var cot = this[ prop ];
  33256. if ( cot instanceof ColorOrTexture ) {
  33257. if ( cot.isTexture() ) {
  33258. var samplerId = cot.texture;
  33259. var sampler = this.effect.sampler[samplerId];
  33260. if ( sampler !== undefined && sampler.source !== undefined ) {
  33261. var surface = this.effect.surface[sampler.source];
  33262. if ( surface !== undefined ) {
  33263. var image = images[ surface.init_from ];
  33264. if ( image ) {
  33265. var url = baseUrl + image.init_from;
  33266. var texture;
  33267. var loader = THREE.Loader.Handlers.get( url );
  33268. if ( loader !== null ) {
  33269. texture = loader.load( url );
  33270. } else {
  33271. texture = new THREE.Texture();
  33272. loadTextureImage( texture, url );
  33273. }
  33274. if ( sampler.wrap_s === "MIRROR" ) {
  33275. texture.wrapS = THREE.MirroredRepeatWrapping;
  33276. } else if ( sampler.wrap_s === "WRAP" || cot.texOpts.wrapU ) {
  33277. texture.wrapS = THREE.RepeatWrapping;
  33278. } else {
  33279. texture.wrapS = THREE.ClampToEdgeWrapping;
  33280. }
  33281. if ( sampler.wrap_t === "MIRROR" ) {
  33282. texture.wrapT = THREE.MirroredRepeatWrapping;
  33283. } else if ( sampler.wrap_t === "WRAP" || cot.texOpts.wrapV ) {
  33284. texture.wrapT = THREE.RepeatWrapping;
  33285. } else {
  33286. texture.wrapT = THREE.ClampToEdgeWrapping;
  33287. }
  33288. texture.offset.x = cot.texOpts.offsetU;
  33289. texture.offset.y = cot.texOpts.offsetV;
  33290. texture.repeat.x = cot.texOpts.repeatU;
  33291. texture.repeat.y = cot.texOpts.repeatV;
  33292. props[keys[prop]] = texture;
  33293. // Texture with baked lighting?
  33294. if (prop === 'emission') props['emissive'] = 0xffffff;
  33295. }
  33296. }
  33297. }
  33298. } else if ( prop === 'diffuse' || !transparent ) {
  33299. if ( prop === 'emission' ) {
  33300. props[ 'emissive' ] = cot.color.getHex();
  33301. } else {
  33302. props[ prop ] = cot.color.getHex();
  33303. }
  33304. }
  33305. }
  33306. break;
  33307. case 'shininess':
  33308. props[ prop ] = this[ prop ];
  33309. break;
  33310. case 'reflectivity':
  33311. props[ prop ] = this[ prop ];
  33312. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  33313. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  33314. break;
  33315. case 'index_of_refraction':
  33316. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  33317. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  33318. break;
  33319. case 'transparency':
  33320. // gets figured out up top
  33321. break;
  33322. default:
  33323. break;
  33324. }
  33325. }
  33326. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  33327. if ( props.diffuse !== undefined ) {
  33328. props.color = props.diffuse;
  33329. delete props.diffuse;
  33330. }
  33331. switch ( this.type ) {
  33332. case 'constant':
  33333. if (props.emissive != undefined) props.color = props.emissive;
  33334. this.material = new THREE.MeshBasicMaterial( props );
  33335. break;
  33336. case 'phong':
  33337. case 'blinn':
  33338. this.material = new THREE.MeshPhongMaterial( props );
  33339. break;
  33340. case 'lambert':
  33341. default:
  33342. this.material = new THREE.MeshLambertMaterial( props );
  33343. break;
  33344. }
  33345. return this.material;
  33346. };
  33347. function Surface ( effect ) {
  33348. this.effect = effect;
  33349. this.init_from = null;
  33350. this.format = null;
  33351. }
  33352. Surface.prototype.parse = function ( element ) {
  33353. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33354. var child = element.childNodes[ i ];
  33355. if ( child.nodeType != 1 ) continue;
  33356. switch ( child.nodeName ) {
  33357. case 'init_from':
  33358. this.init_from = child.textContent;
  33359. break;
  33360. case 'format':
  33361. this.format = child.textContent;
  33362. break;
  33363. default:
  33364. console.log( "unhandled Surface prop: " + child.nodeName );
  33365. break;
  33366. }
  33367. }
  33368. return this;
  33369. };
  33370. function Sampler2D ( effect ) {
  33371. this.effect = effect;
  33372. this.source = null;
  33373. this.wrap_s = null;
  33374. this.wrap_t = null;
  33375. this.minfilter = null;
  33376. this.magfilter = null;
  33377. this.mipfilter = null;
  33378. }
  33379. Sampler2D.prototype.parse = function ( element ) {
  33380. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33381. var child = element.childNodes[ i ];
  33382. if ( child.nodeType != 1 ) continue;
  33383. switch ( child.nodeName ) {
  33384. case 'source':
  33385. this.source = child.textContent;
  33386. break;
  33387. case 'minfilter':
  33388. this.minfilter = child.textContent;
  33389. break;
  33390. case 'magfilter':
  33391. this.magfilter = child.textContent;
  33392. break;
  33393. case 'mipfilter':
  33394. this.mipfilter = child.textContent;
  33395. break;
  33396. case 'wrap_s':
  33397. this.wrap_s = child.textContent;
  33398. break;
  33399. case 'wrap_t':
  33400. this.wrap_t = child.textContent;
  33401. break;
  33402. default:
  33403. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  33404. break;
  33405. }
  33406. }
  33407. return this;
  33408. };
  33409. function Effect () {
  33410. this.id = "";
  33411. this.name = "";
  33412. this.shader = null;
  33413. this.surface = {};
  33414. this.sampler = {};
  33415. }
  33416. Effect.prototype.create = function () {
  33417. if ( this.shader === null ) {
  33418. return null;
  33419. }
  33420. };
  33421. Effect.prototype.parse = function ( element ) {
  33422. this.id = element.getAttribute( 'id' );
  33423. this.name = element.getAttribute( 'name' );
  33424. extractDoubleSided( this, element );
  33425. this.shader = null;
  33426. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33427. var child = element.childNodes[ i ];
  33428. if ( child.nodeType != 1 ) continue;
  33429. switch ( child.nodeName ) {
  33430. case 'profile_COMMON':
  33431. this.parseTechnique( this.parseProfileCOMMON( child ) );
  33432. break;
  33433. default:
  33434. break;
  33435. }
  33436. }
  33437. return this;
  33438. };
  33439. Effect.prototype.parseNewparam = function ( element ) {
  33440. var sid = element.getAttribute( 'sid' );
  33441. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33442. var child = element.childNodes[ i ];
  33443. if ( child.nodeType != 1 ) continue;
  33444. switch ( child.nodeName ) {
  33445. case 'surface':
  33446. this.surface[sid] = ( new Surface( this ) ).parse( child );
  33447. break;
  33448. case 'sampler2D':
  33449. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  33450. break;
  33451. case 'extra':
  33452. break;
  33453. default:
  33454. console.log( child.nodeName );
  33455. break;
  33456. }
  33457. }
  33458. };
  33459. Effect.prototype.parseProfileCOMMON = function ( element ) {
  33460. var technique;
  33461. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33462. var child = element.childNodes[ i ];
  33463. if ( child.nodeType != 1 ) continue;
  33464. switch ( child.nodeName ) {
  33465. case 'profile_COMMON':
  33466. this.parseProfileCOMMON( child );
  33467. break;
  33468. case 'technique':
  33469. technique = child;
  33470. break;
  33471. case 'newparam':
  33472. this.parseNewparam( child );
  33473. break;
  33474. case 'image':
  33475. var _image = ( new _Image() ).parse( child );
  33476. images[ _image.id ] = _image;
  33477. break;
  33478. case 'extra':
  33479. break;
  33480. default:
  33481. console.log( child.nodeName );
  33482. break;
  33483. }
  33484. }
  33485. return technique;
  33486. };
  33487. Effect.prototype.parseTechnique = function ( element ) {
  33488. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33489. var child = element.childNodes[i];
  33490. if ( child.nodeType != 1 ) continue;
  33491. switch ( child.nodeName ) {
  33492. case 'constant':
  33493. case 'lambert':
  33494. case 'blinn':
  33495. case 'phong':
  33496. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  33497. break;
  33498. case 'extra':
  33499. this.parseExtra(child);
  33500. break;
  33501. default:
  33502. break;
  33503. }
  33504. }
  33505. };
  33506. Effect.prototype.parseExtra = function ( element ) {
  33507. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33508. var child = element.childNodes[i];
  33509. if ( child.nodeType != 1 ) continue;
  33510. switch ( child.nodeName ) {
  33511. case 'technique':
  33512. this.parseExtraTechnique( child );
  33513. break;
  33514. default:
  33515. break;
  33516. }
  33517. }
  33518. };
  33519. Effect.prototype.parseExtraTechnique = function ( element ) {
  33520. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33521. var child = element.childNodes[i];
  33522. if ( child.nodeType != 1 ) continue;
  33523. switch ( child.nodeName ) {
  33524. case 'bump':
  33525. this.shader.parse( element );
  33526. break;
  33527. default:
  33528. break;
  33529. }
  33530. }
  33531. };
  33532. function InstanceEffect () {
  33533. this.url = "";
  33534. }
  33535. InstanceEffect.prototype.parse = function ( element ) {
  33536. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  33537. return this;
  33538. };
  33539. function Animation() {
  33540. this.id = "";
  33541. this.name = "";
  33542. this.source = {};
  33543. this.sampler = [];
  33544. this.channel = [];
  33545. }
  33546. Animation.prototype.parse = function ( element ) {
  33547. this.id = element.getAttribute( 'id' );
  33548. this.name = element.getAttribute( 'name' );
  33549. this.source = {};
  33550. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33551. var child = element.childNodes[ i ];
  33552. if ( child.nodeType != 1 ) continue;
  33553. switch ( child.nodeName ) {
  33554. case 'animation':
  33555. var anim = ( new Animation() ).parse( child );
  33556. for ( var src in anim.source ) {
  33557. this.source[ src ] = anim.source[ src ];
  33558. }
  33559. for ( var j = 0; j < anim.channel.length; j ++ ) {
  33560. this.channel.push( anim.channel[ j ] );
  33561. this.sampler.push( anim.sampler[ j ] );
  33562. }
  33563. break;
  33564. case 'source':
  33565. var src = ( new Source() ).parse( child );
  33566. this.source[ src.id ] = src;
  33567. break;
  33568. case 'sampler':
  33569. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  33570. break;
  33571. case 'channel':
  33572. this.channel.push( ( new Channel( this ) ).parse( child ) );
  33573. break;
  33574. default:
  33575. break;
  33576. }
  33577. }
  33578. return this;
  33579. };
  33580. function Channel( animation ) {
  33581. this.animation = animation;
  33582. this.source = "";
  33583. this.target = "";
  33584. this.fullSid = null;
  33585. this.sid = null;
  33586. this.dotSyntax = null;
  33587. this.arrSyntax = null;
  33588. this.arrIndices = null;
  33589. this.member = null;
  33590. }
  33591. Channel.prototype.parse = function ( element ) {
  33592. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  33593. this.target = element.getAttribute( 'target' );
  33594. var parts = this.target.split( '/' );
  33595. var id = parts.shift();
  33596. var sid = parts.shift();
  33597. var dotSyntax = ( sid.indexOf(".") >= 0 );
  33598. var arrSyntax = ( sid.indexOf("(") >= 0 );
  33599. if ( dotSyntax ) {
  33600. parts = sid.split(".");
  33601. this.sid = parts.shift();
  33602. this.member = parts.shift();
  33603. } else if ( arrSyntax ) {
  33604. var arrIndices = sid.split("(");
  33605. this.sid = arrIndices.shift();
  33606. for (var j = 0; j < arrIndices.length; j ++ ) {
  33607. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  33608. }
  33609. this.arrIndices = arrIndices;
  33610. } else {
  33611. this.sid = sid;
  33612. }
  33613. this.fullSid = sid;
  33614. this.dotSyntax = dotSyntax;
  33615. this.arrSyntax = arrSyntax;
  33616. return this;
  33617. };
  33618. function Sampler ( animation ) {
  33619. this.id = "";
  33620. this.animation = animation;
  33621. this.inputs = [];
  33622. this.input = null;
  33623. this.output = null;
  33624. this.strideOut = null;
  33625. this.interpolation = null;
  33626. this.startTime = null;
  33627. this.endTime = null;
  33628. this.duration = 0;
  33629. }
  33630. Sampler.prototype.parse = function ( element ) {
  33631. this.id = element.getAttribute( 'id' );
  33632. this.inputs = [];
  33633. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33634. var child = element.childNodes[ i ];
  33635. if ( child.nodeType != 1 ) continue;
  33636. switch ( child.nodeName ) {
  33637. case 'input':
  33638. this.inputs.push( (new Input()).parse( child ) );
  33639. break;
  33640. default:
  33641. break;
  33642. }
  33643. }
  33644. return this;
  33645. };
  33646. Sampler.prototype.create = function () {
  33647. for ( var i = 0; i < this.inputs.length; i ++ ) {
  33648. var input = this.inputs[ i ];
  33649. var source = this.animation.source[ input.source ];
  33650. switch ( input.semantic ) {
  33651. case 'INPUT':
  33652. this.input = source.read();
  33653. break;
  33654. case 'OUTPUT':
  33655. this.output = source.read();
  33656. this.strideOut = source.accessor.stride;
  33657. break;
  33658. case 'INTERPOLATION':
  33659. this.interpolation = source.read();
  33660. break;
  33661. case 'IN_TANGENT':
  33662. break;
  33663. case 'OUT_TANGENT':
  33664. break;
  33665. default:
  33666. console.log(input.semantic);
  33667. break;
  33668. }
  33669. }
  33670. this.startTime = 0;
  33671. this.endTime = 0;
  33672. this.duration = 0;
  33673. if ( this.input.length ) {
  33674. this.startTime = 100000000;
  33675. this.endTime = -100000000;
  33676. for ( var i = 0; i < this.input.length; i ++ ) {
  33677. this.startTime = Math.min( this.startTime, this.input[ i ] );
  33678. this.endTime = Math.max( this.endTime, this.input[ i ] );
  33679. }
  33680. this.duration = this.endTime - this.startTime;
  33681. }
  33682. };
  33683. Sampler.prototype.getData = function ( type, ndx, member ) {
  33684. var data;
  33685. if ( type === 'matrix' && this.strideOut === 16 ) {
  33686. data = this.output[ ndx ];
  33687. } else if ( this.strideOut > 1 ) {
  33688. data = [];
  33689. ndx *= this.strideOut;
  33690. for ( var i = 0; i < this.strideOut; ++ i ) {
  33691. data[ i ] = this.output[ ndx + i ];
  33692. }
  33693. if ( this.strideOut === 3 ) {
  33694. switch ( type ) {
  33695. case 'rotate':
  33696. case 'translate':
  33697. fixCoords( data, -1 );
  33698. break;
  33699. case 'scale':
  33700. fixCoords( data, 1 );
  33701. break;
  33702. }
  33703. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  33704. fixCoords( data, -1 );
  33705. }
  33706. } else {
  33707. data = this.output[ ndx ];
  33708. if ( member && type === 'translate' ) {
  33709. data = getConvertedTranslation( member, data );
  33710. }
  33711. }
  33712. return data;
  33713. };
  33714. function Key ( time ) {
  33715. this.targets = [];
  33716. this.time = time;
  33717. }
  33718. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  33719. this.targets.push( {
  33720. sid: fullSid,
  33721. member: member,
  33722. transform: transform,
  33723. data: data
  33724. } );
  33725. };
  33726. Key.prototype.apply = function ( opt_sid ) {
  33727. for ( var i = 0; i < this.targets.length; ++ i ) {
  33728. var target = this.targets[ i ];
  33729. if ( !opt_sid || target.sid === opt_sid ) {
  33730. target.transform.update( target.data, target.member );
  33731. }
  33732. }
  33733. };
  33734. Key.prototype.getTarget = function ( fullSid ) {
  33735. for ( var i = 0; i < this.targets.length; ++ i ) {
  33736. if ( this.targets[ i ].sid === fullSid ) {
  33737. return this.targets[ i ];
  33738. }
  33739. }
  33740. return null;
  33741. };
  33742. Key.prototype.hasTarget = function ( fullSid ) {
  33743. for ( var i = 0; i < this.targets.length; ++ i ) {
  33744. if ( this.targets[ i ].sid === fullSid ) {
  33745. return true;
  33746. }
  33747. }
  33748. return false;
  33749. };
  33750. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  33751. Key.prototype.interpolate = function ( nextKey, time ) {
  33752. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  33753. var target = this.targets[ i ],
  33754. nextTarget = nextKey.getTarget( target.sid ),
  33755. data;
  33756. if ( target.transform.type !== 'matrix' && nextTarget ) {
  33757. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  33758. nextData = nextTarget.data,
  33759. prevData = target.data;
  33760. if ( scale < 0 ) scale = 0;
  33761. if ( scale > 1 ) scale = 1;
  33762. if ( prevData.length ) {
  33763. data = [];
  33764. for ( var j = 0; j < prevData.length; ++ j ) {
  33765. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  33766. }
  33767. } else {
  33768. data = prevData + ( nextData - prevData ) * scale;
  33769. }
  33770. } else {
  33771. data = target.data;
  33772. }
  33773. target.transform.update( data, target.member );
  33774. }
  33775. };
  33776. // Camera
  33777. function Camera() {
  33778. this.id = "";
  33779. this.name = "";
  33780. this.technique = "";
  33781. }
  33782. Camera.prototype.parse = function ( element ) {
  33783. this.id = element.getAttribute( 'id' );
  33784. this.name = element.getAttribute( 'name' );
  33785. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33786. var child = element.childNodes[ i ];
  33787. if ( child.nodeType != 1 ) continue;
  33788. switch ( child.nodeName ) {
  33789. case 'optics':
  33790. this.parseOptics( child );
  33791. break;
  33792. default:
  33793. break;
  33794. }
  33795. }
  33796. return this;
  33797. };
  33798. Camera.prototype.parseOptics = function ( element ) {
  33799. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33800. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  33801. var technique = element.childNodes[ i ];
  33802. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  33803. this.technique = technique.childNodes[ j ].nodeName;
  33804. if ( this.technique === 'perspective' ) {
  33805. var perspective = technique.childNodes[ j ];
  33806. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  33807. var param = perspective.childNodes[ k ];
  33808. switch ( param.nodeName ) {
  33809. case 'yfov':
  33810. this.yfov = param.textContent;
  33811. break;
  33812. case 'xfov':
  33813. this.xfov = param.textContent;
  33814. break;
  33815. case 'znear':
  33816. this.znear = param.textContent;
  33817. break;
  33818. case 'zfar':
  33819. this.zfar = param.textContent;
  33820. break;
  33821. case 'aspect_ratio':
  33822. this.aspect_ratio = param.textContent;
  33823. break;
  33824. }
  33825. }
  33826. } else if ( this.technique === 'orthographic' ) {
  33827. var orthographic = technique.childNodes[ j ];
  33828. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  33829. var param = orthographic.childNodes[ k ];
  33830. switch ( param.nodeName ) {
  33831. case 'xmag':
  33832. this.xmag = param.textContent;
  33833. break;
  33834. case 'ymag':
  33835. this.ymag = param.textContent;
  33836. break;
  33837. case 'znear':
  33838. this.znear = param.textContent;
  33839. break;
  33840. case 'zfar':
  33841. this.zfar = param.textContent;
  33842. break;
  33843. case 'aspect_ratio':
  33844. this.aspect_ratio = param.textContent;
  33845. break;
  33846. }
  33847. }
  33848. }
  33849. }
  33850. }
  33851. }
  33852. return this;
  33853. };
  33854. function InstanceCamera() {
  33855. this.url = "";
  33856. }
  33857. InstanceCamera.prototype.parse = function ( element ) {
  33858. this.url = element.getAttribute('url').replace(/^#/, '');
  33859. return this;
  33860. };
  33861. // Light
  33862. function Light() {
  33863. this.id = "";
  33864. this.name = "";
  33865. this.technique = "";
  33866. }
  33867. Light.prototype.parse = function ( element ) {
  33868. this.id = element.getAttribute( 'id' );
  33869. this.name = element.getAttribute( 'name' );
  33870. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33871. var child = element.childNodes[ i ];
  33872. if ( child.nodeType != 1 ) continue;
  33873. switch ( child.nodeName ) {
  33874. case 'technique_common':
  33875. this.parseCommon( child );
  33876. break;
  33877. case 'technique':
  33878. this.parseTechnique( child );
  33879. break;
  33880. default:
  33881. break;
  33882. }
  33883. }
  33884. return this;
  33885. };
  33886. Light.prototype.parseCommon = function ( element ) {
  33887. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33888. switch ( element.childNodes[ i ].nodeName ) {
  33889. case 'directional':
  33890. case 'point':
  33891. case 'spot':
  33892. case 'ambient':
  33893. this.technique = element.childNodes[ i ].nodeName;
  33894. var light = element.childNodes[ i ];
  33895. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  33896. var child = light.childNodes[j];
  33897. switch ( child.nodeName ) {
  33898. case 'color':
  33899. var rgba = _floats( child.textContent );
  33900. this.color = new THREE.Color(0);
  33901. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  33902. this.color.a = rgba[3];
  33903. break;
  33904. case 'falloff_angle':
  33905. this.falloff_angle = parseFloat( child.textContent );
  33906. break;
  33907. case 'quadratic_attenuation':
  33908. var f = parseFloat( child.textContent );
  33909. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  33910. }
  33911. }
  33912. }
  33913. }
  33914. return this;
  33915. };
  33916. Light.prototype.parseTechnique = function ( element ) {
  33917. this.profile = element.getAttribute( 'profile' );
  33918. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33919. var child = element.childNodes[ i ];
  33920. switch ( child.nodeName ) {
  33921. case 'intensity':
  33922. this.intensity = parseFloat(child.textContent);
  33923. break;
  33924. }
  33925. }
  33926. return this;
  33927. };
  33928. function InstanceLight() {
  33929. this.url = "";
  33930. }
  33931. InstanceLight.prototype.parse = function ( element ) {
  33932. this.url = element.getAttribute('url').replace(/^#/, '');
  33933. return this;
  33934. };
  33935. function KinematicsModel( ) {
  33936. this.id = '';
  33937. this.name = '';
  33938. this.joints = [];
  33939. this.links = [];
  33940. }
  33941. KinematicsModel.prototype.parse = function( element ) {
  33942. this.id = element.getAttribute('id');
  33943. this.name = element.getAttribute('name');
  33944. this.joints = [];
  33945. this.links = [];
  33946. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33947. var child = element.childNodes[ i ];
  33948. if ( child.nodeType != 1 ) continue;
  33949. switch ( child.nodeName ) {
  33950. case 'technique_common':
  33951. this.parseCommon(child);
  33952. break;
  33953. default:
  33954. break;
  33955. }
  33956. }
  33957. return this;
  33958. };
  33959. KinematicsModel.prototype.parseCommon = function( element ) {
  33960. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33961. var child = element.childNodes[ i ];
  33962. if ( child.nodeType != 1 ) continue;
  33963. switch ( element.childNodes[ i ].nodeName ) {
  33964. case 'joint':
  33965. this.joints.push( (new Joint()).parse(child) );
  33966. break;
  33967. case 'link':
  33968. this.links.push( (new Link()).parse(child) );
  33969. break;
  33970. default:
  33971. break;
  33972. }
  33973. }
  33974. return this;
  33975. };
  33976. function Joint( ) {
  33977. this.sid = '';
  33978. this.name = '';
  33979. this.axis = new THREE.Vector3();
  33980. this.limits = {
  33981. min: 0,
  33982. max: 0
  33983. };
  33984. this.type = '';
  33985. this.static = false;
  33986. this.zeroPosition = 0.0;
  33987. this.middlePosition = 0.0;
  33988. }
  33989. Joint.prototype.parse = function( element ) {
  33990. this.sid = element.getAttribute('sid');
  33991. this.name = element.getAttribute('name');
  33992. this.axis = new THREE.Vector3();
  33993. this.limits = {
  33994. min: 0,
  33995. max: 0
  33996. };
  33997. this.type = '';
  33998. this.static = false;
  33999. this.zeroPosition = 0.0;
  34000. this.middlePosition = 0.0;
  34001. var axisElement = element.querySelector('axis');
  34002. var _axis = _floats(axisElement.textContent);
  34003. this.axis = getConvertedVec3(_axis, 0);
  34004. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  34005. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  34006. this.limits = {
  34007. min: min,
  34008. max: max
  34009. };
  34010. var jointTypes = [ 'prismatic', 'revolute' ];
  34011. for (var i = 0; i < jointTypes.length; i ++ ) {
  34012. var type = jointTypes[ i ];
  34013. var jointElement = element.querySelector(type);
  34014. if ( jointElement ) {
  34015. this.type = type;
  34016. }
  34017. }
  34018. // if the min is equal to or somehow greater than the max, consider the joint static
  34019. if ( this.limits.min >= this.limits.max ) {
  34020. this.static = true;
  34021. }
  34022. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  34023. return this;
  34024. };
  34025. function Link( ) {
  34026. this.sid = '';
  34027. this.name = '';
  34028. this.transforms = [];
  34029. this.attachments = [];
  34030. }
  34031. Link.prototype.parse = function( element ) {
  34032. this.sid = element.getAttribute('sid');
  34033. this.name = element.getAttribute('name');
  34034. this.transforms = [];
  34035. this.attachments = [];
  34036. for (var i = 0; i < element.childNodes.length; i ++ ) {
  34037. var child = element.childNodes[ i ];
  34038. if ( child.nodeType != 1 ) continue;
  34039. switch ( child.nodeName ) {
  34040. case 'attachment_full':
  34041. this.attachments.push( (new Attachment()).parse(child) );
  34042. break;
  34043. case 'rotate':
  34044. case 'translate':
  34045. case 'matrix':
  34046. this.transforms.push( (new Transform()).parse(child) );
  34047. break;
  34048. default:
  34049. break;
  34050. }
  34051. }
  34052. return this;
  34053. };
  34054. function Attachment( ) {
  34055. this.joint = '';
  34056. this.transforms = [];
  34057. this.links = [];
  34058. }
  34059. Attachment.prototype.parse = function( element ) {
  34060. this.joint = element.getAttribute('joint').split('/').pop();
  34061. this.links = [];
  34062. for (var i = 0; i < element.childNodes.length; i ++ ) {
  34063. var child = element.childNodes[ i ];
  34064. if ( child.nodeType != 1 ) continue;
  34065. switch ( child.nodeName ) {
  34066. case 'link':
  34067. this.links.push( (new Link()).parse(child) );
  34068. break;
  34069. case 'rotate':
  34070. case 'translate':
  34071. case 'matrix':
  34072. this.transforms.push( (new Transform()).parse(child) );
  34073. break;
  34074. default:
  34075. break;
  34076. }
  34077. }
  34078. return this;
  34079. };
  34080. function _source( element ) {
  34081. var id = element.getAttribute( 'id' );
  34082. if ( sources[ id ] != undefined ) {
  34083. return sources[ id ];
  34084. }
  34085. sources[ id ] = ( new Source(id )).parse( element );
  34086. return sources[ id ];
  34087. }
  34088. function _nsResolver( nsPrefix ) {
  34089. if ( nsPrefix === "dae" ) {
  34090. return "http://www.collada.org/2005/11/COLLADASchema";
  34091. }
  34092. return null;
  34093. }
  34094. function _bools( str ) {
  34095. var raw = _strings( str );
  34096. var data = [];
  34097. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  34098. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  34099. }
  34100. return data;
  34101. }
  34102. function _floats( str ) {
  34103. var raw = _strings(str);
  34104. var data = [];
  34105. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  34106. data.push( parseFloat( raw[ i ] ) );
  34107. }
  34108. return data;
  34109. }
  34110. function _ints( str ) {
  34111. var raw = _strings( str );
  34112. var data = [];
  34113. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  34114. data.push( parseInt( raw[ i ], 10 ) );
  34115. }
  34116. return data;
  34117. }
  34118. function _strings( str ) {
  34119. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  34120. }
  34121. function _trimString( str ) {
  34122. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  34123. }
  34124. function _attr_as_float( element, name, defaultValue ) {
  34125. if ( element.hasAttribute( name ) ) {
  34126. return parseFloat( element.getAttribute( name ) );
  34127. } else {
  34128. return defaultValue;
  34129. }
  34130. }
  34131. function _attr_as_int( element, name, defaultValue ) {
  34132. if ( element.hasAttribute( name ) ) {
  34133. return parseInt( element.getAttribute( name ), 10) ;
  34134. } else {
  34135. return defaultValue;
  34136. }
  34137. }
  34138. function _attr_as_string( element, name, defaultValue ) {
  34139. if ( element.hasAttribute( name ) ) {
  34140. return element.getAttribute( name );
  34141. } else {
  34142. return defaultValue;
  34143. }
  34144. }
  34145. function _format_float( f, num ) {
  34146. if ( f === undefined ) {
  34147. var s = '0.';
  34148. while ( s.length < num + 2 ) {
  34149. s += '0';
  34150. }
  34151. return s;
  34152. }
  34153. num = num || 2;
  34154. var parts = f.toString().split( '.' );
  34155. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  34156. while ( parts[ 1 ].length < num ) {
  34157. parts[ 1 ] += '0';
  34158. }
  34159. return parts.join( '.' );
  34160. }
  34161. function loadTextureImage ( texture, url ) {
  34162. var loader = new THREE.ImageLoader();
  34163. loader.load( url, function ( image ) {
  34164. texture.image = image;
  34165. texture.needsUpdate = true;
  34166. } );
  34167. }
  34168. function extractDoubleSided( obj, element ) {
  34169. obj.doubleSided = false;
  34170. var node = element.querySelectorAll('extra double_sided')[0];
  34171. if ( node ) {
  34172. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  34173. obj.doubleSided = true;
  34174. }
  34175. }
  34176. }
  34177. // Up axis conversion
  34178. function setUpConversion() {
  34179. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  34180. upConversion = null;
  34181. } else {
  34182. switch ( colladaUp ) {
  34183. case 'X':
  34184. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  34185. break;
  34186. case 'Y':
  34187. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  34188. break;
  34189. case 'Z':
  34190. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  34191. break;
  34192. }
  34193. }
  34194. }
  34195. function fixCoords( data, sign ) {
  34196. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  34197. return;
  34198. }
  34199. switch ( upConversion ) {
  34200. case 'XtoY':
  34201. var tmp = data[ 0 ];
  34202. data[ 0 ] = sign * data[ 1 ];
  34203. data[ 1 ] = tmp;
  34204. break;
  34205. case 'XtoZ':
  34206. var tmp = data[ 2 ];
  34207. data[ 2 ] = data[ 1 ];
  34208. data[ 1 ] = data[ 0 ];
  34209. data[ 0 ] = tmp;
  34210. break;
  34211. case 'YtoX':
  34212. var tmp = data[ 0 ];
  34213. data[ 0 ] = data[ 1 ];
  34214. data[ 1 ] = sign * tmp;
  34215. break;
  34216. case 'YtoZ':
  34217. var tmp = data[ 1 ];
  34218. data[ 1 ] = sign * data[ 2 ];
  34219. data[ 2 ] = tmp;
  34220. break;
  34221. case 'ZtoX':
  34222. var tmp = data[ 0 ];
  34223. data[ 0 ] = data[ 1 ];
  34224. data[ 1 ] = data[ 2 ];
  34225. data[ 2 ] = tmp;
  34226. break;
  34227. case 'ZtoY':
  34228. var tmp = data[ 1 ];
  34229. data[ 1 ] = data[ 2 ];
  34230. data[ 2 ] = sign * tmp;
  34231. break;
  34232. }
  34233. }
  34234. function getConvertedTranslation( axis, data ) {
  34235. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  34236. return data;
  34237. }
  34238. switch ( axis ) {
  34239. case 'X':
  34240. data = upConversion === 'XtoY' ? data * -1 : data;
  34241. break;
  34242. case 'Y':
  34243. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  34244. break;
  34245. case 'Z':
  34246. data = upConversion === 'ZtoY' ? data * -1 : data ;
  34247. break;
  34248. default:
  34249. break;
  34250. }
  34251. return data;
  34252. }
  34253. function getConvertedVec3( data, offset ) {
  34254. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  34255. fixCoords( arr, -1 );
  34256. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  34257. }
  34258. function getConvertedMat4( data ) {
  34259. if ( options.convertUpAxis ) {
  34260. // First fix rotation and scale
  34261. // Columns first
  34262. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  34263. fixCoords( arr, -1 );
  34264. data[ 0 ] = arr[ 0 ];
  34265. data[ 4 ] = arr[ 1 ];
  34266. data[ 8 ] = arr[ 2 ];
  34267. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  34268. fixCoords( arr, -1 );
  34269. data[ 1 ] = arr[ 0 ];
  34270. data[ 5 ] = arr[ 1 ];
  34271. data[ 9 ] = arr[ 2 ];
  34272. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  34273. fixCoords( arr, -1 );
  34274. data[ 2 ] = arr[ 0 ];
  34275. data[ 6 ] = arr[ 1 ];
  34276. data[ 10 ] = arr[ 2 ];
  34277. // Rows second
  34278. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  34279. fixCoords( arr, -1 );
  34280. data[ 0 ] = arr[ 0 ];
  34281. data[ 1 ] = arr[ 1 ];
  34282. data[ 2 ] = arr[ 2 ];
  34283. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  34284. fixCoords( arr, -1 );
  34285. data[ 4 ] = arr[ 0 ];
  34286. data[ 5 ] = arr[ 1 ];
  34287. data[ 6 ] = arr[ 2 ];
  34288. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  34289. fixCoords( arr, -1 );
  34290. data[ 8 ] = arr[ 0 ];
  34291. data[ 9 ] = arr[ 1 ];
  34292. data[ 10 ] = arr[ 2 ];
  34293. // Now fix translation
  34294. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  34295. fixCoords( arr, -1 );
  34296. data[ 3 ] = arr[ 0 ];
  34297. data[ 7 ] = arr[ 1 ];
  34298. data[ 11 ] = arr[ 2 ];
  34299. }
  34300. return new THREE.Matrix4().set(
  34301. data[0], data[1], data[2], data[3],
  34302. data[4], data[5], data[6], data[7],
  34303. data[8], data[9], data[10], data[11],
  34304. data[12], data[13], data[14], data[15]
  34305. );
  34306. }
  34307. function getConvertedIndex( index ) {
  34308. if ( index > -1 && index < 3 ) {
  34309. var members = [ 'X', 'Y', 'Z' ],
  34310. indices = { X: 0, Y: 1, Z: 2 };
  34311. index = getConvertedMember( members[ index ] );
  34312. index = indices[ index ];
  34313. }
  34314. return index;
  34315. }
  34316. function getConvertedMember( member ) {
  34317. if ( options.convertUpAxis ) {
  34318. switch ( member ) {
  34319. case 'X':
  34320. switch ( upConversion ) {
  34321. case 'XtoY':
  34322. case 'XtoZ':
  34323. case 'YtoX':
  34324. member = 'Y';
  34325. break;
  34326. case 'ZtoX':
  34327. member = 'Z';
  34328. break;
  34329. }
  34330. break;
  34331. case 'Y':
  34332. switch ( upConversion ) {
  34333. case 'XtoY':
  34334. case 'YtoX':
  34335. case 'ZtoX':
  34336. member = 'X';
  34337. break;
  34338. case 'XtoZ':
  34339. case 'YtoZ':
  34340. case 'ZtoY':
  34341. member = 'Z';
  34342. break;
  34343. }
  34344. break;
  34345. case 'Z':
  34346. switch ( upConversion ) {
  34347. case 'XtoZ':
  34348. member = 'X';
  34349. break;
  34350. case 'YtoZ':
  34351. case 'ZtoX':
  34352. case 'ZtoY':
  34353. member = 'Y';
  34354. break;
  34355. }
  34356. break;
  34357. }
  34358. }
  34359. return member;
  34360. }
  34361. return {
  34362. load: load,
  34363. parse: parse,
  34364. applySkin: applySkin,
  34365. geometries : geometries,
  34366. options: options
  34367. };
  34368. };
  34369. },{}],43:[function(_dereq_,module,exports){
  34370. /**
  34371. * @author Rich Tibbett / https://github.com/richtr
  34372. * @author mrdoob / http://mrdoob.com/
  34373. * @author Tony Parisi / http://www.tonyparisi.com/
  34374. * @author Takahiro / https://github.com/takahirox
  34375. * @author Don McCurdy / https://www.donmccurdy.com
  34376. */
  34377. THREE.GLTFLoader = ( function () {
  34378. function GLTFLoader( manager ) {
  34379. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34380. }
  34381. GLTFLoader.prototype = {
  34382. constructor: GLTFLoader,
  34383. crossOrigin: 'Anonymous',
  34384. load: function ( url, onLoad, onProgress, onError ) {
  34385. var scope = this;
  34386. var path = this.path && ( typeof this.path === 'string' ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  34387. var loader = new THREE.FileLoader( scope.manager );
  34388. loader.setResponseType( 'arraybuffer' );
  34389. loader.load( url, function ( data ) {
  34390. try {
  34391. scope.parse( data, path, onLoad, onError );
  34392. } catch ( e ) {
  34393. // For SyntaxError or TypeError, return a generic failure message.
  34394. onError( e.constructor === Error ? e : new Error( 'THREE.GLTFLoader: Unable to parse model.' ) );
  34395. }
  34396. }, onProgress, onError );
  34397. },
  34398. setCrossOrigin: function ( value ) {
  34399. this.crossOrigin = value;
  34400. },
  34401. setPath: function ( value ) {
  34402. this.path = value;
  34403. },
  34404. parse: function ( data, path, onLoad, onError ) {
  34405. var content;
  34406. var extensions = {};
  34407. var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
  34408. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34409. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34410. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34411. } else {
  34412. content = convertUint8ArrayToString( new Uint8Array( data ) );
  34413. }
  34414. var json = JSON.parse( content );
  34415. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  34416. onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  34417. return;
  34418. }
  34419. if ( json.extensionsUsed ) {
  34420. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  34421. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  34422. }
  34423. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  34424. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  34425. }
  34426. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  34427. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  34428. }
  34429. }
  34430. console.time( 'GLTFLoader' );
  34431. var parser = new GLTFParser( json, extensions, {
  34432. path: path || this.path,
  34433. crossOrigin: this.crossOrigin
  34434. } );
  34435. parser.parse( function ( scene, scenes, cameras, animations ) {
  34436. console.timeEnd( 'GLTFLoader' );
  34437. var glTF = {
  34438. scene: scene,
  34439. scenes: scenes,
  34440. cameras: cameras,
  34441. animations: animations
  34442. };
  34443. onLoad( glTF );
  34444. }, onError );
  34445. }
  34446. };
  34447. /* GLTFREGISTRY */
  34448. function GLTFRegistry() {
  34449. var objects = {};
  34450. return {
  34451. get: function ( key ) {
  34452. return objects[ key ];
  34453. },
  34454. add: function ( key, object ) {
  34455. objects[ key ] = object;
  34456. },
  34457. remove: function ( key ) {
  34458. delete objects[ key ];
  34459. },
  34460. removeAll: function () {
  34461. objects = {};
  34462. },
  34463. update: function ( scene, camera ) {
  34464. for ( var name in objects ) {
  34465. var object = objects[ name ];
  34466. if ( object.update ) {
  34467. object.update( scene, camera );
  34468. }
  34469. }
  34470. }
  34471. };
  34472. }
  34473. /*********************************/
  34474. /********** EXTENSIONS ***********/
  34475. /*********************************/
  34476. var EXTENSIONS = {
  34477. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34478. KHR_LIGHTS: 'KHR_lights',
  34479. KHR_MATERIALS_COMMON: 'KHR_materials_common',
  34480. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness'
  34481. };
  34482. /**
  34483. * Lights Extension
  34484. *
  34485. * Specification: PENDING
  34486. */
  34487. function GLTFLightsExtension( json ) {
  34488. this.name = EXTENSIONS.KHR_LIGHTS;
  34489. this.lights = {};
  34490. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  34491. var lights = extension.lights || {};
  34492. for ( var lightId in lights ) {
  34493. var light = lights[ lightId ];
  34494. var lightNode;
  34495. var color = new THREE.Color().fromArray( light.color );
  34496. switch ( light.type ) {
  34497. case 'directional':
  34498. lightNode = new THREE.DirectionalLight( color );
  34499. lightNode.position.set( 0, 0, 1 );
  34500. break;
  34501. case 'point':
  34502. lightNode = new THREE.PointLight( color );
  34503. break;
  34504. case 'spot':
  34505. lightNode = new THREE.SpotLight( color );
  34506. lightNode.position.set( 0, 0, 1 );
  34507. break;
  34508. case 'ambient':
  34509. lightNode = new THREE.AmbientLight( color );
  34510. break;
  34511. }
  34512. if ( lightNode ) {
  34513. if ( light.constantAttenuation !== undefined ) {
  34514. lightNode.intensity = light.constantAttenuation;
  34515. }
  34516. if ( light.linearAttenuation !== undefined ) {
  34517. lightNode.distance = 1 / light.linearAttenuation;
  34518. }
  34519. if ( light.quadraticAttenuation !== undefined ) {
  34520. lightNode.decay = light.quadraticAttenuation;
  34521. }
  34522. if ( light.fallOffAngle !== undefined ) {
  34523. lightNode.angle = light.fallOffAngle;
  34524. }
  34525. if ( light.fallOffExponent !== undefined ) {
  34526. console.warn( 'THREE.GLTFLoader:: light.fallOffExponent not currently supported.' );
  34527. }
  34528. lightNode.name = light.name || ( 'light_' + lightId );
  34529. this.lights[ lightId ] = lightNode;
  34530. }
  34531. }
  34532. }
  34533. /**
  34534. * Common Materials Extension
  34535. *
  34536. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
  34537. */
  34538. function GLTFMaterialsCommonExtension( json ) {
  34539. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  34540. }
  34541. GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {
  34542. var khrMaterial = material.extensions[ this.name ];
  34543. switch ( khrMaterial.type ) {
  34544. case 'commonBlinn' :
  34545. case 'commonPhong' :
  34546. return THREE.MeshPhongMaterial;
  34547. case 'commonLambert' :
  34548. return THREE.MeshLambertMaterial;
  34549. case 'commonConstant' :
  34550. default :
  34551. return THREE.MeshBasicMaterial;
  34552. }
  34553. };
  34554. GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  34555. var khrMaterial = material.extensions[ this.name ];
  34556. var pending = [];
  34557. var keys = [];
  34558. // TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
  34559. switch ( khrMaterial.type ) {
  34560. case 'commonBlinn' :
  34561. case 'commonPhong' :
  34562. keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
  34563. break;
  34564. case 'commonLambert' :
  34565. keys.push( 'diffuseFactor', 'diffuseTexture' );
  34566. break;
  34567. case 'commonConstant' :
  34568. default :
  34569. break;
  34570. }
  34571. var materialValues = {};
  34572. keys.forEach( function( v ) {
  34573. if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];
  34574. } );
  34575. if ( materialValues.diffuseFactor !== undefined ) {
  34576. materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
  34577. materialParams.opacity = materialValues.diffuseFactor[ 3 ];
  34578. }
  34579. if ( materialValues.diffuseTexture !== undefined ) {
  34580. pending.push( parser.assignTexture( materialParams, 'map', materialValues.diffuseTexture.index ) );
  34581. }
  34582. if ( materialValues.specularFactor !== undefined ) {
  34583. materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );
  34584. }
  34585. if ( materialValues.specularTexture !== undefined ) {
  34586. pending.push( parser.assignTexture( materialParams, 'specularMap', materialValues.specularTexture.index ) );
  34587. }
  34588. if ( materialValues.shininessFactor !== undefined ) {
  34589. materialParams.shininess = materialValues.shininessFactor;
  34590. }
  34591. return Promise.all( pending );
  34592. };
  34593. /* BINARY EXTENSION */
  34594. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34595. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  34596. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  34597. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  34598. function GLTFBinaryExtension( data ) {
  34599. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34600. this.content = null;
  34601. this.body = null;
  34602. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34603. this.header = {
  34604. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  34605. version: headerView.getUint32( 4, true ),
  34606. length: headerView.getUint32( 8, true )
  34607. };
  34608. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  34609. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  34610. } else if ( this.header.version < 2.0 ) {
  34611. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use GLTFLoader instead.' );
  34612. }
  34613. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  34614. var chunkIndex = 0;
  34615. while ( chunkIndex < chunkView.byteLength ) {
  34616. var chunkLength = chunkView.getUint32( chunkIndex, true );
  34617. chunkIndex += 4;
  34618. var chunkType = chunkView.getUint32( chunkIndex, true );
  34619. chunkIndex += 4;
  34620. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  34621. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  34622. this.content = convertUint8ArrayToString( contentArray );
  34623. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  34624. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  34625. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  34626. }
  34627. // Clients must ignore chunks with unknown types.
  34628. chunkIndex += chunkLength;
  34629. }
  34630. if ( this.content === null ) {
  34631. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  34632. }
  34633. }
  34634. /**
  34635. * Specular-Glossiness Extension
  34636. *
  34637. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34638. */
  34639. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  34640. return {
  34641. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  34642. getMaterialType: function () {
  34643. return THREE.ShaderMaterial;
  34644. },
  34645. extendParams: function ( params, material, parser ) {
  34646. var pbrSpecularGlossiness = material.extensions[ this.name ];
  34647. var shader = THREE.ShaderLib[ 'standard' ];
  34648. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  34649. var specularMapParsFragmentChunk = [
  34650. '#ifdef USE_SPECULARMAP',
  34651. ' uniform sampler2D specularMap;',
  34652. '#endif'
  34653. ].join( '\n' );
  34654. var glossinessMapParsFragmentChunk = [
  34655. '#ifdef USE_GLOSSINESSMAP',
  34656. ' uniform sampler2D glossinessMap;',
  34657. '#endif'
  34658. ].join( '\n' );
  34659. var specularMapFragmentChunk = [
  34660. 'vec3 specularFactor = specular;',
  34661. '#ifdef USE_SPECULARMAP',
  34662. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  34663. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34664. ' specularFactor *= texelSpecular.rgb;',
  34665. '#endif'
  34666. ].join( '\n' );
  34667. var glossinessMapFragmentChunk = [
  34668. 'float glossinessFactor = glossiness;',
  34669. '#ifdef USE_GLOSSINESSMAP',
  34670. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  34671. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34672. ' glossinessFactor *= texelGlossiness.a;',
  34673. '#endif'
  34674. ].join( '\n' );
  34675. var lightPhysicalFragmentChunk = [
  34676. 'PhysicalMaterial material;',
  34677. 'material.diffuseColor = diffuseColor.rgb;',
  34678. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  34679. 'material.specularColor = specularFactor.rgb;',
  34680. ].join( '\n' );
  34681. var fragmentShader = shader.fragmentShader
  34682. .replace( '#include <specularmap_fragment>', '' )
  34683. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  34684. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  34685. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  34686. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  34687. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  34688. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  34689. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  34690. delete uniforms.roughness;
  34691. delete uniforms.metalness;
  34692. delete uniforms.roughnessMap;
  34693. delete uniforms.metalnessMap;
  34694. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  34695. uniforms.glossiness = { value: 0.5 };
  34696. uniforms.specularMap = { value: null };
  34697. uniforms.glossinessMap = { value: null };
  34698. params.vertexShader = shader.vertexShader;
  34699. params.fragmentShader = fragmentShader;
  34700. params.uniforms = uniforms;
  34701. params.defines = { 'STANDARD': '' };
  34702. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34703. params.opacity = 1.0;
  34704. var pending = [];
  34705. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  34706. var array = pbrSpecularGlossiness.diffuseFactor;
  34707. params.color.fromArray( array );
  34708. params.opacity = array[ 3 ];
  34709. }
  34710. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  34711. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  34712. }
  34713. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  34714. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  34715. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  34716. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  34717. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  34718. }
  34719. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  34720. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  34721. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  34722. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  34723. }
  34724. return Promise.all( pending );
  34725. },
  34726. createMaterial: function ( params ) {
  34727. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  34728. var material = new THREE.ShaderMaterial( {
  34729. defines: params.defines,
  34730. vertexShader: params.vertexShader,
  34731. fragmentShader: params.fragmentShader,
  34732. uniforms: params.uniforms,
  34733. fog: true,
  34734. lights: true,
  34735. opacity: params.opacity,
  34736. transparent: params.transparent
  34737. } );
  34738. material.isGLTFSpecularGlossinessMaterial = true;
  34739. material.color = params.color;
  34740. material.map = params.map === undefined ? null : params.map;
  34741. material.lightMap = null;
  34742. material.lightMapIntensity = 1.0;
  34743. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  34744. material.aoMapIntensity = 1.0;
  34745. material.emissive = params.emissive;
  34746. material.emissiveIntensity = 1.0;
  34747. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  34748. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  34749. material.bumpScale = 1;
  34750. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  34751. material.normalScale = new THREE.Vector2( 1, 1 );
  34752. material.displacementMap = null;
  34753. material.displacementScale = 1;
  34754. material.displacementBias = 0;
  34755. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  34756. material.specular = params.specular;
  34757. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  34758. material.glossiness = params.glossiness;
  34759. material.alphaMap = null;
  34760. material.envMap = params.envMap === undefined ? null : params.envMap;
  34761. material.envMapIntensity = 1.0;
  34762. material.refractionRatio = 0.98;
  34763. material.extensions.derivatives = true;
  34764. return material;
  34765. },
  34766. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  34767. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  34768. var uniforms = material.uniforms;
  34769. var defines = material.defines;
  34770. uniforms.opacity.value = material.opacity;
  34771. uniforms.diffuse.value.copy( material.color );
  34772. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  34773. uniforms.map.value = material.map;
  34774. uniforms.specularMap.value = material.specularMap;
  34775. uniforms.alphaMap.value = material.alphaMap;
  34776. uniforms.lightMap.value = material.lightMap;
  34777. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  34778. uniforms.aoMap.value = material.aoMap;
  34779. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  34780. // uv repeat and offset setting priorities
  34781. // 1. color map
  34782. // 2. specular map
  34783. // 3. normal map
  34784. // 4. bump map
  34785. // 5. alpha map
  34786. // 6. emissive map
  34787. var uvScaleMap;
  34788. if ( material.map ) {
  34789. uvScaleMap = material.map;
  34790. } else if ( material.specularMap ) {
  34791. uvScaleMap = material.specularMap;
  34792. } else if ( material.displacementMap ) {
  34793. uvScaleMap = material.displacementMap;
  34794. } else if ( material.normalMap ) {
  34795. uvScaleMap = material.normalMap;
  34796. } else if ( material.bumpMap ) {
  34797. uvScaleMap = material.bumpMap;
  34798. } else if ( material.glossinessMap ) {
  34799. uvScaleMap = material.glossinessMap;
  34800. } else if ( material.alphaMap ) {
  34801. uvScaleMap = material.alphaMap;
  34802. } else if ( material.emissiveMap ) {
  34803. uvScaleMap = material.emissiveMap;
  34804. }
  34805. if ( uvScaleMap !== undefined ) {
  34806. // backwards compatibility
  34807. if ( uvScaleMap.isWebGLRenderTarget ) {
  34808. uvScaleMap = uvScaleMap.texture;
  34809. }
  34810. var offset = uvScaleMap.offset;
  34811. var repeat = uvScaleMap.repeat;
  34812. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  34813. }
  34814. uniforms.envMap.value = material.envMap;
  34815. uniforms.envMapIntensity.value = material.envMapIntensity;
  34816. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? -1 : 1;
  34817. uniforms.refractionRatio.value = material.refractionRatio;
  34818. uniforms.specular.value.copy( material.specular );
  34819. uniforms.glossiness.value = material.glossiness;
  34820. uniforms.glossinessMap.value = material.glossinessMap;
  34821. uniforms.emissiveMap.value = material.emissiveMap;
  34822. uniforms.bumpMap.value = material.bumpMap;
  34823. uniforms.normalMap.value = material.normalMap;
  34824. uniforms.displacementMap.value = material.displacementMap;
  34825. uniforms.displacementScale.value = material.displacementScale;
  34826. uniforms.displacementBias.value = material.displacementBias;
  34827. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  34828. defines.USE_GLOSSINESSMAP = '';
  34829. // set USE_ROUGHNESSMAP to enable vUv
  34830. defines.USE_ROUGHNESSMAP = '';
  34831. }
  34832. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  34833. delete defines.USE_GLOSSINESSMAP;
  34834. delete defines.USE_ROUGHNESSMAP;
  34835. }
  34836. }
  34837. };
  34838. }
  34839. /*********************************/
  34840. /********** INTERNALS ************/
  34841. /*********************************/
  34842. /* CONSTANTS */
  34843. var WEBGL_CONSTANTS = {
  34844. FLOAT: 5126,
  34845. //FLOAT_MAT2: 35674,
  34846. FLOAT_MAT3: 35675,
  34847. FLOAT_MAT4: 35676,
  34848. FLOAT_VEC2: 35664,
  34849. FLOAT_VEC3: 35665,
  34850. FLOAT_VEC4: 35666,
  34851. LINEAR: 9729,
  34852. REPEAT: 10497,
  34853. SAMPLER_2D: 35678,
  34854. POINTS: 0,
  34855. LINES: 1,
  34856. LINE_LOOP: 2,
  34857. LINE_STRIP: 3,
  34858. TRIANGLES: 4,
  34859. TRIANGLE_STRIP: 5,
  34860. TRIANGLE_FAN: 6,
  34861. UNSIGNED_BYTE: 5121,
  34862. UNSIGNED_SHORT: 5123
  34863. };
  34864. var WEBGL_TYPE = {
  34865. 5126: Number,
  34866. //35674: THREE.Matrix2,
  34867. 35675: THREE.Matrix3,
  34868. 35676: THREE.Matrix4,
  34869. 35664: THREE.Vector2,
  34870. 35665: THREE.Vector3,
  34871. 35666: THREE.Vector4,
  34872. 35678: THREE.Texture
  34873. };
  34874. var WEBGL_COMPONENT_TYPES = {
  34875. 5120: Int8Array,
  34876. 5121: Uint8Array,
  34877. 5122: Int16Array,
  34878. 5123: Uint16Array,
  34879. 5125: Uint32Array,
  34880. 5126: Float32Array
  34881. };
  34882. var WEBGL_FILTERS = {
  34883. 9728: THREE.NearestFilter,
  34884. 9729: THREE.LinearFilter,
  34885. 9984: THREE.NearestMipMapNearestFilter,
  34886. 9985: THREE.LinearMipMapNearestFilter,
  34887. 9986: THREE.NearestMipMapLinearFilter,
  34888. 9987: THREE.LinearMipMapLinearFilter
  34889. };
  34890. var WEBGL_WRAPPINGS = {
  34891. 33071: THREE.ClampToEdgeWrapping,
  34892. 33648: THREE.MirroredRepeatWrapping,
  34893. 10497: THREE.RepeatWrapping
  34894. };
  34895. var WEBGL_TEXTURE_FORMATS = {
  34896. 6406: THREE.AlphaFormat,
  34897. 6407: THREE.RGBFormat,
  34898. 6408: THREE.RGBAFormat,
  34899. 6409: THREE.LuminanceFormat,
  34900. 6410: THREE.LuminanceAlphaFormat
  34901. };
  34902. var WEBGL_TEXTURE_DATATYPES = {
  34903. 5121: THREE.UnsignedByteType,
  34904. 32819: THREE.UnsignedShort4444Type,
  34905. 32820: THREE.UnsignedShort5551Type,
  34906. 33635: THREE.UnsignedShort565Type
  34907. };
  34908. var WEBGL_SIDES = {
  34909. 1028: THREE.BackSide, // Culling front
  34910. 1029: THREE.FrontSide // Culling back
  34911. //1032: THREE.NoSide // Culling front and back, what to do?
  34912. };
  34913. var WEBGL_DEPTH_FUNCS = {
  34914. 512: THREE.NeverDepth,
  34915. 513: THREE.LessDepth,
  34916. 514: THREE.EqualDepth,
  34917. 515: THREE.LessEqualDepth,
  34918. 516: THREE.GreaterEqualDepth,
  34919. 517: THREE.NotEqualDepth,
  34920. 518: THREE.GreaterEqualDepth,
  34921. 519: THREE.AlwaysDepth
  34922. };
  34923. var WEBGL_BLEND_EQUATIONS = {
  34924. 32774: THREE.AddEquation,
  34925. 32778: THREE.SubtractEquation,
  34926. 32779: THREE.ReverseSubtractEquation
  34927. };
  34928. var WEBGL_BLEND_FUNCS = {
  34929. 0: THREE.ZeroFactor,
  34930. 1: THREE.OneFactor,
  34931. 768: THREE.SrcColorFactor,
  34932. 769: THREE.OneMinusSrcColorFactor,
  34933. 770: THREE.SrcAlphaFactor,
  34934. 771: THREE.OneMinusSrcAlphaFactor,
  34935. 772: THREE.DstAlphaFactor,
  34936. 773: THREE.OneMinusDstAlphaFactor,
  34937. 774: THREE.DstColorFactor,
  34938. 775: THREE.OneMinusDstColorFactor,
  34939. 776: THREE.SrcAlphaSaturateFactor
  34940. // The followings are not supported by Three.js yet
  34941. //32769: CONSTANT_COLOR,
  34942. //32770: ONE_MINUS_CONSTANT_COLOR,
  34943. //32771: CONSTANT_ALPHA,
  34944. //32772: ONE_MINUS_CONSTANT_COLOR
  34945. };
  34946. var WEBGL_TYPE_SIZES = {
  34947. 'SCALAR': 1,
  34948. 'VEC2': 2,
  34949. 'VEC3': 3,
  34950. 'VEC4': 4,
  34951. 'MAT2': 4,
  34952. 'MAT3': 9,
  34953. 'MAT4': 16
  34954. };
  34955. var PATH_PROPERTIES = {
  34956. scale: 'scale',
  34957. translation: 'position',
  34958. rotation: 'quaternion',
  34959. weights: 'morphTargetInfluences'
  34960. };
  34961. var INTERPOLATION = {
  34962. CATMULLROMSPLINE: THREE.InterpolateSmooth,
  34963. CUBICSPLINE: THREE.InterpolateSmooth,
  34964. LINEAR: THREE.InterpolateLinear,
  34965. STEP: THREE.InterpolateDiscrete
  34966. };
  34967. var STATES_ENABLES = {
  34968. 2884: 'CULL_FACE',
  34969. 2929: 'DEPTH_TEST',
  34970. 3042: 'BLEND',
  34971. 3089: 'SCISSOR_TEST',
  34972. 32823: 'POLYGON_OFFSET_FILL',
  34973. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  34974. };
  34975. var ALPHA_MODES = {
  34976. OPAQUE: 'OPAQUE',
  34977. MASK: 'MASK',
  34978. BLEND: 'BLEND'
  34979. };
  34980. /* UTILITY FUNCTIONS */
  34981. function _each( object, callback, thisObj ) {
  34982. if ( !object ) {
  34983. return Promise.resolve();
  34984. }
  34985. var results;
  34986. var fns = [];
  34987. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  34988. results = [];
  34989. var length = object.length;
  34990. for ( var idx = 0; idx < length; idx ++ ) {
  34991. var value = callback.call( thisObj || this, object[ idx ], idx );
  34992. if ( value ) {
  34993. fns.push( value );
  34994. if ( value instanceof Promise ) {
  34995. value.then( function( key, value ) {
  34996. results[ key ] = value;
  34997. }.bind( this, idx ));
  34998. } else {
  34999. results[ idx ] = value;
  35000. }
  35001. }
  35002. }
  35003. } else {
  35004. results = {};
  35005. for ( var key in object ) {
  35006. if ( object.hasOwnProperty( key ) ) {
  35007. var value = callback.call( thisObj || this, object[ key ], key );
  35008. if ( value ) {
  35009. fns.push( value );
  35010. if ( value instanceof Promise ) {
  35011. value.then( function( key, value ) {
  35012. results[ key ] = value;
  35013. }.bind( this, key ));
  35014. } else {
  35015. results[ key ] = value;
  35016. }
  35017. }
  35018. }
  35019. }
  35020. }
  35021. return Promise.all( fns ).then( function() {
  35022. return results;
  35023. });
  35024. }
  35025. function resolveURL( url, path ) {
  35026. // Invalid URL
  35027. if ( typeof url !== 'string' || url === '' )
  35028. return '';
  35029. // Absolute URL http://,https://,//
  35030. if ( /^(https?:)?\/\//i.test( url ) ) {
  35031. return url;
  35032. }
  35033. // Data URI
  35034. if ( /^data:.*,.*$/i.test( url ) ) {
  35035. return url;
  35036. }
  35037. // Blob URL
  35038. if ( /^blob:.*$/i.test( url ) ) {
  35039. return url;
  35040. }
  35041. // Relative URL
  35042. return ( path || '' ) + url;
  35043. }
  35044. function convertUint8ArrayToString( array ) {
  35045. if ( window.TextDecoder !== undefined ) {
  35046. return new TextDecoder().decode( array );
  35047. }
  35048. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  35049. // throws a "maximum call stack size exceeded" error for large arrays.
  35050. var s = '';
  35051. for ( var i = 0, il = array.length; i < il; i ++ ) {
  35052. s += String.fromCharCode( array[ i ] );
  35053. }
  35054. return s;
  35055. }
  35056. /**
  35057. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  35058. */
  35059. function createDefaultMaterial() {
  35060. return new THREE.MeshStandardMaterial( {
  35061. color: 0xFFFFFF,
  35062. emissive: 0x000000,
  35063. metalness: 1,
  35064. roughness: 1,
  35065. transparent: false,
  35066. depthTest: true,
  35067. side: THREE.FrontSide
  35068. } );
  35069. }
  35070. /**
  35071. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  35072. * @param {THREE.Mesh} mesh
  35073. * @param {GLTF.Mesh} meshDef
  35074. * @param {GLTF.Primitive} primitiveDef
  35075. * @param {Object} dependencies
  35076. */
  35077. function addMorphTargets ( mesh, meshDef, primitiveDef, dependencies ) {
  35078. var geometry = mesh.geometry;
  35079. var material = mesh.material;
  35080. var targets = primitiveDef.targets;
  35081. var morphAttributes = geometry.morphAttributes;
  35082. morphAttributes.position = [];
  35083. morphAttributes.normal = [];
  35084. material.morphTargets = true;
  35085. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  35086. var target = targets[ i ];
  35087. var attributeName = 'morphTarget' + i;
  35088. var positionAttribute, normalAttribute;
  35089. if ( target.POSITION !== undefined ) {
  35090. // Three.js morph formula is
  35091. // position
  35092. // + weight0 * ( morphTarget0 - position )
  35093. // + weight1 * ( morphTarget1 - position )
  35094. // ...
  35095. // while the glTF one is
  35096. // position
  35097. // + weight0 * morphTarget0
  35098. // + weight1 * morphTarget1
  35099. // ...
  35100. // then adding position to morphTarget.
  35101. // So morphTarget value will depend on mesh's position, then cloning attribute
  35102. // for the case if attribute is shared among two or more meshes.
  35103. positionAttribute = dependencies.accessors[ target.POSITION ].clone();
  35104. var position = geometry.attributes.position;
  35105. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  35106. positionAttribute.setXYZ(
  35107. j,
  35108. positionAttribute.getX( j ) + position.getX( j ),
  35109. positionAttribute.getY( j ) + position.getY( j ),
  35110. positionAttribute.getZ( j ) + position.getZ( j )
  35111. );
  35112. }
  35113. } else {
  35114. // Copying the original position not to affect the final position.
  35115. // See the formula above.
  35116. positionAttribute = geometry.attributes.position.clone();
  35117. }
  35118. if ( target.NORMAL !== undefined ) {
  35119. material.morphNormals = true;
  35120. // see target.POSITION's comment
  35121. normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
  35122. var normal = geometry.attributes.normal;
  35123. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  35124. normalAttribute.setXYZ(
  35125. j,
  35126. normalAttribute.getX( j ) + normal.getX( j ),
  35127. normalAttribute.getY( j ) + normal.getY( j ),
  35128. normalAttribute.getZ( j ) + normal.getZ( j )
  35129. );
  35130. }
  35131. } else {
  35132. normalAttribute = geometry.attributes.normal.clone();
  35133. }
  35134. if ( target.TANGENT !== undefined ) {
  35135. // TODO: implement
  35136. }
  35137. positionAttribute.name = attributeName;
  35138. normalAttribute.name = attributeName;
  35139. morphAttributes.position.push( positionAttribute );
  35140. morphAttributes.normal.push( normalAttribute );
  35141. }
  35142. mesh.updateMorphTargets();
  35143. if ( meshDef.weights !== undefined ) {
  35144. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  35145. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  35146. }
  35147. }
  35148. }
  35149. /* GLTF PARSER */
  35150. function GLTFParser( json, extensions, options ) {
  35151. this.json = json || {};
  35152. this.extensions = extensions || {};
  35153. this.options = options || {};
  35154. // loader object cache
  35155. this.cache = new GLTFRegistry();
  35156. }
  35157. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  35158. var _dependencies = {};
  35159. for ( var i = 0; i < dependencies.length; i ++ ) {
  35160. var dependency = dependencies[ i ];
  35161. var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  35162. var cached = this.cache.get( dependency );
  35163. if ( cached !== undefined ) {
  35164. _dependencies[ dependency ] = cached;
  35165. } else if ( this[ fnName ] ) {
  35166. var fn = this[ fnName ]();
  35167. this.cache.add( dependency, fn );
  35168. _dependencies[ dependency ] = fn;
  35169. }
  35170. }
  35171. return _each( _dependencies, function ( dependency ) {
  35172. return dependency;
  35173. } );
  35174. };
  35175. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  35176. var json = this.json;
  35177. // Clear the loader cache
  35178. this.cache.removeAll();
  35179. // Fire the callback on complete
  35180. this._withDependencies( [
  35181. 'scenes',
  35182. 'cameras',
  35183. 'animations'
  35184. ] ).then( function ( dependencies ) {
  35185. var scenes = [];
  35186. for ( var name in dependencies.scenes ) {
  35187. scenes.push( dependencies.scenes[ name ] );
  35188. }
  35189. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  35190. var cameras = [];
  35191. for ( var name in dependencies.cameras ) {
  35192. var camera = dependencies.cameras[ name ];
  35193. cameras.push( camera );
  35194. }
  35195. var animations = [];
  35196. for ( var name in dependencies.animations ) {
  35197. animations.push( dependencies.animations[ name ] );
  35198. }
  35199. onLoad( scene, scenes, cameras, animations );
  35200. } ).catch( onError );
  35201. };
  35202. /**
  35203. * Requests the specified dependency asynchronously, with caching.
  35204. * @param {string} type
  35205. * @param {number} index
  35206. * @return {Promise<Object>}
  35207. */
  35208. GLTFParser.prototype.getDependency = function ( type, index ) {
  35209. var cacheKey = type + ':' + index;
  35210. var dependency = this.cache.get( cacheKey );
  35211. if ( !dependency ) {
  35212. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  35213. dependency = this[ fnName ]( index );
  35214. this.cache.add( cacheKey, dependency );
  35215. }
  35216. return dependency;
  35217. };
  35218. /**
  35219. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35220. * @param {number} bufferIndex
  35221. * @return {Promise<ArrayBuffer>}
  35222. */
  35223. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  35224. var bufferDef = this.json.buffers[ bufferIndex ];
  35225. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  35226. throw new Error( 'THREE.GLTFLoader: %s buffer type is not supported.', bufferDef.type );
  35227. }
  35228. // If present, GLB container is required to be the first buffer.
  35229. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  35230. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  35231. }
  35232. var options = this.options;
  35233. return new Promise( function ( resolve ) {
  35234. var loader = new THREE.FileLoader();
  35235. loader.setResponseType( 'arraybuffer' );
  35236. loader.load( resolveURL( bufferDef.uri, options.path ), resolve);
  35237. } );
  35238. };
  35239. /**
  35240. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35241. * @param {number} bufferViewIndex
  35242. * @return {Promise<ArrayBuffer>}
  35243. */
  35244. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  35245. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  35246. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  35247. var byteLength = bufferViewDef.byteLength || 0;
  35248. var byteOffset = bufferViewDef.byteOffset || 0;
  35249. return buffer.slice( byteOffset, byteOffset + byteLength );
  35250. } );
  35251. };
  35252. GLTFParser.prototype.loadAccessors = function () {
  35253. var parser = this;
  35254. var json = this.json;
  35255. return _each( json.accessors, function ( accessor ) {
  35256. return parser.getDependency( 'bufferView', accessor.bufferView ).then( function ( bufferView ) {
  35257. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  35258. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  35259. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  35260. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  35261. var itemBytes = elementBytes * itemSize;
  35262. var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
  35263. var array;
  35264. // The buffer is not interleaved if the stride is the item size in bytes.
  35265. if ( byteStride && byteStride !== itemBytes ) {
  35266. // Use the full buffer if it's interleaved.
  35267. array = new TypedArray( bufferView );
  35268. // Integer parameters to IB/IBA are in array elements, not bytes.
  35269. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  35270. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  35271. } else {
  35272. array = new TypedArray( bufferView, accessor.byteOffset, accessor.count * itemSize );
  35273. return new THREE.BufferAttribute( array, itemSize );
  35274. }
  35275. } );
  35276. } );
  35277. };
  35278. /**
  35279. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  35280. * @param {number} textureIndex
  35281. * @return {Promise<THREE.Texture>}
  35282. */
  35283. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  35284. var parser = this;
  35285. var json = this.json;
  35286. var options = this.options;
  35287. var URL = window.URL || window.webkitURL;
  35288. var textureDef = json.textures[ textureIndex ];
  35289. var source = json.images[ textureDef.source ];
  35290. var sourceURI = source.uri;
  35291. var isObjectURL = false;
  35292. if ( source.bufferView !== undefined ) {
  35293. // Load binary image data from bufferView, if provided.
  35294. sourceURI = parser.getDependency( 'bufferView', source.bufferView )
  35295. .then( function ( bufferView ) {
  35296. isObjectURL = true;
  35297. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  35298. sourceURI = URL.createObjectURL( blob );
  35299. return sourceURI;
  35300. } );
  35301. }
  35302. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  35303. // Load Texture resource.
  35304. var textureLoader = THREE.Loader.Handlers.get( sourceURI ) || new THREE.TextureLoader();
  35305. textureLoader.setCrossOrigin( options.crossOrigin );
  35306. return new Promise( function ( resolve, reject ) {
  35307. textureLoader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  35308. } );
  35309. } ).then( function ( texture ) {
  35310. // Clean up resources and configure Texture.
  35311. if ( isObjectURL !== undefined ) {
  35312. URL.revokeObjectURL( sourceURI );
  35313. }
  35314. texture.flipY = false;
  35315. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  35316. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  35317. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  35318. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  35319. 'internalFormat will be forced to be the same value as format.' );
  35320. }
  35321. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  35322. var samplers = json.samplers || {};
  35323. var sampler = samplers[ textureDef.sampler ] || {};
  35324. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  35325. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  35326. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  35327. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  35328. return texture;
  35329. } );
  35330. };
  35331. /**
  35332. * Asynchronously assigns a texture to the given material parameters.
  35333. * @param {Object} materialParams
  35334. * @param {string} textureName
  35335. * @param {number} textureIndex
  35336. * @return {Promise}
  35337. */
  35338. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  35339. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  35340. materialParams[ textureName ] = texture;
  35341. } );
  35342. };
  35343. /**
  35344. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  35345. * @return {Promise<Array<THREE.Material>>}
  35346. */
  35347. GLTFParser.prototype.loadMaterials = function () {
  35348. var parser = this;
  35349. var json = this.json;
  35350. var extensions = this.extensions;
  35351. return _each( json.materials, function ( material ) {
  35352. var materialType;
  35353. var materialParams = {};
  35354. var materialExtensions = material.extensions || {};
  35355. var pending = [];
  35356. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  35357. var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  35358. materialType = khcExtension.getMaterialType( material );
  35359. pending.push( khcExtension.extendParams( materialParams, material, parser ) );
  35360. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  35361. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35362. materialType = sgExtension.getMaterialType( material );
  35363. pending.push( sgExtension.extendParams( materialParams, material, parser ) );
  35364. } else if ( material.pbrMetallicRoughness !== undefined ) {
  35365. // Specification:
  35366. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  35367. materialType = THREE.MeshStandardMaterial;
  35368. var metallicRoughness = material.pbrMetallicRoughness;
  35369. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35370. materialParams.opacity = 1.0;
  35371. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35372. var array = metallicRoughness.baseColorFactor;
  35373. materialParams.color.fromArray( array );
  35374. materialParams.opacity = array[ 3 ];
  35375. }
  35376. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35377. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  35378. }
  35379. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  35380. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  35381. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  35382. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  35383. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  35384. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  35385. }
  35386. } else {
  35387. materialType = THREE.MeshPhongMaterial;
  35388. }
  35389. if ( material.doubleSided === true ) {
  35390. materialParams.side = THREE.DoubleSide;
  35391. }
  35392. var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
  35393. if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
  35394. materialParams.transparent = true;
  35395. } else {
  35396. materialParams.transparent = false;
  35397. }
  35398. if ( material.normalTexture !== undefined ) {
  35399. pending.push( parser.assignTexture( materialParams, 'normalMap', material.normalTexture.index ) );
  35400. }
  35401. if ( material.occlusionTexture !== undefined ) {
  35402. pending.push( parser.assignTexture( materialParams, 'aoMap', material.occlusionTexture.index ) );
  35403. }
  35404. if ( material.emissiveFactor !== undefined ) {
  35405. if ( materialType === THREE.MeshBasicMaterial ) {
  35406. materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
  35407. } else {
  35408. materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
  35409. }
  35410. }
  35411. if ( material.emissiveTexture !== undefined ) {
  35412. if ( materialType === THREE.MeshBasicMaterial ) {
  35413. pending.push( parser.assignTexture( materialParams, 'map', material.emissiveTexture.index ) );
  35414. } else {
  35415. pending.push( parser.assignTexture( materialParams, 'emissiveMap', material.emissiveTexture.index ) );
  35416. }
  35417. }
  35418. return Promise.all( pending ).then( function () {
  35419. var _material;
  35420. if ( materialType === THREE.ShaderMaterial ) {
  35421. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  35422. } else {
  35423. _material = new materialType( materialParams );
  35424. }
  35425. if ( material.name !== undefined ) _material.name = material.name;
  35426. // Normal map textures use OpenGL conventions:
  35427. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  35428. _material.normalScale.x = -1;
  35429. _material.userData = material.extras;
  35430. return _material;
  35431. } );
  35432. } );
  35433. };
  35434. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  35435. return this._withDependencies( [
  35436. 'accessors',
  35437. ] ).then( function ( dependencies ) {
  35438. return _each( primitives, function ( primitive ) {
  35439. var geometry = new THREE.BufferGeometry();
  35440. var attributes = primitive.attributes;
  35441. for ( var attributeId in attributes ) {
  35442. var attributeEntry = attributes[ attributeId ];
  35443. if ( attributeEntry === undefined ) return;
  35444. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  35445. switch ( attributeId ) {
  35446. case 'POSITION':
  35447. geometry.addAttribute( 'position', bufferAttribute );
  35448. break;
  35449. case 'NORMAL':
  35450. geometry.addAttribute( 'normal', bufferAttribute );
  35451. break;
  35452. case 'TEXCOORD_0':
  35453. case 'TEXCOORD0':
  35454. case 'TEXCOORD':
  35455. geometry.addAttribute( 'uv', bufferAttribute );
  35456. break;
  35457. case 'TEXCOORD_1':
  35458. geometry.addAttribute( 'uv2', bufferAttribute );
  35459. break;
  35460. case 'COLOR_0':
  35461. case 'COLOR0':
  35462. case 'COLOR':
  35463. geometry.addAttribute( 'color', bufferAttribute );
  35464. break;
  35465. case 'WEIGHTS_0':
  35466. case 'WEIGHT': // WEIGHT semantic deprecated.
  35467. geometry.addAttribute( 'skinWeight', bufferAttribute );
  35468. break;
  35469. case 'JOINTS_0':
  35470. case 'JOINT': // JOINT semantic deprecated.
  35471. geometry.addAttribute( 'skinIndex', bufferAttribute );
  35472. break;
  35473. }
  35474. }
  35475. if ( primitive.indices !== undefined ) {
  35476. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  35477. }
  35478. return geometry;
  35479. } );
  35480. } );
  35481. };
  35482. /**
  35483. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  35484. */
  35485. GLTFParser.prototype.loadMeshes = function () {
  35486. var scope = this;
  35487. var json = this.json;
  35488. return this._withDependencies( [
  35489. 'accessors',
  35490. 'materials'
  35491. ] ).then( function ( dependencies ) {
  35492. return _each( json.meshes, function ( meshDef ) {
  35493. var group = new THREE.Group();
  35494. if ( meshDef.name !== undefined ) group.name = meshDef.name;
  35495. if ( meshDef.extras ) group.userData = meshDef.extras;
  35496. var primitives = meshDef.primitives || [];
  35497. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  35498. for ( var name in primitives ) {
  35499. var primitive = primitives[ name ];
  35500. var geometry = geometries[ name ];
  35501. var material = primitive.material === undefined
  35502. ? createDefaultMaterial()
  35503. : dependencies.materials[ primitive.material ];
  35504. if ( material.aoMap
  35505. && geometry.attributes.uv2 === undefined
  35506. && geometry.attributes.uv !== undefined ) {
  35507. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  35508. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  35509. }
  35510. if ( geometry.attributes.color !== undefined ) {
  35511. material.vertexColors = THREE.VertexColors;
  35512. material.needsUpdate = true;
  35513. }
  35514. if ( geometry.attributes.normal === undefined ) {
  35515. if ( material.flatShading !== undefined ) {
  35516. material.flatShading = true;
  35517. } else {
  35518. // TODO: Remove this backwards-compatibility fix after r87 release.
  35519. material.shading = THREE.FlatShading;
  35520. }
  35521. }
  35522. var mesh;
  35523. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  35524. mesh = new THREE.Mesh( geometry, material );
  35525. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  35526. mesh = new THREE.Mesh( geometry, material );
  35527. mesh.drawMode = THREE.TriangleStripDrawMode;
  35528. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  35529. mesh = new THREE.Mesh( geometry, material );
  35530. mesh.drawMode = THREE.TriangleFanDrawMode;
  35531. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  35532. mesh = new THREE.LineSegments( geometry, material );
  35533. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  35534. mesh = new THREE.Line( geometry, material );
  35535. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  35536. mesh = new THREE.LineLoop( geometry, material );
  35537. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  35538. mesh = new THREE.Points( geometry, material );
  35539. } else {
  35540. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ', primitive.mode );
  35541. }
  35542. mesh.name = group.name + '_' + name;
  35543. if ( primitive.targets !== undefined ) {
  35544. addMorphTargets( mesh, meshDef, primitive, dependencies );
  35545. }
  35546. if ( primitive.extras ) mesh.userData = primitive.extras;
  35547. group.add( mesh );
  35548. }
  35549. return group;
  35550. } );
  35551. } );
  35552. } );
  35553. };
  35554. /**
  35555. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  35556. */
  35557. GLTFParser.prototype.loadCameras = function () {
  35558. var json = this.json;
  35559. return _each( json.cameras, function ( camera ) {
  35560. var _camera;
  35561. var params = camera[ camera.type ];
  35562. if ( !params ) {
  35563. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  35564. return;
  35565. }
  35566. if ( camera.type === 'perspective' ) {
  35567. var aspectRatio = params.aspectRatio || 1;
  35568. var xfov = params.yfov * aspectRatio;
  35569. _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  35570. } else if ( camera.type === 'orthographic' ) {
  35571. _camera = new THREE.OrthographicCamera( params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar );
  35572. }
  35573. if ( camera.name !== undefined ) _camera.name = camera.name;
  35574. if ( camera.extras ) _camera.userData = camera.extras;
  35575. return _camera;
  35576. } );
  35577. };
  35578. GLTFParser.prototype.loadSkins = function () {
  35579. var json = this.json;
  35580. return this._withDependencies( [
  35581. 'accessors'
  35582. ] ).then( function ( dependencies ) {
  35583. return _each( json.skins, function ( skin ) {
  35584. var _skin = {
  35585. joints: skin.joints,
  35586. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  35587. };
  35588. return _skin;
  35589. } );
  35590. } );
  35591. };
  35592. GLTFParser.prototype.loadAnimations = function () {
  35593. var json = this.json;
  35594. return this._withDependencies( [
  35595. 'accessors',
  35596. 'nodes'
  35597. ] ).then( function ( dependencies ) {
  35598. return _each( json.animations, function ( animation, animationId ) {
  35599. var tracks = [];
  35600. for ( var channelId in animation.channels ) {
  35601. var channel = animation.channels[ channelId ];
  35602. var sampler = animation.samplers[ channel.sampler ];
  35603. if ( sampler ) {
  35604. var target = channel.target;
  35605. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  35606. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  35607. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  35608. var inputAccessor = dependencies.accessors[ input ];
  35609. var outputAccessor = dependencies.accessors[ output ];
  35610. var node = dependencies.nodes[ name ];
  35611. if ( node ) {
  35612. node.updateMatrix();
  35613. node.matrixAutoUpdate = true;
  35614. var TypedKeyframeTrack;
  35615. switch ( PATH_PROPERTIES[ target.path ] ) {
  35616. case PATH_PROPERTIES.weights:
  35617. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  35618. break;
  35619. case PATH_PROPERTIES.rotation:
  35620. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  35621. break;
  35622. case PATH_PROPERTIES.position:
  35623. case PATH_PROPERTIES.scale:
  35624. default:
  35625. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  35626. break;
  35627. }
  35628. var targetName = node.name ? node.name : node.uuid;
  35629. if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {
  35630. console.warn( 'THREE.GLTFLoader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );
  35631. }
  35632. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  35633. var targetNames = [];
  35634. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  35635. // node should be THREE.Group here but
  35636. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  35637. // the property of a mesh object under node.
  35638. // So finding targets here.
  35639. node.traverse( function ( object ) {
  35640. if ( object.isMesh === true && object.material.morphTargets === true ) {
  35641. targetNames.push( object.name ? object.name : object.uuid );
  35642. }
  35643. } );
  35644. } else {
  35645. targetNames.push( targetName );
  35646. }
  35647. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  35648. // buffers before creating a truncated copy to keep. Because buffers may
  35649. // be reused by other tracks, make copies here.
  35650. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  35651. tracks.push( new TypedKeyframeTrack(
  35652. targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ],
  35653. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  35654. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  35655. interpolation
  35656. ) );
  35657. }
  35658. }
  35659. }
  35660. }
  35661. var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
  35662. return new THREE.AnimationClip( name, undefined, tracks );
  35663. } );
  35664. } );
  35665. };
  35666. GLTFParser.prototype.loadNodes = function () {
  35667. var json = this.json;
  35668. var extensions = this.extensions;
  35669. var scope = this;
  35670. var nodes = json.nodes || [];
  35671. var skins = json.skins || [];
  35672. // Nothing in the node definition indicates whether it is a Bone or an
  35673. // Object3D. Use the skins' joint references to mark bones.
  35674. skins.forEach( function ( skin ) {
  35675. skin.joints.forEach( function ( id ) {
  35676. nodes[ id ].isBone = true;
  35677. } );
  35678. } );
  35679. return _each( json.nodes, function ( node ) {
  35680. var matrix = new THREE.Matrix4();
  35681. var _node = node.isBone === true ? new THREE.Bone() : new THREE.Object3D();
  35682. if ( node.name !== undefined ) {
  35683. _node.name = THREE.PropertyBinding.sanitizeNodeName( node.name );
  35684. }
  35685. if ( node.extras ) _node.userData = node.extras;
  35686. if ( node.matrix !== undefined ) {
  35687. matrix.fromArray( node.matrix );
  35688. _node.applyMatrix( matrix );
  35689. } else {
  35690. if ( node.translation !== undefined ) {
  35691. _node.position.fromArray( node.translation );
  35692. }
  35693. if ( node.rotation !== undefined ) {
  35694. _node.quaternion.fromArray( node.rotation );
  35695. }
  35696. if ( node.scale !== undefined ) {
  35697. _node.scale.fromArray( node.scale );
  35698. }
  35699. }
  35700. return _node;
  35701. } ).then( function ( __nodes ) {
  35702. return scope._withDependencies( [
  35703. 'meshes',
  35704. 'skins',
  35705. 'cameras'
  35706. ] ).then( function ( dependencies ) {
  35707. return _each( __nodes, function ( _node, nodeId ) {
  35708. var node = json.nodes[ nodeId ];
  35709. var meshes;
  35710. if ( node.mesh !== undefined) {
  35711. meshes = [ node.mesh ];
  35712. } else if ( node.meshes !== undefined ) {
  35713. console.warn( 'THREE.GLTFLoader: Legacy glTF file detected. Nodes may have no more than one mesh.' );
  35714. meshes = node.meshes;
  35715. }
  35716. if ( meshes !== undefined ) {
  35717. for ( var meshId in meshes ) {
  35718. var mesh = meshes[ meshId ];
  35719. var group = dependencies.meshes[ mesh ];
  35720. if ( group === undefined ) {
  35721. console.warn( 'THREE.GLTFLoader: Could not find node "' + mesh + '".' );
  35722. continue;
  35723. }
  35724. // do not clone children as they will be replaced anyway
  35725. var clonedgroup = group.clone( false );
  35726. for ( var childrenId in group.children ) {
  35727. var child = group.children[ childrenId ];
  35728. var originalChild = child;
  35729. // clone Mesh to add to _node
  35730. var originalMaterial = child.material;
  35731. var originalGeometry = child.geometry;
  35732. var originalInfluences = child.morphTargetInfluences;
  35733. var originalUserData = child.userData;
  35734. var originalName = child.name;
  35735. var material = originalMaterial;
  35736. switch ( child.type ) {
  35737. case 'LineSegments':
  35738. child = new THREE.LineSegments( originalGeometry, material );
  35739. break;
  35740. case 'LineLoop':
  35741. child = new THREE.LineLoop( originalGeometry, material );
  35742. break;
  35743. case 'Line':
  35744. child = new THREE.Line( originalGeometry, material );
  35745. break;
  35746. case 'Points':
  35747. child = new THREE.Points( originalGeometry, material );
  35748. break;
  35749. default:
  35750. child = new THREE.Mesh( originalGeometry, material );
  35751. child.drawMode = originalChild.drawMode;
  35752. }
  35753. child.castShadow = true;
  35754. child.morphTargetInfluences = originalInfluences;
  35755. child.userData = originalUserData;
  35756. child.name = originalName;
  35757. var skinEntry;
  35758. if ( node.skin !== undefined ) {
  35759. skinEntry = dependencies.skins[ node.skin ];
  35760. }
  35761. // Replace Mesh with SkinnedMesh in library
  35762. if ( skinEntry ) {
  35763. var geometry = originalGeometry;
  35764. material = originalMaterial;
  35765. material.skinning = true;
  35766. child = new THREE.SkinnedMesh( geometry, material );
  35767. child.castShadow = true;
  35768. child.userData = originalUserData;
  35769. child.name = originalName;
  35770. var bones = [];
  35771. var boneInverses = [];
  35772. for ( var i = 0, l = skinEntry.joints.length; i < l; i ++ ) {
  35773. var jointId = skinEntry.joints[ i ];
  35774. var jointNode = __nodes[ jointId ];
  35775. if ( jointNode ) {
  35776. bones.push( jointNode );
  35777. var m = skinEntry.inverseBindMatrices.array;
  35778. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  35779. boneInverses.push( mat );
  35780. } else {
  35781. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  35782. }
  35783. }
  35784. child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
  35785. }
  35786. clonedgroup.add( child );
  35787. }
  35788. _node.add( clonedgroup );
  35789. }
  35790. }
  35791. if ( node.camera !== undefined ) {
  35792. var camera = dependencies.cameras[ node.camera ];
  35793. _node.add( camera );
  35794. }
  35795. if ( node.extensions
  35796. && node.extensions[ EXTENSIONS.KHR_LIGHTS ]
  35797. && node.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  35798. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  35799. _node.add( lights[ node.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  35800. }
  35801. return _node;
  35802. } );
  35803. } );
  35804. } );
  35805. };
  35806. GLTFParser.prototype.loadScenes = function () {
  35807. var json = this.json;
  35808. var extensions = this.extensions;
  35809. // scene node hierachy builder
  35810. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  35811. var _node = allNodes[ nodeId ];
  35812. parentObject.add( _node );
  35813. var node = json.nodes[ nodeId ];
  35814. if ( node.children ) {
  35815. var children = node.children;
  35816. for ( var i = 0, l = children.length; i < l; i ++ ) {
  35817. var child = children[ i ];
  35818. buildNodeHierachy( child, _node, allNodes );
  35819. }
  35820. }
  35821. }
  35822. return this._withDependencies( [
  35823. 'nodes'
  35824. ] ).then( function ( dependencies ) {
  35825. return _each( json.scenes, function ( scene ) {
  35826. var _scene = new THREE.Scene();
  35827. if ( scene.name !== undefined ) _scene.name = scene.name;
  35828. if ( scene.extras ) _scene.userData = scene.extras;
  35829. var nodes = scene.nodes || [];
  35830. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  35831. var nodeId = nodes[ i ];
  35832. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  35833. }
  35834. _scene.traverse( function ( child ) {
  35835. // for Specular-Glossiness.
  35836. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
  35837. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  35838. }
  35839. } );
  35840. // Ambient lighting, if present, is always attached to the scene root.
  35841. if ( scene.extensions
  35842. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
  35843. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  35844. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  35845. _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  35846. }
  35847. return _scene;
  35848. } );
  35849. } );
  35850. };
  35851. return GLTFLoader;
  35852. } )();
  35853. },{}],44:[function(_dereq_,module,exports){
  35854. /**
  35855. * Loads a Wavefront .mtl file specifying materials
  35856. *
  35857. * @author angelxuanchang
  35858. */
  35859. THREE.MTLLoader = function ( manager ) {
  35860. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35861. };
  35862. THREE.MTLLoader.prototype = {
  35863. constructor: THREE.MTLLoader,
  35864. /**
  35865. * Loads and parses a MTL asset from a URL.
  35866. *
  35867. * @param {String} url - URL to the MTL file.
  35868. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  35869. * @param {Function} [onProgress] - Callback for download progress.
  35870. * @param {Function} [onError] - Callback for download errors.
  35871. *
  35872. * @see setPath setTexturePath
  35873. *
  35874. * @note In order for relative texture references to resolve correctly
  35875. * you must call setPath and/or setTexturePath explicitly prior to load.
  35876. */
  35877. load: function ( url, onLoad, onProgress, onError ) {
  35878. var scope = this;
  35879. var loader = new THREE.FileLoader( this.manager );
  35880. loader.setPath( this.path );
  35881. loader.load( url, function ( text ) {
  35882. onLoad( scope.parse( text ) );
  35883. }, onProgress, onError );
  35884. },
  35885. /**
  35886. * Set base path for resolving references.
  35887. * If set this path will be prepended to each loaded and found reference.
  35888. *
  35889. * @see setTexturePath
  35890. * @param {String} path
  35891. *
  35892. * @example
  35893. * mtlLoader.setPath( 'assets/obj/' );
  35894. * mtlLoader.load( 'my.mtl', ... );
  35895. */
  35896. setPath: function ( path ) {
  35897. this.path = path;
  35898. },
  35899. /**
  35900. * Set base path for resolving texture references.
  35901. * If set this path will be prepended found texture reference.
  35902. * If not set and setPath is, it will be used as texture base path.
  35903. *
  35904. * @see setPath
  35905. * @param {String} path
  35906. *
  35907. * @example
  35908. * mtlLoader.setPath( 'assets/obj/' );
  35909. * mtlLoader.setTexturePath( 'assets/textures/' );
  35910. * mtlLoader.load( 'my.mtl', ... );
  35911. */
  35912. setTexturePath: function ( path ) {
  35913. this.texturePath = path;
  35914. },
  35915. setBaseUrl: function ( path ) {
  35916. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  35917. this.setTexturePath( path );
  35918. },
  35919. setCrossOrigin: function ( value ) {
  35920. this.crossOrigin = value;
  35921. },
  35922. setMaterialOptions: function ( value ) {
  35923. this.materialOptions = value;
  35924. },
  35925. /**
  35926. * Parses a MTL file.
  35927. *
  35928. * @param {String} text - Content of MTL file
  35929. * @return {THREE.MTLLoader.MaterialCreator}
  35930. *
  35931. * @see setPath setTexturePath
  35932. *
  35933. * @note In order for relative texture references to resolve correctly
  35934. * you must call setPath and/or setTexturePath explicitly prior to parse.
  35935. */
  35936. parse: function ( text ) {
  35937. var lines = text.split( '\n' );
  35938. var info = {};
  35939. var delimiter_pattern = /\s+/;
  35940. var materialsInfo = {};
  35941. for ( var i = 0; i < lines.length; i ++ ) {
  35942. var line = lines[ i ];
  35943. line = line.trim();
  35944. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  35945. // Blank line or comment ignore
  35946. continue;
  35947. }
  35948. var pos = line.indexOf( ' ' );
  35949. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  35950. key = key.toLowerCase();
  35951. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  35952. value = value.trim();
  35953. if ( key === 'newmtl' ) {
  35954. // New material
  35955. info = { name: value };
  35956. materialsInfo[ value ] = info;
  35957. } else if ( info ) {
  35958. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  35959. var ss = value.split( delimiter_pattern, 3 );
  35960. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  35961. } else {
  35962. info[ key ] = value;
  35963. }
  35964. }
  35965. }
  35966. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  35967. materialCreator.setCrossOrigin( this.crossOrigin );
  35968. materialCreator.setManager( this.manager );
  35969. materialCreator.setMaterials( materialsInfo );
  35970. return materialCreator;
  35971. }
  35972. };
  35973. /**
  35974. * Create a new THREE-MTLLoader.MaterialCreator
  35975. * @param baseUrl - Url relative to which textures are loaded
  35976. * @param options - Set of options on how to construct the materials
  35977. * side: Which side to apply the material
  35978. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  35979. * wrap: What type of wrapping to apply for textures
  35980. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  35981. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  35982. * Default: false, assumed to be already normalized
  35983. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  35984. * Default: false
  35985. * @constructor
  35986. */
  35987. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  35988. this.baseUrl = baseUrl || '';
  35989. this.options = options;
  35990. this.materialsInfo = {};
  35991. this.materials = {};
  35992. this.materialsArray = [];
  35993. this.nameLookup = {};
  35994. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  35995. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  35996. };
  35997. THREE.MTLLoader.MaterialCreator.prototype = {
  35998. constructor: THREE.MTLLoader.MaterialCreator,
  35999. crossOrigin: 'Anonymous',
  36000. setCrossOrigin: function ( value ) {
  36001. this.crossOrigin = value;
  36002. },
  36003. setManager: function ( value ) {
  36004. this.manager = value;
  36005. },
  36006. setMaterials: function ( materialsInfo ) {
  36007. this.materialsInfo = this.convert( materialsInfo );
  36008. this.materials = {};
  36009. this.materialsArray = [];
  36010. this.nameLookup = {};
  36011. },
  36012. convert: function ( materialsInfo ) {
  36013. if ( ! this.options ) return materialsInfo;
  36014. var converted = {};
  36015. for ( var mn in materialsInfo ) {
  36016. // Convert materials info into normalized form based on options
  36017. var mat = materialsInfo[ mn ];
  36018. var covmat = {};
  36019. converted[ mn ] = covmat;
  36020. for ( var prop in mat ) {
  36021. var save = true;
  36022. var value = mat[ prop ];
  36023. var lprop = prop.toLowerCase();
  36024. switch ( lprop ) {
  36025. case 'kd':
  36026. case 'ka':
  36027. case 'ks':
  36028. // Diffuse color (color under white light) using RGB values
  36029. if ( this.options && this.options.normalizeRGB ) {
  36030. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  36031. }
  36032. if ( this.options && this.options.ignoreZeroRGBs ) {
  36033. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  36034. // ignore
  36035. save = false;
  36036. }
  36037. }
  36038. break;
  36039. default:
  36040. break;
  36041. }
  36042. if ( save ) {
  36043. covmat[ lprop ] = value;
  36044. }
  36045. }
  36046. }
  36047. return converted;
  36048. },
  36049. preload: function () {
  36050. for ( var mn in this.materialsInfo ) {
  36051. this.create( mn );
  36052. }
  36053. },
  36054. getIndex: function ( materialName ) {
  36055. return this.nameLookup[ materialName ];
  36056. },
  36057. getAsArray: function () {
  36058. var index = 0;
  36059. for ( var mn in this.materialsInfo ) {
  36060. this.materialsArray[ index ] = this.create( mn );
  36061. this.nameLookup[ mn ] = index;
  36062. index ++;
  36063. }
  36064. return this.materialsArray;
  36065. },
  36066. create: function ( materialName ) {
  36067. if ( this.materials[ materialName ] === undefined ) {
  36068. this.createMaterial_( materialName );
  36069. }
  36070. return this.materials[ materialName ];
  36071. },
  36072. createMaterial_: function ( materialName ) {
  36073. // Create material
  36074. var scope = this;
  36075. var mat = this.materialsInfo[ materialName ];
  36076. var params = {
  36077. name: materialName,
  36078. side: this.side
  36079. };
  36080. function resolveURL( baseUrl, url ) {
  36081. if ( typeof url !== 'string' || url === '' )
  36082. return '';
  36083. // Absolute URL
  36084. if ( /^https?:\/\//i.test( url ) ) return url;
  36085. return baseUrl + url;
  36086. }
  36087. function setMapForType( mapType, value ) {
  36088. if ( params[ mapType ] ) return; // Keep the first encountered texture
  36089. var texParams = scope.getTextureParams( value, params );
  36090. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  36091. map.repeat.copy( texParams.scale );
  36092. map.offset.copy( texParams.offset );
  36093. map.wrapS = scope.wrap;
  36094. map.wrapT = scope.wrap;
  36095. params[ mapType ] = map;
  36096. }
  36097. for ( var prop in mat ) {
  36098. var value = mat[ prop ];
  36099. var n;
  36100. if ( value === '' ) continue;
  36101. switch ( prop.toLowerCase() ) {
  36102. // Ns is material specular exponent
  36103. case 'kd':
  36104. // Diffuse color (color under white light) using RGB values
  36105. params.color = new THREE.Color().fromArray( value );
  36106. break;
  36107. case 'ks':
  36108. // Specular color (color when light is reflected from shiny surface) using RGB values
  36109. params.specular = new THREE.Color().fromArray( value );
  36110. break;
  36111. case 'map_kd':
  36112. // Diffuse texture map
  36113. setMapForType( "map", value );
  36114. break;
  36115. case 'map_ks':
  36116. // Specular map
  36117. setMapForType( "specularMap", value );
  36118. break;
  36119. case 'norm':
  36120. setMapForType( "normalMap", value );
  36121. break;
  36122. case 'map_bump':
  36123. case 'bump':
  36124. // Bump texture map
  36125. setMapForType( "bumpMap", value );
  36126. break;
  36127. case 'ns':
  36128. // The specular exponent (defines the focus of the specular highlight)
  36129. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  36130. params.shininess = parseFloat( value );
  36131. break;
  36132. case 'd':
  36133. n = parseFloat(value);
  36134. if ( n < 1 ) {
  36135. params.opacity = n;
  36136. params.transparent = true;
  36137. }
  36138. break;
  36139. case 'tr':
  36140. n = parseFloat(value);
  36141. if ( n > 0 ) {
  36142. params.opacity = 1 - n;
  36143. params.transparent = true;
  36144. }
  36145. break;
  36146. default:
  36147. break;
  36148. }
  36149. }
  36150. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  36151. return this.materials[ materialName ];
  36152. },
  36153. getTextureParams: function ( value, matParams ) {
  36154. var texParams = {
  36155. scale: new THREE.Vector2( 1, 1 ),
  36156. offset: new THREE.Vector2( 0, 0 )
  36157. };
  36158. var items = value.split( /\s+/ );
  36159. var pos;
  36160. pos = items.indexOf( '-bm' );
  36161. if ( pos >= 0 ) {
  36162. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  36163. items.splice( pos, 2 );
  36164. }
  36165. pos = items.indexOf( '-s' );
  36166. if ( pos >= 0 ) {
  36167. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36168. items.splice( pos, 4 ); // we expect 3 parameters here!
  36169. }
  36170. pos = items.indexOf( '-o' );
  36171. if ( pos >= 0 ) {
  36172. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36173. items.splice( pos, 4 ); // we expect 3 parameters here!
  36174. }
  36175. texParams.url = items.join( ' ' ).trim();
  36176. return texParams;
  36177. },
  36178. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  36179. var texture;
  36180. var loader = THREE.Loader.Handlers.get( url );
  36181. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  36182. if ( loader === null ) {
  36183. loader = new THREE.TextureLoader( manager );
  36184. }
  36185. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  36186. texture = loader.load( url, onLoad, onProgress, onError );
  36187. if ( mapping !== undefined ) texture.mapping = mapping;
  36188. return texture;
  36189. }
  36190. };
  36191. },{}],45:[function(_dereq_,module,exports){
  36192. /**
  36193. * @author mrdoob / http://mrdoob.com/
  36194. */
  36195. THREE.OBJLoader = ( function () {
  36196. // o object_name | g group_name
  36197. var object_pattern = /^[og]\s*(.+)?/;
  36198. // mtllib file_reference
  36199. var material_library_pattern = /^mtllib /;
  36200. // usemtl material_name
  36201. var material_use_pattern = /^usemtl /;
  36202. function ParserState() {
  36203. var state = {
  36204. objects : [],
  36205. object : {},
  36206. vertices : [],
  36207. normals : [],
  36208. uvs : [],
  36209. materialLibraries : [],
  36210. startObject: function ( name, fromDeclaration ) {
  36211. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  36212. // file. We need to use it for the first parsed g/o to keep things in sync.
  36213. if ( this.object && this.object.fromDeclaration === false ) {
  36214. this.object.name = name;
  36215. this.object.fromDeclaration = ( fromDeclaration !== false );
  36216. return;
  36217. }
  36218. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  36219. if ( this.object && typeof this.object._finalize === 'function' ) {
  36220. this.object._finalize( true );
  36221. }
  36222. this.object = {
  36223. name : name || '',
  36224. fromDeclaration : ( fromDeclaration !== false ),
  36225. geometry : {
  36226. vertices : [],
  36227. normals : [],
  36228. uvs : []
  36229. },
  36230. materials : [],
  36231. smooth : true,
  36232. startMaterial: function ( name, libraries ) {
  36233. var previous = this._finalize( false );
  36234. // New usemtl declaration overwrites an inherited material, except if faces were declared
  36235. // after the material, then it must be preserved for proper MultiMaterial continuation.
  36236. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  36237. this.materials.splice( previous.index, 1 );
  36238. }
  36239. var material = {
  36240. index : this.materials.length,
  36241. name : name || '',
  36242. mtllib : ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  36243. smooth : ( previous !== undefined ? previous.smooth : this.smooth ),
  36244. groupStart : ( previous !== undefined ? previous.groupEnd : 0 ),
  36245. groupEnd : -1,
  36246. groupCount : -1,
  36247. inherited : false,
  36248. clone: function ( index ) {
  36249. var cloned = {
  36250. index : ( typeof index === 'number' ? index : this.index ),
  36251. name : this.name,
  36252. mtllib : this.mtllib,
  36253. smooth : this.smooth,
  36254. groupStart : 0,
  36255. groupEnd : -1,
  36256. groupCount : -1,
  36257. inherited : false
  36258. };
  36259. cloned.clone = this.clone.bind(cloned);
  36260. return cloned;
  36261. }
  36262. };
  36263. this.materials.push( material );
  36264. return material;
  36265. },
  36266. currentMaterial: function () {
  36267. if ( this.materials.length > 0 ) {
  36268. return this.materials[ this.materials.length - 1 ];
  36269. }
  36270. return undefined;
  36271. },
  36272. _finalize: function ( end ) {
  36273. var lastMultiMaterial = this.currentMaterial();
  36274. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === -1 ) {
  36275. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  36276. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  36277. lastMultiMaterial.inherited = false;
  36278. }
  36279. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  36280. if ( end && this.materials.length > 1 ) {
  36281. for ( var mi = this.materials.length - 1; mi >= 0; mi-- ) {
  36282. if ( this.materials[ mi ].groupCount <= 0 ) {
  36283. this.materials.splice( mi, 1 );
  36284. }
  36285. }
  36286. }
  36287. // Guarantee at least one empty material, this makes the creation later more straight forward.
  36288. if ( end && this.materials.length === 0 ) {
  36289. this.materials.push({
  36290. name : '',
  36291. smooth : this.smooth
  36292. });
  36293. }
  36294. return lastMultiMaterial;
  36295. }
  36296. };
  36297. // Inherit previous objects material.
  36298. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  36299. // If a usemtl declaration is encountered while this new object is being parsed, it will
  36300. // overwrite the inherited material. Exception being that there was already face declarations
  36301. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  36302. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  36303. var declared = previousMaterial.clone( 0 );
  36304. declared.inherited = true;
  36305. this.object.materials.push( declared );
  36306. }
  36307. this.objects.push( this.object );
  36308. },
  36309. finalize: function () {
  36310. if ( this.object && typeof this.object._finalize === 'function' ) {
  36311. this.object._finalize( true );
  36312. }
  36313. },
  36314. parseVertexIndex: function ( value, len ) {
  36315. var index = parseInt( value, 10 );
  36316. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36317. },
  36318. parseNormalIndex: function ( value, len ) {
  36319. var index = parseInt( value, 10 );
  36320. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36321. },
  36322. parseUVIndex: function ( value, len ) {
  36323. var index = parseInt( value, 10 );
  36324. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  36325. },
  36326. addVertex: function ( a, b, c ) {
  36327. var src = this.vertices;
  36328. var dst = this.object.geometry.vertices;
  36329. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36330. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36331. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36332. },
  36333. addVertexLine: function ( a ) {
  36334. var src = this.vertices;
  36335. var dst = this.object.geometry.vertices;
  36336. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36337. },
  36338. addNormal: function ( a, b, c ) {
  36339. var src = this.normals;
  36340. var dst = this.object.geometry.normals;
  36341. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36342. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36343. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36344. },
  36345. addUV: function ( a, b, c ) {
  36346. var src = this.uvs;
  36347. var dst = this.object.geometry.uvs;
  36348. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36349. dst.push( src[ b + 0 ], src[ b + 1 ] );
  36350. dst.push( src[ c + 0 ], src[ c + 1 ] );
  36351. },
  36352. addUVLine: function ( a ) {
  36353. var src = this.uvs;
  36354. var dst = this.object.geometry.uvs;
  36355. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36356. },
  36357. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  36358. var vLen = this.vertices.length;
  36359. var ia = this.parseVertexIndex( a, vLen );
  36360. var ib = this.parseVertexIndex( b, vLen );
  36361. var ic = this.parseVertexIndex( c, vLen );
  36362. this.addVertex( ia, ib, ic );
  36363. if ( ua !== undefined ) {
  36364. var uvLen = this.uvs.length;
  36365. ia = this.parseUVIndex( ua, uvLen );
  36366. ib = this.parseUVIndex( ub, uvLen );
  36367. ic = this.parseUVIndex( uc, uvLen );
  36368. this.addUV( ia, ib, ic );
  36369. }
  36370. if ( na !== undefined ) {
  36371. // Normals are many times the same. If so, skip function call and parseInt.
  36372. var nLen = this.normals.length;
  36373. ia = this.parseNormalIndex( na, nLen );
  36374. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  36375. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  36376. this.addNormal( ia, ib, ic );
  36377. }
  36378. },
  36379. addLineGeometry: function ( vertices, uvs ) {
  36380. this.object.geometry.type = 'Line';
  36381. var vLen = this.vertices.length;
  36382. var uvLen = this.uvs.length;
  36383. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36384. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36385. }
  36386. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  36387. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  36388. }
  36389. }
  36390. };
  36391. state.startObject( '', false );
  36392. return state;
  36393. }
  36394. //
  36395. function OBJLoader( manager ) {
  36396. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36397. this.materials = null;
  36398. };
  36399. OBJLoader.prototype = {
  36400. constructor: OBJLoader,
  36401. load: function ( url, onLoad, onProgress, onError ) {
  36402. var scope = this;
  36403. var loader = new THREE.FileLoader( scope.manager );
  36404. loader.setPath( this.path );
  36405. loader.load( url, function ( text ) {
  36406. onLoad( scope.parse( text ) );
  36407. }, onProgress, onError );
  36408. },
  36409. setPath: function ( value ) {
  36410. this.path = value;
  36411. },
  36412. setMaterials: function ( materials ) {
  36413. this.materials = materials;
  36414. return this;
  36415. },
  36416. parse: function ( text ) {
  36417. console.time( 'OBJLoader' );
  36418. var state = new ParserState();
  36419. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  36420. // This is faster than String.split with regex that splits on both
  36421. text = text.replace( /\r\n/g, '\n' );
  36422. }
  36423. if ( text.indexOf( '\\\n' ) !== - 1) {
  36424. // join lines separated by a line continuation character (\)
  36425. text = text.replace( /\\\n/g, '' );
  36426. }
  36427. var lines = text.split( '\n' );
  36428. var line = '', lineFirstChar = '';
  36429. var lineLength = 0;
  36430. var result = [];
  36431. // Faster to just trim left side of the line. Use if available.
  36432. var trimLeft = ( typeof ''.trimLeft === 'function' );
  36433. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  36434. line = lines[ i ];
  36435. line = trimLeft ? line.trimLeft() : line.trim();
  36436. lineLength = line.length;
  36437. if ( lineLength === 0 ) continue;
  36438. lineFirstChar = line.charAt( 0 );
  36439. // @todo invoke passed in handler if any
  36440. if ( lineFirstChar === '#' ) continue;
  36441. if ( lineFirstChar === 'v' ) {
  36442. var data = line.split( /\s+/ );
  36443. switch ( data[ 0 ] ) {
  36444. case 'v':
  36445. state.vertices.push(
  36446. parseFloat( data[ 1 ] ),
  36447. parseFloat( data[ 2 ] ),
  36448. parseFloat( data[ 3 ] )
  36449. );
  36450. break;
  36451. case 'vn':
  36452. state.normals.push(
  36453. parseFloat( data[ 1 ] ),
  36454. parseFloat( data[ 2 ] ),
  36455. parseFloat( data[ 3 ] )
  36456. );
  36457. break;
  36458. case 'vt':
  36459. state.uvs.push(
  36460. parseFloat( data[ 1 ] ),
  36461. parseFloat( data[ 2 ] )
  36462. );
  36463. break;
  36464. }
  36465. } else if ( lineFirstChar === 'f' ) {
  36466. var lineData = line.substr( 1 ).trim();
  36467. var vertexData = lineData.split( /\s+/ );
  36468. var faceVertices = [];
  36469. // Parse the face vertex data into an easy to work with format
  36470. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  36471. var vertex = vertexData[ j ];
  36472. if ( vertex.length > 0 ) {
  36473. var vertexParts = vertex.split( '/' );
  36474. faceVertices.push( vertexParts );
  36475. }
  36476. }
  36477. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  36478. var v1 = faceVertices[ 0 ];
  36479. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  36480. var v2 = faceVertices[ j ];
  36481. var v3 = faceVertices[ j + 1 ];
  36482. state.addFace(
  36483. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  36484. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  36485. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  36486. );
  36487. }
  36488. } else if ( lineFirstChar === 'l' ) {
  36489. var lineParts = line.substring( 1 ).trim().split( " " );
  36490. var lineVertices = [], lineUVs = [];
  36491. if ( line.indexOf( "/" ) === - 1 ) {
  36492. lineVertices = lineParts;
  36493. } else {
  36494. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  36495. var parts = lineParts[ li ].split( "/" );
  36496. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  36497. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  36498. }
  36499. }
  36500. state.addLineGeometry( lineVertices, lineUVs );
  36501. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  36502. // o object_name
  36503. // or
  36504. // g group_name
  36505. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  36506. // var name = result[ 0 ].substr( 1 ).trim();
  36507. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  36508. state.startObject( name );
  36509. } else if ( material_use_pattern.test( line ) ) {
  36510. // material
  36511. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  36512. } else if ( material_library_pattern.test( line ) ) {
  36513. // mtl file
  36514. state.materialLibraries.push( line.substring( 7 ).trim() );
  36515. } else if ( lineFirstChar === 's' ) {
  36516. result = line.split( ' ' );
  36517. // smooth shading
  36518. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  36519. // but does not define a usemtl for each face set.
  36520. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  36521. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  36522. // where explicit usemtl defines geometry groups.
  36523. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  36524. /*
  36525. * http://paulbourke.net/dataformats/obj/
  36526. * or
  36527. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  36528. *
  36529. * From chapter "Grouping" Syntax explanation "s group_number":
  36530. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  36531. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  36532. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  36533. * than 0."
  36534. */
  36535. if ( result.length > 1 ) {
  36536. var value = result[ 1 ].trim().toLowerCase();
  36537. state.object.smooth = ( value !== '0' && value !== 'off' );
  36538. } else {
  36539. // ZBrush can produce "s" lines #11707
  36540. state.object.smooth = true;
  36541. }
  36542. var material = state.object.currentMaterial();
  36543. if ( material ) material.smooth = state.object.smooth;
  36544. } else {
  36545. // Handle null terminated files without exception
  36546. if ( line === '\0' ) continue;
  36547. throw new Error( "Unexpected line: '" + line + "'" );
  36548. }
  36549. }
  36550. state.finalize();
  36551. var container = new THREE.Group();
  36552. container.materialLibraries = [].concat( state.materialLibraries );
  36553. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  36554. var object = state.objects[ i ];
  36555. var geometry = object.geometry;
  36556. var materials = object.materials;
  36557. var isLine = ( geometry.type === 'Line' );
  36558. // Skip o/g line declarations that did not follow with any faces
  36559. if ( geometry.vertices.length === 0 ) continue;
  36560. var buffergeometry = new THREE.BufferGeometry();
  36561. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  36562. if ( geometry.normals.length > 0 ) {
  36563. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  36564. } else {
  36565. buffergeometry.computeVertexNormals();
  36566. }
  36567. if ( geometry.uvs.length > 0 ) {
  36568. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  36569. }
  36570. // Create materials
  36571. var createdMaterials = [];
  36572. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  36573. var sourceMaterial = materials[ mi ];
  36574. var material = undefined;
  36575. if ( this.materials !== null ) {
  36576. material = this.materials.create( sourceMaterial.name );
  36577. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  36578. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  36579. var materialLine = new THREE.LineBasicMaterial();
  36580. materialLine.copy( material );
  36581. material = materialLine;
  36582. }
  36583. }
  36584. if ( ! material ) {
  36585. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  36586. material.name = sourceMaterial.name;
  36587. }
  36588. material.flatShading = sourceMaterial.smooth ? false : true;
  36589. createdMaterials.push(material);
  36590. }
  36591. // Create mesh
  36592. var mesh;
  36593. if ( createdMaterials.length > 1 ) {
  36594. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  36595. var sourceMaterial = materials[ mi ];
  36596. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  36597. }
  36598. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials ) : new THREE.LineSegments( buffergeometry, createdMaterials ) );
  36599. } else {
  36600. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  36601. }
  36602. mesh.name = object.name;
  36603. container.add( mesh );
  36604. }
  36605. console.timeEnd( 'OBJLoader' );
  36606. return container;
  36607. }
  36608. };
  36609. return OBJLoader;
  36610. } )();
  36611. },{}],46:[function(_dereq_,module,exports){
  36612. exports = module.exports = trim;
  36613. function trim(str){
  36614. return str.replace(/^\s*|\s*$/g, '');
  36615. }
  36616. exports.left = function(str){
  36617. return str.replace(/^\s*/, '');
  36618. };
  36619. exports.right = function(str){
  36620. return str.replace(/\s*$/, '');
  36621. };
  36622. },{}],47:[function(_dereq_,module,exports){
  36623. module.exports={
  36624. "_args": [
  36625. [
  36626. {
  36627. "raw": "webvr-polyfill@^0.9.40",
  36628. "scope": null,
  36629. "escapedName": "webvr-polyfill",
  36630. "name": "webvr-polyfill",
  36631. "rawSpec": "^0.9.40",
  36632. "spec": ">=0.9.40 <0.10.0",
  36633. "type": "range"
  36634. },
  36635. "/home/ubuntu/a-frobot/aframe"
  36636. ]
  36637. ],
  36638. "_from": "webvr-polyfill@>=0.9.40 <0.10.0",
  36639. "_id": "webvr-polyfill@0.9.40",
  36640. "_inCache": true,
  36641. "_location": "/webvr-polyfill",
  36642. "_nodeVersion": "8.6.0",
  36643. "_npmOperationalInternal": {
  36644. "host": "s3://npm-registry-packages",
  36645. "tmp": "tmp/webvr-polyfill-0.9.40.tgz_1507657755590_0.00047161197289824486"
  36646. },
  36647. "_npmUser": {
  36648. "name": "jsantell",
  36649. "email": "jsantell@gmail.com"
  36650. },
  36651. "_npmVersion": "5.3.0",
  36652. "_phantomChildren": {},
  36653. "_requested": {
  36654. "raw": "webvr-polyfill@^0.9.40",
  36655. "scope": null,
  36656. "escapedName": "webvr-polyfill",
  36657. "name": "webvr-polyfill",
  36658. "rawSpec": "^0.9.40",
  36659. "spec": ">=0.9.40 <0.10.0",
  36660. "type": "range"
  36661. },
  36662. "_requiredBy": [
  36663. "/"
  36664. ],
  36665. "_resolved": "https://registry.npmjs.org/webvr-polyfill/-/webvr-polyfill-0.9.40.tgz",
  36666. "_shasum": "2cfa0ec0e0cc6ba7238c73a09cba4952fff59a63",
  36667. "_shrinkwrap": null,
  36668. "_spec": "webvr-polyfill@^0.9.40",
  36669. "_where": "/home/ubuntu/a-frobot/aframe",
  36670. "authors": [
  36671. "Boris Smus <boris@smus.com>",
  36672. "Brandon Jones <tojiro@gmail.com>",
  36673. "Jordan Santell <jordan@jsantell.com>"
  36674. ],
  36675. "bugs": {
  36676. "url": "https://github.com/googlevr/webvr-polyfill/issues"
  36677. },
  36678. "dependencies": {},
  36679. "description": "Use WebVR today, on mobile or desktop, without requiring a special browser build.",
  36680. "devDependencies": {
  36681. "chai": "^3.5.0",
  36682. "jsdom": "^9.12.0",
  36683. "mocha": "^3.2.0",
  36684. "semver": "^5.3.0",
  36685. "webpack": "^2.6.1",
  36686. "webpack-dev-server": "2.7.1"
  36687. },
  36688. "directories": {},
  36689. "dist": {
  36690. "integrity": "sha512-m7jhJHjFcUYPyPSNeGmly7a2h/cP7bARz0OZMoUn5SueVXEKeZ4P7bzbAUDBDvvqCsa5gHgM3PFIhYe13bqaWw==",
  36691. "shasum": "2cfa0ec0e0cc6ba7238c73a09cba4952fff59a63",
  36692. "tarball": "https://registry.npmjs.org/webvr-polyfill/-/webvr-polyfill-0.9.40.tgz"
  36693. },
  36694. "gitHead": "45828ffdb8c3e0f9bb90296d6039d3cc7909ba8e",
  36695. "homepage": "https://github.com/googlevr/webvr-polyfill",
  36696. "keywords": [
  36697. "vr",
  36698. "webvr"
  36699. ],
  36700. "license": "Apache-2.0",
  36701. "main": "src/node-entry",
  36702. "maintainers": [
  36703. {
  36704. "name": "jsantell",
  36705. "email": "jsantell@gmail.com"
  36706. },
  36707. {
  36708. "name": "toji",
  36709. "email": "tojiro@gmail.com"
  36710. },
  36711. {
  36712. "name": "smus",
  36713. "email": "boris@smus.com"
  36714. }
  36715. ],
  36716. "name": "webvr-polyfill",
  36717. "optionalDependencies": {},
  36718. "readme": "ERROR: No README data found!",
  36719. "repository": {
  36720. "type": "git",
  36721. "url": "git+https://github.com/googlevr/webvr-polyfill.git"
  36722. },
  36723. "scripts": {
  36724. "build": "webpack",
  36725. "start": "npm run watch",
  36726. "test": "mocha",
  36727. "watch": "webpack-dev-server"
  36728. },
  36729. "version": "0.9.40"
  36730. }
  36731. },{}],48:[function(_dereq_,module,exports){
  36732. /*
  36733. * Copyright 2015 Google Inc. All Rights Reserved.
  36734. * Licensed under the Apache License, Version 2.0 (the "License");
  36735. * you may not use this file except in compliance with the License.
  36736. * You may obtain a copy of the License at
  36737. *
  36738. * http://www.apache.org/licenses/LICENSE-2.0
  36739. *
  36740. * Unless required by applicable law or agreed to in writing, software
  36741. * distributed under the License is distributed on an "AS IS" BASIS,
  36742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36743. * See the License for the specific language governing permissions and
  36744. * limitations under the License.
  36745. */
  36746. var Util = _dereq_('./util.js');
  36747. var WakeLock = _dereq_('./wakelock.js');
  36748. // Start at a higher number to reduce chance of conflict.
  36749. var nextDisplayId = 1000;
  36750. var hasShowDeprecationWarning = false;
  36751. var defaultLeftBounds = [0, 0, 0.5, 1];
  36752. var defaultRightBounds = [0.5, 0, 0.5, 1];
  36753. /**
  36754. * The base class for all VR frame data.
  36755. */
  36756. function VRFrameData() {
  36757. this.leftProjectionMatrix = new Float32Array(16);
  36758. this.leftViewMatrix = new Float32Array(16);
  36759. this.rightProjectionMatrix = new Float32Array(16);
  36760. this.rightViewMatrix = new Float32Array(16);
  36761. this.pose = null;
  36762. };
  36763. /**
  36764. * The base class for all VR displays.
  36765. */
  36766. function VRDisplay() {
  36767. this.isPolyfilled = true;
  36768. this.displayId = nextDisplayId++;
  36769. this.displayName = 'webvr-polyfill displayName';
  36770. this.depthNear = 0.01;
  36771. this.depthFar = 10000.0;
  36772. this.isConnected = true;
  36773. this.isPresenting = false;
  36774. this.capabilities = {
  36775. hasPosition: false,
  36776. hasOrientation: false,
  36777. hasExternalDisplay: false,
  36778. canPresent: false,
  36779. maxLayers: 1
  36780. };
  36781. this.stageParameters = null;
  36782. // "Private" members.
  36783. this.waitingForPresent_ = false;
  36784. this.layer_ = null;
  36785. this.fullscreenElement_ = null;
  36786. this.fullscreenWrapper_ = null;
  36787. this.fullscreenElementCachedStyle_ = null;
  36788. this.fullscreenEventTarget_ = null;
  36789. this.fullscreenChangeHandler_ = null;
  36790. this.fullscreenErrorHandler_ = null;
  36791. this.wakelock_ = new WakeLock();
  36792. }
  36793. VRDisplay.prototype.getFrameData = function(frameData) {
  36794. // TODO: Technically this should retain it's value for the duration of a frame
  36795. // but I doubt that's practical to do in javascript.
  36796. return Util.frameDataFromPose(frameData, this.getPose(), this);
  36797. };
  36798. VRDisplay.prototype.getPose = function() {
  36799. // TODO: Technically this should retain it's value for the duration of a frame
  36800. // but I doubt that's practical to do in javascript.
  36801. return this.getImmediatePose();
  36802. };
  36803. VRDisplay.prototype.requestAnimationFrame = function(callback) {
  36804. return window.requestAnimationFrame(callback);
  36805. };
  36806. VRDisplay.prototype.cancelAnimationFrame = function(id) {
  36807. return window.cancelAnimationFrame(id);
  36808. };
  36809. VRDisplay.prototype.wrapForFullscreen = function(element) {
  36810. // Don't wrap in iOS.
  36811. if (Util.isIOS()) {
  36812. return element;
  36813. }
  36814. if (!this.fullscreenWrapper_) {
  36815. this.fullscreenWrapper_ = document.createElement('div');
  36816. var cssProperties = [
  36817. 'height: ' + Math.min(screen.height, screen.width) + 'px !important',
  36818. 'top: 0 !important',
  36819. 'left: 0 !important',
  36820. 'right: 0 !important',
  36821. 'border: 0',
  36822. 'margin: 0',
  36823. 'padding: 0',
  36824. 'z-index: 999999 !important',
  36825. 'position: fixed',
  36826. ];
  36827. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  36828. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  36829. }
  36830. if (this.fullscreenElement_ == element) {
  36831. return this.fullscreenWrapper_;
  36832. }
  36833. // Remove any previously applied wrappers
  36834. this.removeFullscreenWrapper();
  36835. this.fullscreenElement_ = element;
  36836. var parent = this.fullscreenElement_.parentElement;
  36837. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  36838. parent.removeChild(this.fullscreenElement_);
  36839. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  36840. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  36841. var self = this;
  36842. function applyFullscreenElementStyle() {
  36843. if (!self.fullscreenElement_) {
  36844. return;
  36845. }
  36846. var cssProperties = [
  36847. 'position: absolute',
  36848. 'top: 0',
  36849. 'left: 0',
  36850. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  36851. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  36852. 'border: 0',
  36853. 'margin: 0',
  36854. 'padding: 0',
  36855. ];
  36856. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  36857. }
  36858. applyFullscreenElementStyle();
  36859. return this.fullscreenWrapper_;
  36860. };
  36861. VRDisplay.prototype.removeFullscreenWrapper = function() {
  36862. if (!this.fullscreenElement_) {
  36863. return;
  36864. }
  36865. var element = this.fullscreenElement_;
  36866. if (this.fullscreenElementCachedStyle_) {
  36867. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  36868. } else {
  36869. element.removeAttribute('style');
  36870. }
  36871. this.fullscreenElement_ = null;
  36872. this.fullscreenElementCachedStyle_ = null;
  36873. var parent = this.fullscreenWrapper_.parentElement;
  36874. this.fullscreenWrapper_.removeChild(element);
  36875. parent.insertBefore(element, this.fullscreenWrapper_);
  36876. parent.removeChild(this.fullscreenWrapper_);
  36877. return element;
  36878. };
  36879. VRDisplay.prototype.requestPresent = function(layers) {
  36880. var wasPresenting = this.isPresenting;
  36881. var self = this;
  36882. if (!(layers instanceof Array)) {
  36883. if (!hasShowDeprecationWarning) {
  36884. console.warn("Using a deprecated form of requestPresent. Should pass in an array of VRLayers.");
  36885. hasShowDeprecationWarning = true;
  36886. }
  36887. layers = [layers];
  36888. }
  36889. return new Promise(function(resolve, reject) {
  36890. if (!self.capabilities.canPresent) {
  36891. reject(new Error('VRDisplay is not capable of presenting.'));
  36892. return;
  36893. }
  36894. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  36895. reject(new Error('Invalid number of layers.'));
  36896. return;
  36897. }
  36898. var incomingLayer = layers[0];
  36899. if (!incomingLayer.source) {
  36900. /*
  36901. todo: figure out the correct behavior if the source is not provided.
  36902. see https://github.com/w3c/webvr/issues/58
  36903. */
  36904. resolve();
  36905. return;
  36906. }
  36907. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  36908. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  36909. if (wasPresenting) {
  36910. // Already presenting, just changing configuration
  36911. var layer = self.layer_;
  36912. if (layer.source !== incomingLayer.source) {
  36913. layer.source = incomingLayer.source;
  36914. }
  36915. for (var i = 0; i < 4; i++) {
  36916. layer.leftBounds[i] = leftBounds[i];
  36917. layer.rightBounds[i] = rightBounds[i];
  36918. }
  36919. resolve();
  36920. return;
  36921. }
  36922. // Was not already presenting.
  36923. self.layer_ = {
  36924. predistorted: incomingLayer.predistorted,
  36925. source: incomingLayer.source,
  36926. leftBounds: leftBounds.slice(0),
  36927. rightBounds: rightBounds.slice(0)
  36928. };
  36929. self.waitingForPresent_ = false;
  36930. if (self.layer_ && self.layer_.source) {
  36931. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  36932. var onFullscreenChange = function() {
  36933. var actualFullscreenElement = Util.getFullscreenElement();
  36934. self.isPresenting = (fullscreenElement === actualFullscreenElement);
  36935. if (self.isPresenting) {
  36936. if (screen.orientation && screen.orientation.lock) {
  36937. screen.orientation.lock('landscape-primary').catch(function(error){
  36938. console.error('screen.orientation.lock() failed due to', error.message)
  36939. });
  36940. }
  36941. self.waitingForPresent_ = false;
  36942. self.beginPresent_();
  36943. resolve();
  36944. } else {
  36945. if (screen.orientation && screen.orientation.unlock) {
  36946. screen.orientation.unlock();
  36947. }
  36948. self.removeFullscreenWrapper();
  36949. self.wakelock_.release();
  36950. self.endPresent_();
  36951. self.removeFullscreenListeners_();
  36952. }
  36953. self.fireVRDisplayPresentChange_();
  36954. }
  36955. var onFullscreenError = function() {
  36956. if (!self.waitingForPresent_) {
  36957. return;
  36958. }
  36959. self.removeFullscreenWrapper();
  36960. self.removeFullscreenListeners_();
  36961. self.wakelock_.release();
  36962. self.waitingForPresent_ = false;
  36963. self.isPresenting = false;
  36964. reject(new Error('Unable to present.'));
  36965. }
  36966. self.addFullscreenListeners_(fullscreenElement,
  36967. onFullscreenChange, onFullscreenError);
  36968. if (Util.requestFullscreen(fullscreenElement)) {
  36969. self.wakelock_.request();
  36970. self.waitingForPresent_ = true;
  36971. } else if (Util.isIOS() || Util.isWebViewAndroid()) {
  36972. // *sigh* Just fake it.
  36973. self.wakelock_.request();
  36974. self.isPresenting = true;
  36975. self.beginPresent_();
  36976. self.fireVRDisplayPresentChange_();
  36977. resolve();
  36978. }
  36979. }
  36980. if (!self.waitingForPresent_ && !Util.isIOS()) {
  36981. Util.exitFullscreen();
  36982. reject(new Error('Unable to present.'));
  36983. }
  36984. });
  36985. };
  36986. VRDisplay.prototype.exitPresent = function() {
  36987. var wasPresenting = this.isPresenting;
  36988. var self = this;
  36989. this.isPresenting = false;
  36990. this.layer_ = null;
  36991. this.wakelock_.release();
  36992. return new Promise(function(resolve, reject) {
  36993. if (wasPresenting) {
  36994. if (!Util.exitFullscreen() && Util.isIOS()) {
  36995. self.endPresent_();
  36996. self.fireVRDisplayPresentChange_();
  36997. }
  36998. if (Util.isWebViewAndroid()) {
  36999. self.removeFullscreenWrapper();
  37000. self.removeFullscreenListeners_();
  37001. self.endPresent_();
  37002. self.fireVRDisplayPresentChange_();
  37003. }
  37004. resolve();
  37005. } else {
  37006. reject(new Error('Was not presenting to VRDisplay.'));
  37007. }
  37008. });
  37009. };
  37010. VRDisplay.prototype.getLayers = function() {
  37011. if (this.layer_) {
  37012. return [this.layer_];
  37013. }
  37014. return [];
  37015. };
  37016. VRDisplay.prototype.fireVRDisplayPresentChange_ = function() {
  37017. // Important: unfortunately we cannot have full spec compliance here.
  37018. // CustomEvent custom fields all go under e.detail (so the VRDisplay ends up
  37019. // being e.detail.display, instead of e.display as per WebVR spec).
  37020. var event = new CustomEvent('vrdisplaypresentchange', {detail: {display: this}});
  37021. window.dispatchEvent(event);
  37022. };
  37023. VRDisplay.prototype.fireVRDisplayConnect_ = function() {
  37024. // Important: unfortunately we cannot have full spec compliance here.
  37025. // CustomEvent custom fields all go under e.detail (so the VRDisplay ends up
  37026. // being e.detail.display, instead of e.display as per WebVR spec).
  37027. var event = new CustomEvent('vrdisplayconnect', {detail: {display: this}});
  37028. window.dispatchEvent(event);
  37029. };
  37030. VRDisplay.prototype.addFullscreenListeners_ = function(element, changeHandler, errorHandler) {
  37031. this.removeFullscreenListeners_();
  37032. this.fullscreenEventTarget_ = element;
  37033. this.fullscreenChangeHandler_ = changeHandler;
  37034. this.fullscreenErrorHandler_ = errorHandler;
  37035. if (changeHandler) {
  37036. if (document.fullscreenEnabled) {
  37037. element.addEventListener('fullscreenchange', changeHandler, false);
  37038. } else if (document.webkitFullscreenEnabled) {
  37039. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  37040. } else if (document.mozFullScreenEnabled) {
  37041. document.addEventListener('mozfullscreenchange', changeHandler, false);
  37042. } else if (document.msFullscreenEnabled) {
  37043. element.addEventListener('msfullscreenchange', changeHandler, false);
  37044. }
  37045. }
  37046. if (errorHandler) {
  37047. if (document.fullscreenEnabled) {
  37048. element.addEventListener('fullscreenerror', errorHandler, false);
  37049. } else if (document.webkitFullscreenEnabled) {
  37050. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  37051. } else if (document.mozFullScreenEnabled) {
  37052. document.addEventListener('mozfullscreenerror', errorHandler, false);
  37053. } else if (document.msFullscreenEnabled) {
  37054. element.addEventListener('msfullscreenerror', errorHandler, false);
  37055. }
  37056. }
  37057. };
  37058. VRDisplay.prototype.removeFullscreenListeners_ = function() {
  37059. if (!this.fullscreenEventTarget_)
  37060. return;
  37061. var element = this.fullscreenEventTarget_;
  37062. if (this.fullscreenChangeHandler_) {
  37063. var changeHandler = this.fullscreenChangeHandler_;
  37064. element.removeEventListener('fullscreenchange', changeHandler, false);
  37065. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  37066. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  37067. element.removeEventListener('msfullscreenchange', changeHandler, false);
  37068. }
  37069. if (this.fullscreenErrorHandler_) {
  37070. var errorHandler = this.fullscreenErrorHandler_;
  37071. element.removeEventListener('fullscreenerror', errorHandler, false);
  37072. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  37073. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  37074. element.removeEventListener('msfullscreenerror', errorHandler, false);
  37075. }
  37076. this.fullscreenEventTarget_ = null;
  37077. this.fullscreenChangeHandler_ = null;
  37078. this.fullscreenErrorHandler_ = null;
  37079. };
  37080. VRDisplay.prototype.beginPresent_ = function() {
  37081. // Override to add custom behavior when presentation begins.
  37082. };
  37083. VRDisplay.prototype.endPresent_ = function() {
  37084. // Override to add custom behavior when presentation ends.
  37085. };
  37086. VRDisplay.prototype.submitFrame = function(pose) {
  37087. // Override to add custom behavior for frame submission.
  37088. };
  37089. VRDisplay.prototype.getEyeParameters = function(whichEye) {
  37090. // Override to return accurate eye parameters if canPresent is true.
  37091. return null;
  37092. };
  37093. /*
  37094. * Deprecated classes
  37095. */
  37096. /**
  37097. * The base class for all VR devices. (Deprecated)
  37098. */
  37099. function VRDevice() {
  37100. this.isPolyfilled = true;
  37101. this.hardwareUnitId = 'webvr-polyfill hardwareUnitId';
  37102. this.deviceId = 'webvr-polyfill deviceId';
  37103. this.deviceName = 'webvr-polyfill deviceName';
  37104. }
  37105. /**
  37106. * The base class for all VR HMD devices. (Deprecated)
  37107. */
  37108. function HMDVRDevice() {
  37109. }
  37110. HMDVRDevice.prototype = new VRDevice();
  37111. /**
  37112. * The base class for all VR position sensor devices. (Deprecated)
  37113. */
  37114. function PositionSensorVRDevice() {
  37115. }
  37116. PositionSensorVRDevice.prototype = new VRDevice();
  37117. module.exports.VRFrameData = VRFrameData;
  37118. module.exports.VRDisplay = VRDisplay;
  37119. module.exports.VRDevice = VRDevice;
  37120. module.exports.HMDVRDevice = HMDVRDevice;
  37121. module.exports.PositionSensorVRDevice = PositionSensorVRDevice;
  37122. },{"./util.js":68,"./wakelock.js":70}],49:[function(_dereq_,module,exports){
  37123. /*
  37124. * Copyright 2016 Google Inc. All Rights Reserved.
  37125. * Licensed under the Apache License, Version 2.0 (the "License");
  37126. * you may not use this file except in compliance with the License.
  37127. * You may obtain a copy of the License at
  37128. *
  37129. * http://www.apache.org/licenses/LICENSE-2.0
  37130. *
  37131. * Unless required by applicable law or agreed to in writing, software
  37132. * distributed under the License is distributed on an "AS IS" BASIS,
  37133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37134. * See the License for the specific language governing permissions and
  37135. * limitations under the License.
  37136. */
  37137. var CardboardUI = _dereq_('./cardboard-ui.js');
  37138. var Util = _dereq_('./util.js');
  37139. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37140. var distortionVS = [
  37141. 'attribute vec2 position;',
  37142. 'attribute vec3 texCoord;',
  37143. 'varying vec2 vTexCoord;',
  37144. 'uniform vec4 viewportOffsetScale[2];',
  37145. 'void main() {',
  37146. ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];',
  37147. ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;',
  37148. ' gl_Position = vec4( position, 1.0, 1.0 );',
  37149. '}',
  37150. ].join('\n');
  37151. var distortionFS = [
  37152. 'precision mediump float;',
  37153. 'uniform sampler2D diffuse;',
  37154. 'varying vec2 vTexCoord;',
  37155. 'void main() {',
  37156. ' gl_FragColor = texture2D(diffuse, vTexCoord);',
  37157. '}',
  37158. ].join('\n');
  37159. /**
  37160. * A mesh-based distorter.
  37161. */
  37162. function CardboardDistorter(gl) {
  37163. this.gl = gl;
  37164. this.ctxAttribs = gl.getContextAttributes();
  37165. this.meshWidth = 20;
  37166. this.meshHeight = 20;
  37167. this.bufferScale = window.WebVRConfig.BUFFER_SCALE;
  37168. this.bufferWidth = gl.drawingBufferWidth;
  37169. this.bufferHeight = gl.drawingBufferHeight;
  37170. // Patching support
  37171. this.realBindFramebuffer = gl.bindFramebuffer;
  37172. this.realEnable = gl.enable;
  37173. this.realDisable = gl.disable;
  37174. this.realColorMask = gl.colorMask;
  37175. this.realClearColor = gl.clearColor;
  37176. this.realViewport = gl.viewport;
  37177. if (!Util.isIOS()) {
  37178. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  37179. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  37180. }
  37181. this.isPatched = false;
  37182. // State tracking
  37183. this.lastBoundFramebuffer = null;
  37184. this.cullFace = false;
  37185. this.depthTest = false;
  37186. this.blend = false;
  37187. this.scissorTest = false;
  37188. this.stencilTest = false;
  37189. this.viewport = [0, 0, 0, 0];
  37190. this.colorMask = [true, true, true, true];
  37191. this.clearColor = [0, 0, 0, 0];
  37192. this.attribs = {
  37193. position: 0,
  37194. texCoord: 1
  37195. };
  37196. this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs);
  37197. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37198. this.viewportOffsetScale = new Float32Array(8);
  37199. this.setTextureBounds();
  37200. this.vertexBuffer = gl.createBuffer();
  37201. this.indexBuffer = gl.createBuffer();
  37202. this.indexCount = 0;
  37203. this.renderTarget = gl.createTexture();
  37204. this.framebuffer = gl.createFramebuffer();
  37205. this.depthStencilBuffer = null;
  37206. this.depthBuffer = null;
  37207. this.stencilBuffer = null;
  37208. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  37209. this.depthStencilBuffer = gl.createRenderbuffer();
  37210. } else if (this.ctxAttribs.depth) {
  37211. this.depthBuffer = gl.createRenderbuffer();
  37212. } else if (this.ctxAttribs.stencil) {
  37213. this.stencilBuffer = gl.createRenderbuffer();
  37214. }
  37215. this.patch();
  37216. this.onResize();
  37217. if (!window.WebVRConfig.CARDBOARD_UI_DISABLED) {
  37218. this.cardboardUI = new CardboardUI(gl);
  37219. }
  37220. };
  37221. /**
  37222. * Tears down all the resources created by the distorter and removes any
  37223. * patches.
  37224. */
  37225. CardboardDistorter.prototype.destroy = function() {
  37226. var gl = this.gl;
  37227. this.unpatch();
  37228. gl.deleteProgram(this.program);
  37229. gl.deleteBuffer(this.vertexBuffer);
  37230. gl.deleteBuffer(this.indexBuffer);
  37231. gl.deleteTexture(this.renderTarget);
  37232. gl.deleteFramebuffer(this.framebuffer);
  37233. if (this.depthStencilBuffer) {
  37234. gl.deleteRenderbuffer(this.depthStencilBuffer);
  37235. }
  37236. if (this.depthBuffer) {
  37237. gl.deleteRenderbuffer(this.depthBuffer);
  37238. }
  37239. if (this.stencilBuffer) {
  37240. gl.deleteRenderbuffer(this.stencilBuffer);
  37241. }
  37242. if (this.cardboardUI) {
  37243. this.cardboardUI.destroy();
  37244. }
  37245. };
  37246. /**
  37247. * Resizes the backbuffer to match the canvas width and height.
  37248. */
  37249. CardboardDistorter.prototype.onResize = function() {
  37250. var gl = this.gl;
  37251. var self = this;
  37252. var glState = [
  37253. gl.RENDERBUFFER_BINDING,
  37254. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37255. ];
  37256. WGLUPreserveGLState(gl, glState, function(gl) {
  37257. // Bind real backbuffer and clear it once. We don't need to clear it again
  37258. // after that because we're overwriting the same area every frame.
  37259. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37260. // Put things in a good state
  37261. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37262. self.realColorMask.call(gl, true, true, true, true);
  37263. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37264. self.realClearColor.call(gl, 0, 0, 0, 1);
  37265. gl.clear(gl.COLOR_BUFFER_BIT);
  37266. // Now bind and resize the fake backbuffer
  37267. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  37268. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37269. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB,
  37270. self.bufferWidth, self.bufferHeight, 0,
  37271. self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  37272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  37273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  37274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  37275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  37276. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  37277. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  37278. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  37279. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL,
  37280. self.bufferWidth, self.bufferHeight);
  37281. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT,
  37282. gl.RENDERBUFFER, self.depthStencilBuffer);
  37283. } else if (self.ctxAttribs.depth) {
  37284. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  37285. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
  37286. self.bufferWidth, self.bufferHeight);
  37287. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
  37288. gl.RENDERBUFFER, self.depthBuffer);
  37289. } else if (self.ctxAttribs.stencil) {
  37290. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  37291. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8,
  37292. self.bufferWidth, self.bufferHeight);
  37293. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT,
  37294. gl.RENDERBUFFER, self.stencilBuffer);
  37295. }
  37296. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  37297. console.error('Framebuffer incomplete!');
  37298. }
  37299. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37300. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37301. self.realColorMask.apply(gl, self.colorMask);
  37302. self.realViewport.apply(gl, self.viewport);
  37303. self.realClearColor.apply(gl, self.clearColor);
  37304. });
  37305. if (this.cardboardUI) {
  37306. this.cardboardUI.onResize();
  37307. }
  37308. };
  37309. CardboardDistorter.prototype.patch = function() {
  37310. if (this.isPatched) {
  37311. return;
  37312. }
  37313. var self = this;
  37314. var canvas = this.gl.canvas;
  37315. var gl = this.gl;
  37316. if (!Util.isIOS()) {
  37317. canvas.width = Util.getScreenWidth() * this.bufferScale;
  37318. canvas.height = Util.getScreenHeight() * this.bufferScale;
  37319. Object.defineProperty(canvas, 'width', {
  37320. configurable: true,
  37321. enumerable: true,
  37322. get: function() {
  37323. return self.bufferWidth;
  37324. },
  37325. set: function(value) {
  37326. self.bufferWidth = value;
  37327. self.realCanvasWidth.set.call(canvas, value);
  37328. self.onResize();
  37329. }
  37330. });
  37331. Object.defineProperty(canvas, 'height', {
  37332. configurable: true,
  37333. enumerable: true,
  37334. get: function() {
  37335. return self.bufferHeight;
  37336. },
  37337. set: function(value) {
  37338. self.bufferHeight = value;
  37339. self.realCanvasHeight.set.call(canvas, value);
  37340. self.onResize();
  37341. }
  37342. });
  37343. }
  37344. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  37345. if (this.lastBoundFramebuffer == null) {
  37346. this.lastBoundFramebuffer = this.framebuffer;
  37347. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  37348. }
  37349. this.gl.bindFramebuffer = function(target, framebuffer) {
  37350. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  37351. // Silently make calls to bind the default framebuffer bind ours instead.
  37352. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  37353. };
  37354. this.cullFace = gl.getParameter(gl.CULL_FACE);
  37355. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  37356. this.blend = gl.getParameter(gl.BLEND);
  37357. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  37358. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  37359. gl.enable = function(pname) {
  37360. switch (pname) {
  37361. case gl.CULL_FACE: self.cullFace = true; break;
  37362. case gl.DEPTH_TEST: self.depthTest = true; break;
  37363. case gl.BLEND: self.blend = true; break;
  37364. case gl.SCISSOR_TEST: self.scissorTest = true; break;
  37365. case gl.STENCIL_TEST: self.stencilTest = true; break;
  37366. }
  37367. self.realEnable.call(gl, pname);
  37368. };
  37369. gl.disable = function(pname) {
  37370. switch (pname) {
  37371. case gl.CULL_FACE: self.cullFace = false; break;
  37372. case gl.DEPTH_TEST: self.depthTest = false; break;
  37373. case gl.BLEND: self.blend = false; break;
  37374. case gl.SCISSOR_TEST: self.scissorTest = false; break;
  37375. case gl.STENCIL_TEST: self.stencilTest = false; break;
  37376. }
  37377. self.realDisable.call(gl, pname);
  37378. };
  37379. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  37380. gl.colorMask = function(r, g, b, a) {
  37381. self.colorMask[0] = r;
  37382. self.colorMask[1] = g;
  37383. self.colorMask[2] = b;
  37384. self.colorMask[3] = a;
  37385. self.realColorMask.call(gl, r, g, b, a);
  37386. };
  37387. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  37388. gl.clearColor = function(r, g, b, a) {
  37389. self.clearColor[0] = r;
  37390. self.clearColor[1] = g;
  37391. self.clearColor[2] = b;
  37392. self.clearColor[3] = a;
  37393. self.realClearColor.call(gl, r, g, b, a);
  37394. };
  37395. this.viewport = gl.getParameter(gl.VIEWPORT);
  37396. gl.viewport = function(x, y, w, h) {
  37397. self.viewport[0] = x;
  37398. self.viewport[1] = y;
  37399. self.viewport[2] = w;
  37400. self.viewport[3] = h;
  37401. self.realViewport.call(gl, x, y, w, h);
  37402. };
  37403. this.isPatched = true;
  37404. Util.safariCssSizeWorkaround(canvas);
  37405. };
  37406. CardboardDistorter.prototype.unpatch = function() {
  37407. if (!this.isPatched) {
  37408. return;
  37409. }
  37410. var gl = this.gl;
  37411. var canvas = this.gl.canvas;
  37412. if (!Util.isIOS()) {
  37413. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  37414. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  37415. }
  37416. canvas.width = this.bufferWidth;
  37417. canvas.height = this.bufferHeight;
  37418. gl.bindFramebuffer = this.realBindFramebuffer;
  37419. gl.enable = this.realEnable;
  37420. gl.disable = this.realDisable;
  37421. gl.colorMask = this.realColorMask;
  37422. gl.clearColor = this.realClearColor;
  37423. gl.viewport = this.realViewport;
  37424. // Check to see if our fake backbuffer is bound and bind the real backbuffer
  37425. // if that's the case.
  37426. if (this.lastBoundFramebuffer == this.framebuffer) {
  37427. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  37428. }
  37429. this.isPatched = false;
  37430. setTimeout(function() {
  37431. Util.safariCssSizeWorkaround(canvas);
  37432. }, 1);
  37433. };
  37434. CardboardDistorter.prototype.setTextureBounds = function(leftBounds, rightBounds) {
  37435. if (!leftBounds) {
  37436. leftBounds = [0, 0, 0.5, 1];
  37437. }
  37438. if (!rightBounds) {
  37439. rightBounds = [0.5, 0, 0.5, 1];
  37440. }
  37441. // Left eye
  37442. this.viewportOffsetScale[0] = leftBounds[0]; // X
  37443. this.viewportOffsetScale[1] = leftBounds[1]; // Y
  37444. this.viewportOffsetScale[2] = leftBounds[2]; // Width
  37445. this.viewportOffsetScale[3] = leftBounds[3]; // Height
  37446. // Right eye
  37447. this.viewportOffsetScale[4] = rightBounds[0]; // X
  37448. this.viewportOffsetScale[5] = rightBounds[1]; // Y
  37449. this.viewportOffsetScale[6] = rightBounds[2]; // Width
  37450. this.viewportOffsetScale[7] = rightBounds[3]; // Height
  37451. };
  37452. /**
  37453. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37454. * backbuffer.
  37455. */
  37456. CardboardDistorter.prototype.submitFrame = function() {
  37457. var gl = this.gl;
  37458. var self = this;
  37459. var glState = [];
  37460. if (!window.WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37461. glState.push(
  37462. gl.CURRENT_PROGRAM,
  37463. gl.ARRAY_BUFFER_BINDING,
  37464. gl.ELEMENT_ARRAY_BUFFER_BINDING,
  37465. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37466. );
  37467. }
  37468. WGLUPreserveGLState(gl, glState, function(gl) {
  37469. // Bind the real default framebuffer
  37470. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37471. // Make sure the GL state is in a good place
  37472. if (self.cullFace) { self.realDisable.call(gl, gl.CULL_FACE); }
  37473. if (self.depthTest) { self.realDisable.call(gl, gl.DEPTH_TEST); }
  37474. if (self.blend) { self.realDisable.call(gl, gl.BLEND); }
  37475. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37476. if (self.stencilTest) { self.realDisable.call(gl, gl.STENCIL_TEST); }
  37477. self.realColorMask.call(gl, true, true, true, true);
  37478. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37479. // If the backbuffer has an alpha channel clear every frame so the page
  37480. // doesn't show through.
  37481. if (self.ctxAttribs.alpha || Util.isIOS()) {
  37482. self.realClearColor.call(gl, 0, 0, 0, 1);
  37483. gl.clear(gl.COLOR_BUFFER_BIT);
  37484. }
  37485. // Bind distortion program and mesh
  37486. gl.useProgram(self.program);
  37487. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37488. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37489. gl.enableVertexAttribArray(self.attribs.position);
  37490. gl.enableVertexAttribArray(self.attribs.texCoord);
  37491. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  37492. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  37493. gl.activeTexture(gl.TEXTURE0);
  37494. gl.uniform1i(self.uniforms.diffuse, 0);
  37495. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37496. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  37497. // Draws both eyes
  37498. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  37499. if (self.cardboardUI) {
  37500. self.cardboardUI.renderNoState();
  37501. }
  37502. // Bind the fake default framebuffer again
  37503. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  37504. // If preserveDrawingBuffer == false clear the framebuffer
  37505. if (!self.ctxAttribs.preserveDrawingBuffer) {
  37506. self.realClearColor.call(gl, 0, 0, 0, 0);
  37507. gl.clear(gl.COLOR_BUFFER_BIT);
  37508. }
  37509. if (!window.WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37510. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37511. }
  37512. // Restore state
  37513. if (self.cullFace) { self.realEnable.call(gl, gl.CULL_FACE); }
  37514. if (self.depthTest) { self.realEnable.call(gl, gl.DEPTH_TEST); }
  37515. if (self.blend) { self.realEnable.call(gl, gl.BLEND); }
  37516. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37517. if (self.stencilTest) { self.realEnable.call(gl, gl.STENCIL_TEST); }
  37518. self.realColorMask.apply(gl, self.colorMask);
  37519. self.realViewport.apply(gl, self.viewport);
  37520. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  37521. self.realClearColor.apply(gl, self.clearColor);
  37522. }
  37523. });
  37524. // Workaround for the fact that Safari doesn't allow us to patch the canvas
  37525. // width and height correctly. After each submit frame check to see what the
  37526. // real backbuffer size has been set to and resize the fake backbuffer size
  37527. // to match.
  37528. if (Util.isIOS()) {
  37529. var canvas = gl.canvas;
  37530. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  37531. self.bufferWidth = canvas.width;
  37532. self.bufferHeight = canvas.height;
  37533. self.onResize();
  37534. }
  37535. }
  37536. };
  37537. /**
  37538. * Call when the deviceInfo has changed. At this point we need
  37539. * to re-calculate the distortion mesh.
  37540. */
  37541. CardboardDistorter.prototype.updateDeviceInfo = function(deviceInfo) {
  37542. var gl = this.gl;
  37543. var self = this;
  37544. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  37545. WGLUPreserveGLState(gl, glState, function(gl) {
  37546. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  37547. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37548. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  37549. // Indices don't change based on device parameters, so only compute once.
  37550. if (!self.indexCount) {
  37551. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  37552. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37553. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  37554. self.indexCount = indices.length;
  37555. }
  37556. });
  37557. };
  37558. /**
  37559. * Build the distortion mesh vertices.
  37560. * Based on code from the Unity cardboard plugin.
  37561. */
  37562. CardboardDistorter.prototype.computeMeshVertices_ = function(width, height, deviceInfo) {
  37563. var vertices = new Float32Array(2 * width * height * 5);
  37564. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  37565. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  37566. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  37567. var vidx = 0;
  37568. var iidx = 0;
  37569. for (var e = 0; e < 2; e++) {
  37570. for (var j = 0; j < height; j++) {
  37571. for (var i = 0; i < width; i++, vidx++) {
  37572. var u = i / (width - 1);
  37573. var v = j / (height - 1);
  37574. // Grid points regularly spaced in StreoScreen, and barrel distorted in
  37575. // the mesh.
  37576. var s = u;
  37577. var t = v;
  37578. var x = Util.lerp(lensFrustum[0], lensFrustum[2], u);
  37579. var y = Util.lerp(lensFrustum[3], lensFrustum[1], v);
  37580. var d = Math.sqrt(x * x + y * y);
  37581. var r = deviceInfo.distortion.distortInverse(d);
  37582. var p = x * r / d;
  37583. var q = y * r / d;
  37584. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  37585. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  37586. // Convert u,v to mesh screen coordinates.
  37587. var aspect = deviceInfo.device.widthMeters / deviceInfo.device.heightMeters;
  37588. // FIXME: The original Unity plugin multiplied U by the aspect ratio
  37589. // and didn't multiply either value by 2, but that seems to get it
  37590. // really close to correct looking for me. I hate this kind of "Don't
  37591. // know why it works" code though, and wold love a more logical
  37592. // explanation of what needs to happen here.
  37593. u = (viewport.x + u * viewport.width - 0.5) * 2.0; //* aspect;
  37594. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  37595. vertices[(vidx * 5) + 0] = u; // position.x
  37596. vertices[(vidx * 5) + 1] = v; // position.y
  37597. vertices[(vidx * 5) + 2] = s; // texCoord.x
  37598. vertices[(vidx * 5) + 3] = t; // texCoord.y
  37599. vertices[(vidx * 5) + 4] = e; // texCoord.z (viewport index)
  37600. }
  37601. }
  37602. var w = lensFrustum[2] - lensFrustum[0];
  37603. lensFrustum[0] = -(w + lensFrustum[0]);
  37604. lensFrustum[2] = w - lensFrustum[2];
  37605. w = noLensFrustum[2] - noLensFrustum[0];
  37606. noLensFrustum[0] = -(w + noLensFrustum[0]);
  37607. noLensFrustum[2] = w - noLensFrustum[2];
  37608. viewport.x = 1 - (viewport.x + viewport.width);
  37609. }
  37610. return vertices;
  37611. }
  37612. /**
  37613. * Build the distortion mesh indices.
  37614. * Based on code from the Unity cardboard plugin.
  37615. */
  37616. CardboardDistorter.prototype.computeMeshIndices_ = function(width, height) {
  37617. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  37618. var halfwidth = width / 2;
  37619. var halfheight = height / 2;
  37620. var vidx = 0;
  37621. var iidx = 0;
  37622. for (var e = 0; e < 2; e++) {
  37623. for (var j = 0; j < height; j++) {
  37624. for (var i = 0; i < width; i++, vidx++) {
  37625. if (i == 0 || j == 0)
  37626. continue;
  37627. // Build a quad. Lower right and upper left quadrants have quads with
  37628. // the triangle diagonal flipped to get the vignette to interpolate
  37629. // correctly.
  37630. if ((i <= halfwidth) == (j <= halfheight)) {
  37631. // Quad diagonal lower left to upper right.
  37632. indices[iidx++] = vidx;
  37633. indices[iidx++] = vidx - width - 1;
  37634. indices[iidx++] = vidx - width;
  37635. indices[iidx++] = vidx - width - 1;
  37636. indices[iidx++] = vidx;
  37637. indices[iidx++] = vidx - 1;
  37638. } else {
  37639. // Quad diagonal upper left to lower right.
  37640. indices[iidx++] = vidx - 1;
  37641. indices[iidx++] = vidx - width;
  37642. indices[iidx++] = vidx;
  37643. indices[iidx++] = vidx - width;
  37644. indices[iidx++] = vidx - 1;
  37645. indices[iidx++] = vidx - width - 1;
  37646. }
  37647. }
  37648. }
  37649. }
  37650. return indices;
  37651. };
  37652. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function(proto, attrName) {
  37653. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  37654. // In some cases (ahem... Safari), the descriptor returns undefined get and
  37655. // set fields. In this case, we need to create a synthetic property
  37656. // descriptor. This works around some of the issues in
  37657. // https://github.com/borismus/webvr-polyfill/issues/46
  37658. if (descriptor.get === undefined || descriptor.set === undefined) {
  37659. descriptor.configurable = true;
  37660. descriptor.enumerable = true;
  37661. descriptor.get = function() {
  37662. return this.getAttribute(attrName);
  37663. };
  37664. descriptor.set = function(val) {
  37665. this.setAttribute(attrName, val);
  37666. };
  37667. }
  37668. return descriptor;
  37669. };
  37670. module.exports = CardboardDistorter;
  37671. },{"./cardboard-ui.js":50,"./deps/wglu-preserve-state.js":52,"./util.js":68}],50:[function(_dereq_,module,exports){
  37672. /*
  37673. * Copyright 2016 Google Inc. All Rights Reserved.
  37674. * Licensed under the Apache License, Version 2.0 (the "License");
  37675. * you may not use this file except in compliance with the License.
  37676. * You may obtain a copy of the License at
  37677. *
  37678. * http://www.apache.org/licenses/LICENSE-2.0
  37679. *
  37680. * Unless required by applicable law or agreed to in writing, software
  37681. * distributed under the License is distributed on an "AS IS" BASIS,
  37682. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37683. * See the License for the specific language governing permissions and
  37684. * limitations under the License.
  37685. */
  37686. var Util = _dereq_('./util.js');
  37687. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37688. var uiVS = [
  37689. 'attribute vec2 position;',
  37690. 'uniform mat4 projectionMat;',
  37691. 'void main() {',
  37692. ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );',
  37693. '}',
  37694. ].join('\n');
  37695. var uiFS = [
  37696. 'precision mediump float;',
  37697. 'uniform vec4 color;',
  37698. 'void main() {',
  37699. ' gl_FragColor = color;',
  37700. '}',
  37701. ].join('\n');
  37702. var DEG2RAD = Math.PI/180.0;
  37703. // The gear has 6 identical sections, each spanning 60 degrees.
  37704. var kAnglePerGearSection = 60;
  37705. // Half-angle of the span of the outer rim.
  37706. var kOuterRimEndAngle = 12;
  37707. // Angle between the middle of the outer rim and the start of the inner rim.
  37708. var kInnerRimBeginAngle = 20;
  37709. // Distance from center to outer rim, normalized so that the entire model
  37710. // fits in a [-1, 1] x [-1, 1] square.
  37711. var kOuterRadius = 1;
  37712. // Distance from center to depressed rim, in model units.
  37713. var kMiddleRadius = 0.75;
  37714. // Radius of the inner hollow circle, in model units.
  37715. var kInnerRadius = 0.3125;
  37716. // Center line thickness in DP.
  37717. var kCenterLineThicknessDp = 4;
  37718. // Button width in DP.
  37719. var kButtonWidthDp = 28;
  37720. // Factor to scale the touch area that responds to the touch.
  37721. var kTouchSlopFactor = 1.5;
  37722. var Angles = [
  37723. 0, kOuterRimEndAngle, kInnerRimBeginAngle,
  37724. kAnglePerGearSection - kInnerRimBeginAngle,
  37725. kAnglePerGearSection - kOuterRimEndAngle
  37726. ];
  37727. /**
  37728. * Renders the alignment line and "options" gear. It is assumed that the canvas
  37729. * this is rendered into covers the entire screen (or close to it.)
  37730. */
  37731. function CardboardUI(gl) {
  37732. this.gl = gl;
  37733. this.attribs = {
  37734. position: 0
  37735. };
  37736. this.program = Util.linkProgram(gl, uiVS, uiFS, this.attribs);
  37737. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37738. this.vertexBuffer = gl.createBuffer();
  37739. this.gearOffset = 0;
  37740. this.gearVertexCount = 0;
  37741. this.arrowOffset = 0;
  37742. this.arrowVertexCount = 0;
  37743. this.projMat = new Float32Array(16);
  37744. this.listener = null;
  37745. this.onResize();
  37746. };
  37747. /**
  37748. * Tears down all the resources created by the UI renderer.
  37749. */
  37750. CardboardUI.prototype.destroy = function() {
  37751. var gl = this.gl;
  37752. if (this.listener) {
  37753. gl.canvas.removeEventListener('click', this.listener, false);
  37754. }
  37755. gl.deleteProgram(this.program);
  37756. gl.deleteBuffer(this.vertexBuffer);
  37757. };
  37758. /**
  37759. * Adds a listener to clicks on the gear and back icons
  37760. */
  37761. CardboardUI.prototype.listen = function(optionsCallback, backCallback) {
  37762. var canvas = this.gl.canvas;
  37763. this.listener = function(event) {
  37764. var midline = canvas.clientWidth / 2;
  37765. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  37766. // Check to see if the user clicked on (or around) the gear icon
  37767. if (event.clientX > midline - buttonSize &&
  37768. event.clientX < midline + buttonSize &&
  37769. event.clientY > canvas.clientHeight - buttonSize) {
  37770. optionsCallback(event);
  37771. }
  37772. // Check to see if the user clicked on (or around) the back icon
  37773. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  37774. backCallback(event);
  37775. }
  37776. };
  37777. canvas.addEventListener('click', this.listener, false);
  37778. };
  37779. /**
  37780. * Builds the UI mesh.
  37781. */
  37782. CardboardUI.prototype.onResize = function() {
  37783. var gl = this.gl;
  37784. var self = this;
  37785. var glState = [
  37786. gl.ARRAY_BUFFER_BINDING
  37787. ];
  37788. WGLUPreserveGLState(gl, glState, function(gl) {
  37789. var vertices = [];
  37790. var midline = gl.drawingBufferWidth / 2;
  37791. // The gl buffer size will likely be smaller than the physical pixel count.
  37792. // So we need to scale the dps down based on the actual buffer size vs physical pixel count.
  37793. // This will properly size the ui elements no matter what the gl buffer resolution is
  37794. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  37795. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  37796. var dps = scalingRatio * window.devicePixelRatio;
  37797. var lineWidth = kCenterLineThicknessDp * dps / 2;
  37798. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  37799. var buttonScale = kButtonWidthDp * dps / 2;
  37800. var buttonBorder = ((kButtonWidthDp * kTouchSlopFactor) - kButtonWidthDp) * dps;
  37801. // Build centerline
  37802. vertices.push(midline - lineWidth, buttonSize);
  37803. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  37804. vertices.push(midline + lineWidth, buttonSize);
  37805. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  37806. // Build gear
  37807. self.gearOffset = (vertices.length / 2);
  37808. function addGearSegment(theta, r) {
  37809. var angle = (90 - theta) * DEG2RAD;
  37810. var x = Math.cos(angle);
  37811. var y = Math.sin(angle);
  37812. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  37813. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  37814. }
  37815. for (var i = 0; i <= 6; i++) {
  37816. var segmentTheta = i * kAnglePerGearSection;
  37817. addGearSegment(segmentTheta, kOuterRadius);
  37818. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  37819. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  37820. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  37821. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  37822. }
  37823. self.gearVertexCount = (vertices.length / 2) - self.gearOffset;
  37824. // Build back arrow
  37825. self.arrowOffset = (vertices.length / 2);
  37826. function addArrowVertex(x, y) {
  37827. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  37828. }
  37829. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  37830. addArrowVertex(0, buttonScale);
  37831. addArrowVertex(buttonScale, 0);
  37832. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  37833. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  37834. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37835. addArrowVertex(0, buttonScale);
  37836. addArrowVertex(buttonScale, buttonScale * 2);
  37837. addArrowVertex(buttonScale + angledLineWidth, (buttonScale * 2) - angledLineWidth);
  37838. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37839. addArrowVertex(0, buttonScale);
  37840. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  37841. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  37842. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  37843. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  37844. self.arrowVertexCount = (vertices.length / 2) - self.arrowOffset;
  37845. // Buffer data
  37846. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37847. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  37848. });
  37849. };
  37850. /**
  37851. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37852. * backbuffer.
  37853. */
  37854. CardboardUI.prototype.render = function() {
  37855. var gl = this.gl;
  37856. var self = this;
  37857. var glState = [
  37858. gl.CULL_FACE,
  37859. gl.DEPTH_TEST,
  37860. gl.BLEND,
  37861. gl.SCISSOR_TEST,
  37862. gl.STENCIL_TEST,
  37863. gl.COLOR_WRITEMASK,
  37864. gl.VIEWPORT,
  37865. gl.CURRENT_PROGRAM,
  37866. gl.ARRAY_BUFFER_BINDING
  37867. ];
  37868. WGLUPreserveGLState(gl, glState, function(gl) {
  37869. // Make sure the GL state is in a good place
  37870. gl.disable(gl.CULL_FACE);
  37871. gl.disable(gl.DEPTH_TEST);
  37872. gl.disable(gl.BLEND);
  37873. gl.disable(gl.SCISSOR_TEST);
  37874. gl.disable(gl.STENCIL_TEST);
  37875. gl.colorMask(true, true, true, true);
  37876. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37877. self.renderNoState();
  37878. });
  37879. };
  37880. CardboardUI.prototype.renderNoState = function() {
  37881. var gl = this.gl;
  37882. // Bind distortion program and mesh
  37883. gl.useProgram(this.program);
  37884. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  37885. gl.enableVertexAttribArray(this.attribs.position);
  37886. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  37887. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  37888. Util.orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  37889. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  37890. // Draws UI element
  37891. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  37892. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  37893. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  37894. };
  37895. module.exports = CardboardUI;
  37896. },{"./deps/wglu-preserve-state.js":52,"./util.js":68}],51:[function(_dereq_,module,exports){
  37897. /*
  37898. * Copyright 2016 Google Inc. All Rights Reserved.
  37899. * Licensed under the Apache License, Version 2.0 (the "License");
  37900. * you may not use this file except in compliance with the License.
  37901. * You may obtain a copy of the License at
  37902. *
  37903. * http://www.apache.org/licenses/LICENSE-2.0
  37904. *
  37905. * Unless required by applicable law or agreed to in writing, software
  37906. * distributed under the License is distributed on an "AS IS" BASIS,
  37907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37908. * See the License for the specific language governing permissions and
  37909. * limitations under the License.
  37910. */
  37911. var CardboardDistorter = _dereq_('./cardboard-distorter.js');
  37912. var CardboardUI = _dereq_('./cardboard-ui.js');
  37913. var DeviceInfo = _dereq_('./device-info.js');
  37914. var Dpdb = _dereq_('./dpdb/dpdb.js');
  37915. var FusionPoseSensor = _dereq_('./sensor-fusion/fusion-pose-sensor.js');
  37916. var RotateInstructions = _dereq_('./rotate-instructions.js');
  37917. var ViewerSelector = _dereq_('./viewer-selector.js');
  37918. var VRDisplay = _dereq_('./base.js').VRDisplay;
  37919. var Util = _dereq_('./util.js');
  37920. var Eye = {
  37921. LEFT: 'left',
  37922. RIGHT: 'right'
  37923. };
  37924. /**
  37925. * VRDisplay based on mobile device parameters and DeviceMotion APIs.
  37926. */
  37927. function CardboardVRDisplay() {
  37928. this.displayName = 'Cardboard VRDisplay (webvr-polyfill)';
  37929. this.capabilities.hasOrientation = true;
  37930. this.capabilities.canPresent = true;
  37931. // "Private" members.
  37932. this.bufferScale_ = window.WebVRConfig.BUFFER_SCALE;
  37933. this.poseSensor_ = new FusionPoseSensor();
  37934. this.distorter_ = null;
  37935. this.cardboardUI_ = null;
  37936. this.dpdb_ = new Dpdb(true, this.onDeviceParamsUpdated_.bind(this));
  37937. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  37938. this.viewerSelector_ = new ViewerSelector();
  37939. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  37940. // Set the correct initial viewer.
  37941. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  37942. if (!window.WebVRConfig.ROTATE_INSTRUCTIONS_DISABLED) {
  37943. this.rotateInstructions_ = new RotateInstructions();
  37944. }
  37945. if (Util.isIOS()) {
  37946. // Listen for resize events to workaround this awful Safari bug.
  37947. window.addEventListener('resize', this.onResize_.bind(this));
  37948. }
  37949. }
  37950. CardboardVRDisplay.prototype = new VRDisplay();
  37951. CardboardVRDisplay.prototype.getImmediatePose = function() {
  37952. return {
  37953. position: this.poseSensor_.getPosition(),
  37954. orientation: this.poseSensor_.getOrientation(),
  37955. linearVelocity: null,
  37956. linearAcceleration: null,
  37957. angularVelocity: null,
  37958. angularAcceleration: null
  37959. };
  37960. };
  37961. CardboardVRDisplay.prototype.resetPose = function() {
  37962. this.poseSensor_.resetPose();
  37963. };
  37964. CardboardVRDisplay.prototype.getEyeParameters = function(whichEye) {
  37965. var offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  37966. var fieldOfView;
  37967. // TODO: FoV can be a little expensive to compute. Cache when device params change.
  37968. if (whichEye == Eye.LEFT) {
  37969. offset[0] *= -1.0;
  37970. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  37971. } else if (whichEye == Eye.RIGHT) {
  37972. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  37973. } else {
  37974. console.error('Invalid eye provided: %s', whichEye);
  37975. return null;
  37976. }
  37977. return {
  37978. fieldOfView: fieldOfView,
  37979. offset: offset,
  37980. // TODO: Should be able to provide better values than these.
  37981. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  37982. renderHeight: this.deviceInfo_.device.height * this.bufferScale_,
  37983. };
  37984. };
  37985. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function(newParams) {
  37986. if (Util.isDebug()) {
  37987. console.log('DPDB reported that device params were updated.');
  37988. }
  37989. this.deviceInfo_.updateDeviceParams(newParams);
  37990. if (this.distorter_) {
  37991. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37992. }
  37993. };
  37994. CardboardVRDisplay.prototype.updateBounds_ = function () {
  37995. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  37996. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  37997. }
  37998. };
  37999. CardboardVRDisplay.prototype.beginPresent_ = function() {
  38000. var gl = this.layer_.source.getContext('webgl');
  38001. if (!gl)
  38002. gl = this.layer_.source.getContext('experimental-webgl');
  38003. if (!gl)
  38004. gl = this.layer_.source.getContext('webgl2');
  38005. if (!gl)
  38006. return; // Can't do distortion without a WebGL context.
  38007. // Provides a way to opt out of distortion
  38008. if (this.layer_.predistorted) {
  38009. if (!window.WebVRConfig.CARDBOARD_UI_DISABLED) {
  38010. gl.canvas.width = Util.getScreenWidth() * this.bufferScale_;
  38011. gl.canvas.height = Util.getScreenHeight() * this.bufferScale_;
  38012. this.cardboardUI_ = new CardboardUI(gl);
  38013. }
  38014. } else {
  38015. // Create a new distorter for the target context
  38016. this.distorter_ = new CardboardDistorter(gl);
  38017. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  38018. this.cardboardUI_ = this.distorter_.cardboardUI;
  38019. }
  38020. if (this.cardboardUI_) {
  38021. this.cardboardUI_.listen(function(e) {
  38022. // Options clicked.
  38023. this.viewerSelector_.show(this.layer_.source.parentElement);
  38024. e.stopPropagation();
  38025. e.preventDefault();
  38026. }.bind(this), function(e) {
  38027. // Back clicked.
  38028. this.exitPresent();
  38029. e.stopPropagation();
  38030. e.preventDefault();
  38031. }.bind(this));
  38032. }
  38033. if (this.rotateInstructions_) {
  38034. if (Util.isLandscapeMode() && Util.isMobile()) {
  38035. // In landscape mode, temporarily show the "put into Cardboard"
  38036. // interstitial. Otherwise, do the default thing.
  38037. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  38038. } else {
  38039. this.rotateInstructions_.update();
  38040. }
  38041. }
  38042. // Listen for orientation change events in order to show interstitial.
  38043. this.orientationHandler = this.onOrientationChange_.bind(this);
  38044. window.addEventListener('orientationchange', this.orientationHandler);
  38045. // Listen for present display change events in order to update distorter dimensions
  38046. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  38047. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  38048. // Fire this event initially, to give geometry-distortion clients the chance
  38049. // to do something custom.
  38050. this.fireVRDisplayDeviceParamsChange_();
  38051. };
  38052. CardboardVRDisplay.prototype.endPresent_ = function() {
  38053. if (this.distorter_) {
  38054. this.distorter_.destroy();
  38055. this.distorter_ = null;
  38056. }
  38057. if (this.cardboardUI_) {
  38058. this.cardboardUI_.destroy();
  38059. this.cardboardUI_ = null;
  38060. }
  38061. if (this.rotateInstructions_) {
  38062. this.rotateInstructions_.hide();
  38063. }
  38064. this.viewerSelector_.hide();
  38065. window.removeEventListener('orientationchange', this.orientationHandler);
  38066. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  38067. };
  38068. CardboardVRDisplay.prototype.submitFrame = function(pose) {
  38069. if (this.distorter_) {
  38070. this.updateBounds_();
  38071. this.distorter_.submitFrame();
  38072. } else if (this.cardboardUI_ && this.layer_) {
  38073. // Hack for predistorted: true.
  38074. var canvas = this.layer_.source.getContext('webgl').canvas;
  38075. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  38076. this.cardboardUI_.onResize();
  38077. }
  38078. this.lastWidth = canvas.width;
  38079. this.lastHeight = canvas.height;
  38080. // Render the Cardboard UI.
  38081. this.cardboardUI_.render();
  38082. }
  38083. };
  38084. CardboardVRDisplay.prototype.onOrientationChange_ = function(e) {
  38085. // Hide the viewer selector.
  38086. this.viewerSelector_.hide();
  38087. // Update the rotate instructions.
  38088. if (this.rotateInstructions_) {
  38089. this.rotateInstructions_.update();
  38090. }
  38091. this.onResize_();
  38092. };
  38093. CardboardVRDisplay.prototype.onResize_ = function(e) {
  38094. if (this.layer_) {
  38095. var gl = this.layer_.source.getContext('webgl');
  38096. // Size the CSS canvas.
  38097. // Added padding on right and bottom because iPhone 5 will not
  38098. // hide the URL bar unless content is bigger than the screen.
  38099. // This will not be visible as long as the container element (e.g. body)
  38100. // is set to 'overflow: hidden'.
  38101. // Additionally, 'box-sizing: content-box' ensures renderWidth = width + padding.
  38102. // This is required when 'box-sizing: border-box' is used elsewhere in the page.
  38103. var cssProperties = [
  38104. 'position: absolute',
  38105. 'top: 0',
  38106. 'left: 0',
  38107. // Use vw/vh to handle implicitly devicePixelRatio; issue #282
  38108. 'width: 100vw',
  38109. 'height: 100vh',
  38110. 'border: 0',
  38111. 'margin: 0',
  38112. // Set no padding in the case where you don't have control over
  38113. // the content injection, like in Unity WebGL; issue #282
  38114. 'padding: 0px',
  38115. 'box-sizing: content-box',
  38116. ];
  38117. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  38118. Util.safariCssSizeWorkaround(gl.canvas);
  38119. }
  38120. };
  38121. CardboardVRDisplay.prototype.onViewerChanged_ = function(viewer) {
  38122. this.deviceInfo_.setViewer(viewer);
  38123. if (this.distorter_) {
  38124. // Update the distortion appropriately.
  38125. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  38126. }
  38127. // Fire a new event containing viewer and device parameters for clients that
  38128. // want to implement their own geometry-based distortion.
  38129. this.fireVRDisplayDeviceParamsChange_();
  38130. };
  38131. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function() {
  38132. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  38133. detail: {
  38134. vrdisplay: this,
  38135. deviceInfo: this.deviceInfo_,
  38136. }
  38137. });
  38138. window.dispatchEvent(event);
  38139. };
  38140. module.exports = CardboardVRDisplay;
  38141. },{"./base.js":48,"./cardboard-distorter.js":49,"./cardboard-ui.js":50,"./device-info.js":53,"./dpdb/dpdb.js":57,"./rotate-instructions.js":62,"./sensor-fusion/fusion-pose-sensor.js":64,"./util.js":68,"./viewer-selector.js":69}],52:[function(_dereq_,module,exports){
  38142. /**
  38143. * Copyright (c) 2016, Brandon Jones.
  38144. * https://github.com/toji/webgl-utils/blob/master/src/wglu-preserve-state.js
  38145. * LICENSE: https://github.com/toji/webgl-utils/blob/master/LICENSE.md
  38146. */
  38147. function WGLUPreserveGLState(gl, bindings, callback) {
  38148. if (!bindings) {
  38149. callback(gl);
  38150. return;
  38151. }
  38152. var boundValues = [];
  38153. var activeTexture = null;
  38154. for (var i = 0; i < bindings.length; ++i) {
  38155. var binding = bindings[i];
  38156. switch (binding) {
  38157. case gl.TEXTURE_BINDING_2D:
  38158. case gl.TEXTURE_BINDING_CUBE_MAP:
  38159. var textureUnit = bindings[++i];
  38160. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  38161. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  38162. boundValues.push(null, null);
  38163. break;
  38164. }
  38165. if (!activeTexture) {
  38166. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38167. }
  38168. gl.activeTexture(textureUnit);
  38169. boundValues.push(gl.getParameter(binding), null);
  38170. break;
  38171. case gl.ACTIVE_TEXTURE:
  38172. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38173. boundValues.push(null);
  38174. break;
  38175. default:
  38176. boundValues.push(gl.getParameter(binding));
  38177. break;
  38178. }
  38179. }
  38180. callback(gl);
  38181. for (var i = 0; i < bindings.length; ++i) {
  38182. var binding = bindings[i];
  38183. var boundValue = boundValues[i];
  38184. switch (binding) {
  38185. case gl.ACTIVE_TEXTURE:
  38186. break; // Ignore this binding, since we special-case it to happen last.
  38187. case gl.ARRAY_BUFFER_BINDING:
  38188. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  38189. break;
  38190. case gl.COLOR_CLEAR_VALUE:
  38191. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38192. break;
  38193. case gl.COLOR_WRITEMASK:
  38194. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38195. break;
  38196. case gl.CURRENT_PROGRAM:
  38197. gl.useProgram(boundValue);
  38198. break;
  38199. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  38200. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  38201. break;
  38202. case gl.FRAMEBUFFER_BINDING:
  38203. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  38204. break;
  38205. case gl.RENDERBUFFER_BINDING:
  38206. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  38207. break;
  38208. case gl.TEXTURE_BINDING_2D:
  38209. var textureUnit = bindings[++i];
  38210. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38211. break;
  38212. gl.activeTexture(textureUnit);
  38213. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  38214. break;
  38215. case gl.TEXTURE_BINDING_CUBE_MAP:
  38216. var textureUnit = bindings[++i];
  38217. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38218. break;
  38219. gl.activeTexture(textureUnit);
  38220. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  38221. break;
  38222. case gl.VIEWPORT:
  38223. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38224. break;
  38225. case gl.BLEND:
  38226. case gl.CULL_FACE:
  38227. case gl.DEPTH_TEST:
  38228. case gl.SCISSOR_TEST:
  38229. case gl.STENCIL_TEST:
  38230. if (boundValue) {
  38231. gl.enable(binding);
  38232. } else {
  38233. gl.disable(binding);
  38234. }
  38235. break;
  38236. default:
  38237. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38238. break;
  38239. }
  38240. if (activeTexture) {
  38241. gl.activeTexture(activeTexture);
  38242. }
  38243. }
  38244. }
  38245. module.exports = WGLUPreserveGLState;
  38246. },{}],53:[function(_dereq_,module,exports){
  38247. /*
  38248. * Copyright 2015 Google Inc. All Rights Reserved.
  38249. * Licensed under the Apache License, Version 2.0 (the "License");
  38250. * you may not use this file except in compliance with the License.
  38251. * You may obtain a copy of the License at
  38252. *
  38253. * http://www.apache.org/licenses/LICENSE-2.0
  38254. *
  38255. * Unless required by applicable law or agreed to in writing, software
  38256. * distributed under the License is distributed on an "AS IS" BASIS,
  38257. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38258. * See the License for the specific language governing permissions and
  38259. * limitations under the License.
  38260. */
  38261. var Distortion = _dereq_('./distortion/distortion.js');
  38262. var MathUtil = _dereq_('./math-util.js');
  38263. var Util = _dereq_('./util.js');
  38264. function Device(params) {
  38265. this.width = params.width || Util.getScreenWidth();
  38266. this.height = params.height || Util.getScreenHeight();
  38267. this.widthMeters = params.widthMeters;
  38268. this.heightMeters = params.heightMeters;
  38269. this.bevelMeters = params.bevelMeters;
  38270. }
  38271. // Fallback Android device (based on Nexus 5 measurements) for use when
  38272. // we can't recognize an Android device.
  38273. var DEFAULT_ANDROID = new Device({
  38274. widthMeters: 0.110,
  38275. heightMeters: 0.062,
  38276. bevelMeters: 0.004
  38277. });
  38278. // Fallback iOS device (based on iPhone6) for use when
  38279. // we can't recognize an Android device.
  38280. var DEFAULT_IOS = new Device({
  38281. widthMeters: 0.1038,
  38282. heightMeters: 0.0584,
  38283. bevelMeters: 0.004
  38284. });
  38285. var Viewers = {
  38286. CardboardV1: new CardboardViewer({
  38287. id: 'CardboardV1',
  38288. label: 'Cardboard I/O 2014',
  38289. fov: 40,
  38290. interLensDistance: 0.060,
  38291. baselineLensDistance: 0.035,
  38292. screenLensDistance: 0.042,
  38293. distortionCoefficients: [0.441, 0.156],
  38294. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139,
  38295. -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841,
  38296. 0.0651772, -0.01488963, 0.001559834]
  38297. }),
  38298. CardboardV2: new CardboardViewer({
  38299. id: 'CardboardV2',
  38300. label: 'Cardboard I/O 2015',
  38301. fov: 60,
  38302. interLensDistance: 0.064,
  38303. baselineLensDistance: 0.035,
  38304. screenLensDistance: 0.039,
  38305. distortionCoefficients: [0.34, 0.55],
  38306. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051,
  38307. 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956,
  38308. -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  38309. })
  38310. };
  38311. var DEFAULT_LEFT_CENTER = {x: 0.5, y: 0.5};
  38312. var DEFAULT_RIGHT_CENTER = {x: 0.5, y: 0.5};
  38313. /**
  38314. * Manages information about the device and the viewer.
  38315. *
  38316. * deviceParams indicates the parameters of the device to use (generally
  38317. * obtained from dpdb.getDeviceParams()). Can be null to mean no device
  38318. * params were found.
  38319. */
  38320. function DeviceInfo(deviceParams) {
  38321. this.viewer = Viewers.CardboardV2;
  38322. this.updateDeviceParams(deviceParams);
  38323. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38324. }
  38325. DeviceInfo.prototype.updateDeviceParams = function(deviceParams) {
  38326. this.device = this.determineDevice_(deviceParams) || this.device;
  38327. };
  38328. DeviceInfo.prototype.getDevice = function() {
  38329. return this.device;
  38330. };
  38331. DeviceInfo.prototype.setViewer = function(viewer) {
  38332. this.viewer = viewer;
  38333. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38334. };
  38335. DeviceInfo.prototype.determineDevice_ = function(deviceParams) {
  38336. if (!deviceParams) {
  38337. // No parameters, so use a default.
  38338. if (Util.isIOS()) {
  38339. console.warn('Using fallback iOS device measurements.');
  38340. return DEFAULT_IOS;
  38341. } else {
  38342. console.warn('Using fallback Android device measurements.');
  38343. return DEFAULT_ANDROID;
  38344. }
  38345. }
  38346. // Compute device screen dimensions based on deviceParams.
  38347. var METERS_PER_INCH = 0.0254;
  38348. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  38349. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  38350. var width = Util.getScreenWidth();
  38351. var height = Util.getScreenHeight();
  38352. return new Device({
  38353. widthMeters: metersPerPixelX * width,
  38354. heightMeters: metersPerPixelY * height,
  38355. bevelMeters: deviceParams.bevelMm * 0.001,
  38356. });
  38357. };
  38358. /**
  38359. * Calculates field of view for the left eye.
  38360. */
  38361. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function() {
  38362. var viewer = this.viewer;
  38363. var device = this.device;
  38364. var distortion = this.distortion;
  38365. // Device.height and device.width for device in portrait mode, so transpose.
  38366. var eyeToScreenDistance = viewer.screenLensDistance;
  38367. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  38368. var innerDist = viewer.interLensDistance / 2;
  38369. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  38370. var topDist = device.heightMeters - bottomDist;
  38371. var outerAngle = MathUtil.radToDeg * Math.atan(
  38372. distortion.distort(outerDist / eyeToScreenDistance));
  38373. var innerAngle = MathUtil.radToDeg * Math.atan(
  38374. distortion.distort(innerDist / eyeToScreenDistance));
  38375. var bottomAngle = MathUtil.radToDeg * Math.atan(
  38376. distortion.distort(bottomDist / eyeToScreenDistance));
  38377. var topAngle = MathUtil.radToDeg * Math.atan(
  38378. distortion.distort(topDist / eyeToScreenDistance));
  38379. return {
  38380. leftDegrees: Math.min(outerAngle, viewer.fov),
  38381. rightDegrees: Math.min(innerAngle, viewer.fov),
  38382. downDegrees: Math.min(bottomAngle, viewer.fov),
  38383. upDegrees: Math.min(topAngle, viewer.fov)
  38384. };
  38385. };
  38386. /**
  38387. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38388. * current device and screen parameters.
  38389. */
  38390. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function() {
  38391. var viewer = this.viewer;
  38392. var device = this.device;
  38393. var distortion = this.distortion;
  38394. // Tan-angles from the max FOV.
  38395. var fovLeft = Math.tan(-MathUtil.degToRad * viewer.fov);
  38396. var fovTop = Math.tan(MathUtil.degToRad * viewer.fov);
  38397. var fovRight = Math.tan(MathUtil.degToRad * viewer.fov);
  38398. var fovBottom = Math.tan(-MathUtil.degToRad * viewer.fov);
  38399. // Viewport size.
  38400. var halfWidth = device.widthMeters / 4;
  38401. var halfHeight = device.heightMeters / 2;
  38402. // Viewport center, measured from left lens position.
  38403. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38404. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38405. var centerY = -verticalLensOffset;
  38406. var centerZ = viewer.screenLensDistance;
  38407. // Tan-angles of the viewport edges, as seen through the lens.
  38408. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  38409. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  38410. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  38411. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  38412. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38413. var result = new Float32Array(4);
  38414. result[0] = Math.max(fovLeft, screenLeft);
  38415. result[1] = Math.min(fovTop, screenTop);
  38416. result[2] = Math.min(fovRight, screenRight);
  38417. result[3] = Math.max(fovBottom, screenBottom);
  38418. return result;
  38419. };
  38420. /**
  38421. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38422. * current device and screen parameters, assuming no lenses.
  38423. */
  38424. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function() {
  38425. var viewer = this.viewer;
  38426. var device = this.device;
  38427. var distortion = this.distortion;
  38428. var result = new Float32Array(4);
  38429. // Tan-angles from the max FOV.
  38430. var fovLeft = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38431. var fovTop = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38432. var fovRight = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38433. var fovBottom = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38434. // Viewport size.
  38435. var halfWidth = device.widthMeters / 4;
  38436. var halfHeight = device.heightMeters / 2;
  38437. // Viewport center, measured from left lens position.
  38438. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38439. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38440. var centerY = -verticalLensOffset;
  38441. var centerZ = viewer.screenLensDistance;
  38442. // Tan-angles of the viewport edges, as seen through the lens.
  38443. var screenLeft = (centerX - halfWidth) / centerZ;
  38444. var screenTop = (centerY + halfHeight) / centerZ;
  38445. var screenRight = (centerX + halfWidth) / centerZ;
  38446. var screenBottom = (centerY - halfHeight) / centerZ;
  38447. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38448. result[0] = Math.max(fovLeft, screenLeft);
  38449. result[1] = Math.min(fovTop, screenTop);
  38450. result[2] = Math.min(fovRight, screenRight);
  38451. result[3] = Math.max(fovBottom, screenBottom);
  38452. return result;
  38453. };
  38454. /**
  38455. * Calculates the screen rectangle visible from the left eye for the
  38456. * current device and screen parameters.
  38457. */
  38458. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function(undistortedFrustum) {
  38459. var viewer = this.viewer;
  38460. var device = this.device;
  38461. var dist = viewer.screenLensDistance;
  38462. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  38463. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  38464. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  38465. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  38466. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  38467. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  38468. return {
  38469. x: left,
  38470. y: bottom,
  38471. width: right - left,
  38472. height: top - bottom
  38473. };
  38474. };
  38475. DeviceInfo.prototype.getFieldOfViewLeftEye = function(opt_isUndistorted) {
  38476. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() :
  38477. this.getDistortedFieldOfViewLeftEye();
  38478. };
  38479. DeviceInfo.prototype.getFieldOfViewRightEye = function(opt_isUndistorted) {
  38480. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  38481. return {
  38482. leftDegrees: fov.rightDegrees,
  38483. rightDegrees: fov.leftDegrees,
  38484. upDegrees: fov.upDegrees,
  38485. downDegrees: fov.downDegrees
  38486. };
  38487. };
  38488. /**
  38489. * Calculates undistorted field of view for the left eye.
  38490. */
  38491. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function() {
  38492. var p = this.getUndistortedParams_();
  38493. return {
  38494. leftDegrees: MathUtil.radToDeg * Math.atan(p.outerDist),
  38495. rightDegrees: MathUtil.radToDeg * Math.atan(p.innerDist),
  38496. downDegrees: MathUtil.radToDeg * Math.atan(p.bottomDist),
  38497. upDegrees: MathUtil.radToDeg * Math.atan(p.topDist)
  38498. };
  38499. };
  38500. DeviceInfo.prototype.getUndistortedViewportLeftEye = function() {
  38501. var p = this.getUndistortedParams_();
  38502. var viewer = this.viewer;
  38503. var device = this.device;
  38504. // Distances stored in local variables are in tan-angle units unless otherwise
  38505. // noted.
  38506. var eyeToScreenDistance = viewer.screenLensDistance;
  38507. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38508. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38509. var xPxPerTanAngle = device.width / screenWidth;
  38510. var yPxPerTanAngle = device.height / screenHeight;
  38511. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  38512. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  38513. return {
  38514. x: x,
  38515. y: y,
  38516. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  38517. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  38518. };
  38519. };
  38520. DeviceInfo.prototype.getUndistortedParams_ = function() {
  38521. var viewer = this.viewer;
  38522. var device = this.device;
  38523. var distortion = this.distortion;
  38524. // Most of these variables in tan-angle units.
  38525. var eyeToScreenDistance = viewer.screenLensDistance;
  38526. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  38527. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38528. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38529. var eyePosX = screenWidth / 2 - halfLensDistance;
  38530. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  38531. var maxFov = viewer.fov;
  38532. var viewerMax = distortion.distortInverse(Math.tan(MathUtil.degToRad * maxFov));
  38533. var outerDist = Math.min(eyePosX, viewerMax);
  38534. var innerDist = Math.min(halfLensDistance, viewerMax);
  38535. var bottomDist = Math.min(eyePosY, viewerMax);
  38536. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  38537. return {
  38538. outerDist: outerDist,
  38539. innerDist: innerDist,
  38540. topDist: topDist,
  38541. bottomDist: bottomDist,
  38542. eyePosX: eyePosX,
  38543. eyePosY: eyePosY
  38544. };
  38545. };
  38546. function CardboardViewer(params) {
  38547. // A machine readable ID.
  38548. this.id = params.id;
  38549. // A human readable label.
  38550. this.label = params.label;
  38551. // Field of view in degrees (per side).
  38552. this.fov = params.fov;
  38553. // Distance between lens centers in meters.
  38554. this.interLensDistance = params.interLensDistance;
  38555. // Distance between viewer baseline and lens center in meters.
  38556. this.baselineLensDistance = params.baselineLensDistance;
  38557. // Screen-to-lens distance in meters.
  38558. this.screenLensDistance = params.screenLensDistance;
  38559. // Distortion coefficients.
  38560. this.distortionCoefficients = params.distortionCoefficients;
  38561. // Inverse distortion coefficients.
  38562. // TODO: Calculate these from distortionCoefficients in the future.
  38563. this.inverseCoefficients = params.inverseCoefficients;
  38564. }
  38565. // Export viewer information.
  38566. DeviceInfo.Viewers = Viewers;
  38567. module.exports = DeviceInfo;
  38568. },{"./distortion/distortion.js":55,"./math-util.js":59,"./util.js":68}],54:[function(_dereq_,module,exports){
  38569. /*
  38570. * Copyright 2016 Google Inc. All Rights Reserved.
  38571. * Licensed under the Apache License, Version 2.0 (the "License");
  38572. * you may not use this file except in compliance with the License.
  38573. * You may obtain a copy of the License at
  38574. *
  38575. * http://www.apache.org/licenses/LICENSE-2.0
  38576. *
  38577. * Unless required by applicable law or agreed to in writing, software
  38578. * distributed under the License is distributed on an "AS IS" BASIS,
  38579. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38580. * See the License for the specific language governing permissions and
  38581. * limitations under the License.
  38582. */
  38583. var VRDisplay = _dereq_('./base.js').VRDisplay;
  38584. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  38585. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  38586. /**
  38587. * Wraps a VRDisplay and exposes it as a HMDVRDevice
  38588. */
  38589. function VRDisplayHMDDevice(display) {
  38590. this.display = display;
  38591. this.hardwareUnitId = display.displayId;
  38592. this.deviceId = 'webvr-polyfill:HMD:' + display.displayId;
  38593. this.deviceName = display.displayName + ' (HMD)';
  38594. }
  38595. VRDisplayHMDDevice.prototype = new HMDVRDevice();
  38596. VRDisplayHMDDevice.prototype.getEyeParameters = function(whichEye) {
  38597. var eyeParameters = this.display.getEyeParameters(whichEye);
  38598. return {
  38599. currentFieldOfView: eyeParameters.fieldOfView,
  38600. maximumFieldOfView: eyeParameters.fieldOfView,
  38601. minimumFieldOfView: eyeParameters.fieldOfView,
  38602. recommendedFieldOfView: eyeParameters.fieldOfView,
  38603. eyeTranslation: { x: eyeParameters.offset[0], y: eyeParameters.offset[1], z: eyeParameters.offset[2] },
  38604. renderRect: {
  38605. x: (whichEye == 'right') ? eyeParameters.renderWidth : 0,
  38606. y: 0,
  38607. width: eyeParameters.renderWidth,
  38608. height: eyeParameters.renderHeight
  38609. }
  38610. };
  38611. };
  38612. VRDisplayHMDDevice.prototype.setFieldOfView =
  38613. function(opt_fovLeft, opt_fovRight, opt_zNear, opt_zFar) {
  38614. // Not supported. getEyeParameters reports that the min, max, and recommended
  38615. // FoV is all the same, so no adjustment can be made.
  38616. };
  38617. // TODO: Need to hook requestFullscreen to see if a wrapped VRDisplay was passed
  38618. // in as an option. If so we should prevent the default fullscreen behavior and
  38619. // call VRDisplay.requestPresent instead.
  38620. /**
  38621. * Wraps a VRDisplay and exposes it as a PositionSensorVRDevice
  38622. */
  38623. function VRDisplayPositionSensorDevice(display) {
  38624. this.display = display;
  38625. this.hardwareUnitId = display.displayId;
  38626. this.deviceId = 'webvr-polyfill:PositionSensor: ' + display.displayId;
  38627. this.deviceName = display.displayName + ' (PositionSensor)';
  38628. }
  38629. VRDisplayPositionSensorDevice.prototype = new PositionSensorVRDevice();
  38630. VRDisplayPositionSensorDevice.prototype.getState = function() {
  38631. var pose = this.display.getPose();
  38632. return {
  38633. position: pose.position ? { x: pose.position[0], y: pose.position[1], z: pose.position[2] } : null,
  38634. orientation: pose.orientation ? { x: pose.orientation[0], y: pose.orientation[1], z: pose.orientation[2], w: pose.orientation[3] } : null,
  38635. linearVelocity: null,
  38636. linearAcceleration: null,
  38637. angularVelocity: null,
  38638. angularAcceleration: null
  38639. };
  38640. };
  38641. VRDisplayPositionSensorDevice.prototype.resetState = function() {
  38642. return this.positionDevice.resetPose();
  38643. };
  38644. module.exports.VRDisplayHMDDevice = VRDisplayHMDDevice;
  38645. module.exports.VRDisplayPositionSensorDevice = VRDisplayPositionSensorDevice;
  38646. },{"./base.js":48}],55:[function(_dereq_,module,exports){
  38647. /**
  38648. * TODO(smus): Implement coefficient inversion.
  38649. */
  38650. function Distortion(coefficients) {
  38651. this.coefficients = coefficients;
  38652. }
  38653. /**
  38654. * Calculates the inverse distortion for a radius.
  38655. * </p><p>
  38656. * Allows to compute the original undistorted radius from a distorted one.
  38657. * See also getApproximateInverseDistortion() for a faster but potentially
  38658. * less accurate method.
  38659. *
  38660. * @param {Number} radius Distorted radius from the lens center in tan-angle units.
  38661. * @return {Number} The undistorted radius in tan-angle units.
  38662. */
  38663. Distortion.prototype.distortInverse = function(radius) {
  38664. // Secant method.
  38665. var r0 = 0;
  38666. var r1 = 1;
  38667. var dr0 = radius - this.distort(r0);
  38668. while (Math.abs(r1 - r0) > 0.0001 /** 0.1mm */) {
  38669. var dr1 = radius - this.distort(r1);
  38670. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38671. r0 = r1;
  38672. r1 = r2;
  38673. dr0 = dr1;
  38674. }
  38675. return r1;
  38676. };
  38677. /**
  38678. * Distorts a radius by its distortion factor from the center of the lenses.
  38679. *
  38680. * @param {Number} radius Radius from the lens center in tan-angle units.
  38681. * @return {Number} The distorted radius in tan-angle units.
  38682. */
  38683. Distortion.prototype.distort = function(radius) {
  38684. var r2 = radius * radius;
  38685. var ret = 0;
  38686. for (var i = 0; i < this.coefficients.length; i++) {
  38687. ret = r2 * (ret + this.coefficients[i]);
  38688. }
  38689. return (ret + 1) * radius;
  38690. };
  38691. module.exports = Distortion;
  38692. },{}],56:[function(_dereq_,module,exports){
  38693. module.exports={
  38694. "format": 1,
  38695. "last_updated": "2017-08-27T14:39:31Z",
  38696. "devices": [
  38697. {
  38698. "type": "android",
  38699. "rules": [
  38700. {
  38701. "mdmh": "asus/*/Nexus 7/*"
  38702. },
  38703. {
  38704. "ua": "Nexus 7"
  38705. }
  38706. ],
  38707. "dpi": [
  38708. 320.8,
  38709. 323
  38710. ],
  38711. "bw": 3,
  38712. "ac": 500
  38713. },
  38714. {
  38715. "type": "android",
  38716. "rules": [
  38717. {
  38718. "mdmh": "asus/*/ASUS_Z00AD/*"
  38719. },
  38720. {
  38721. "ua": "ASUS_Z00AD"
  38722. }
  38723. ],
  38724. "dpi": [
  38725. 403,
  38726. 404.6
  38727. ],
  38728. "bw": 3,
  38729. "ac": 1000
  38730. },
  38731. {
  38732. "type": "android",
  38733. "rules": [
  38734. {
  38735. "mdmh": "Google/*/Pixel XL/*"
  38736. },
  38737. {
  38738. "ua": "Pixel XL"
  38739. }
  38740. ],
  38741. "dpi": [
  38742. 537.9,
  38743. 533
  38744. ],
  38745. "bw": 3,
  38746. "ac": 1000
  38747. },
  38748. {
  38749. "type": "android",
  38750. "rules": [
  38751. {
  38752. "mdmh": "Google/*/Pixel/*"
  38753. },
  38754. {
  38755. "ua": "Pixel"
  38756. }
  38757. ],
  38758. "dpi": [
  38759. 432.6,
  38760. 436.7
  38761. ],
  38762. "bw": 3,
  38763. "ac": 1000
  38764. },
  38765. {
  38766. "type": "android",
  38767. "rules": [
  38768. {
  38769. "mdmh": "HTC/*/HTC6435LVW/*"
  38770. },
  38771. {
  38772. "ua": "HTC6435LVW"
  38773. }
  38774. ],
  38775. "dpi": [
  38776. 449.7,
  38777. 443.3
  38778. ],
  38779. "bw": 3,
  38780. "ac": 1000
  38781. },
  38782. {
  38783. "type": "android",
  38784. "rules": [
  38785. {
  38786. "mdmh": "HTC/*/HTC One XL/*"
  38787. },
  38788. {
  38789. "ua": "HTC One XL"
  38790. }
  38791. ],
  38792. "dpi": [
  38793. 315.3,
  38794. 314.6
  38795. ],
  38796. "bw": 3,
  38797. "ac": 1000
  38798. },
  38799. {
  38800. "type": "android",
  38801. "rules": [
  38802. {
  38803. "mdmh": "htc/*/Nexus 9/*"
  38804. },
  38805. {
  38806. "ua": "Nexus 9"
  38807. }
  38808. ],
  38809. "dpi": 289,
  38810. "bw": 3,
  38811. "ac": 500
  38812. },
  38813. {
  38814. "type": "android",
  38815. "rules": [
  38816. {
  38817. "mdmh": "HTC/*/HTC One M9/*"
  38818. },
  38819. {
  38820. "ua": "HTC One M9"
  38821. }
  38822. ],
  38823. "dpi": [
  38824. 442.5,
  38825. 443.3
  38826. ],
  38827. "bw": 3,
  38828. "ac": 500
  38829. },
  38830. {
  38831. "type": "android",
  38832. "rules": [
  38833. {
  38834. "mdmh": "HTC/*/HTC One_M8/*"
  38835. },
  38836. {
  38837. "ua": "HTC One_M8"
  38838. }
  38839. ],
  38840. "dpi": [
  38841. 449.7,
  38842. 447.4
  38843. ],
  38844. "bw": 3,
  38845. "ac": 500
  38846. },
  38847. {
  38848. "type": "android",
  38849. "rules": [
  38850. {
  38851. "mdmh": "HTC/*/HTC One/*"
  38852. },
  38853. {
  38854. "ua": "HTC One"
  38855. }
  38856. ],
  38857. "dpi": 472.8,
  38858. "bw": 3,
  38859. "ac": 1000
  38860. },
  38861. {
  38862. "type": "android",
  38863. "rules": [
  38864. {
  38865. "mdmh": "Huawei/*/Nexus 6P/*"
  38866. },
  38867. {
  38868. "ua": "Nexus 6P"
  38869. }
  38870. ],
  38871. "dpi": [
  38872. 515.1,
  38873. 518
  38874. ],
  38875. "bw": 3,
  38876. "ac": 1000
  38877. },
  38878. {
  38879. "type": "android",
  38880. "rules": [
  38881. {
  38882. "mdmh": "LENOVO/*/Lenovo PB2-690Y/*"
  38883. },
  38884. {
  38885. "ua": "Lenovo PB2-690Y"
  38886. }
  38887. ],
  38888. "dpi": [
  38889. 457.2,
  38890. 454.713
  38891. ],
  38892. "bw": 3,
  38893. "ac": 500
  38894. },
  38895. {
  38896. "type": "android",
  38897. "rules": [
  38898. {
  38899. "mdmh": "LGE/*/Nexus 5X/*"
  38900. },
  38901. {
  38902. "ua": "Nexus 5X"
  38903. }
  38904. ],
  38905. "dpi": [
  38906. 422,
  38907. 419.9
  38908. ],
  38909. "bw": 3,
  38910. "ac": 1000
  38911. },
  38912. {
  38913. "type": "android",
  38914. "rules": [
  38915. {
  38916. "mdmh": "LGE/*/LGMS345/*"
  38917. },
  38918. {
  38919. "ua": "LGMS345"
  38920. }
  38921. ],
  38922. "dpi": [
  38923. 221.7,
  38924. 219.1
  38925. ],
  38926. "bw": 3,
  38927. "ac": 500
  38928. },
  38929. {
  38930. "type": "android",
  38931. "rules": [
  38932. {
  38933. "mdmh": "LGE/*/LG-D800/*"
  38934. },
  38935. {
  38936. "ua": "LG-D800"
  38937. }
  38938. ],
  38939. "dpi": [
  38940. 422,
  38941. 424.1
  38942. ],
  38943. "bw": 3,
  38944. "ac": 500
  38945. },
  38946. {
  38947. "type": "android",
  38948. "rules": [
  38949. {
  38950. "mdmh": "LGE/*/LG-D850/*"
  38951. },
  38952. {
  38953. "ua": "LG-D850"
  38954. }
  38955. ],
  38956. "dpi": [
  38957. 537.9,
  38958. 541.9
  38959. ],
  38960. "bw": 3,
  38961. "ac": 500
  38962. },
  38963. {
  38964. "type": "android",
  38965. "rules": [
  38966. {
  38967. "mdmh": "LGE/*/VS985 4G/*"
  38968. },
  38969. {
  38970. "ua": "VS985 4G"
  38971. }
  38972. ],
  38973. "dpi": [
  38974. 537.9,
  38975. 535.6
  38976. ],
  38977. "bw": 3,
  38978. "ac": 1000
  38979. },
  38980. {
  38981. "type": "android",
  38982. "rules": [
  38983. {
  38984. "mdmh": "LGE/*/Nexus 5/*"
  38985. },
  38986. {
  38987. "ua": "Nexus 5 B"
  38988. }
  38989. ],
  38990. "dpi": [
  38991. 442.4,
  38992. 444.8
  38993. ],
  38994. "bw": 3,
  38995. "ac": 1000
  38996. },
  38997. {
  38998. "type": "android",
  38999. "rules": [
  39000. {
  39001. "mdmh": "LGE/*/Nexus 4/*"
  39002. },
  39003. {
  39004. "ua": "Nexus 4"
  39005. }
  39006. ],
  39007. "dpi": [
  39008. 319.8,
  39009. 318.4
  39010. ],
  39011. "bw": 3,
  39012. "ac": 1000
  39013. },
  39014. {
  39015. "type": "android",
  39016. "rules": [
  39017. {
  39018. "mdmh": "LGE/*/LG-P769/*"
  39019. },
  39020. {
  39021. "ua": "LG-P769"
  39022. }
  39023. ],
  39024. "dpi": [
  39025. 240.6,
  39026. 247.5
  39027. ],
  39028. "bw": 3,
  39029. "ac": 1000
  39030. },
  39031. {
  39032. "type": "android",
  39033. "rules": [
  39034. {
  39035. "mdmh": "LGE/*/LGMS323/*"
  39036. },
  39037. {
  39038. "ua": "LGMS323"
  39039. }
  39040. ],
  39041. "dpi": [
  39042. 206.6,
  39043. 204.6
  39044. ],
  39045. "bw": 3,
  39046. "ac": 1000
  39047. },
  39048. {
  39049. "type": "android",
  39050. "rules": [
  39051. {
  39052. "mdmh": "LGE/*/LGLS996/*"
  39053. },
  39054. {
  39055. "ua": "LGLS996"
  39056. }
  39057. ],
  39058. "dpi": [
  39059. 403.4,
  39060. 401.5
  39061. ],
  39062. "bw": 3,
  39063. "ac": 1000
  39064. },
  39065. {
  39066. "type": "android",
  39067. "rules": [
  39068. {
  39069. "mdmh": "Micromax/*/4560MMX/*"
  39070. },
  39071. {
  39072. "ua": "4560MMX"
  39073. }
  39074. ],
  39075. "dpi": [
  39076. 240,
  39077. 219.4
  39078. ],
  39079. "bw": 3,
  39080. "ac": 1000
  39081. },
  39082. {
  39083. "type": "android",
  39084. "rules": [
  39085. {
  39086. "mdmh": "Micromax/*/A250/*"
  39087. },
  39088. {
  39089. "ua": "Micromax A250"
  39090. }
  39091. ],
  39092. "dpi": [
  39093. 480,
  39094. 446.4
  39095. ],
  39096. "bw": 3,
  39097. "ac": 1000
  39098. },
  39099. {
  39100. "type": "android",
  39101. "rules": [
  39102. {
  39103. "mdmh": "Micromax/*/Micromax AQ4501/*"
  39104. },
  39105. {
  39106. "ua": "Micromax AQ4501"
  39107. }
  39108. ],
  39109. "dpi": 240,
  39110. "bw": 3,
  39111. "ac": 500
  39112. },
  39113. {
  39114. "type": "android",
  39115. "rules": [
  39116. {
  39117. "mdmh": "motorola/*/DROID RAZR/*"
  39118. },
  39119. {
  39120. "ua": "DROID RAZR"
  39121. }
  39122. ],
  39123. "dpi": [
  39124. 368.1,
  39125. 256.7
  39126. ],
  39127. "bw": 3,
  39128. "ac": 1000
  39129. },
  39130. {
  39131. "type": "android",
  39132. "rules": [
  39133. {
  39134. "mdmh": "motorola/*/XT830C/*"
  39135. },
  39136. {
  39137. "ua": "XT830C"
  39138. }
  39139. ],
  39140. "dpi": [
  39141. 254,
  39142. 255.9
  39143. ],
  39144. "bw": 3,
  39145. "ac": 1000
  39146. },
  39147. {
  39148. "type": "android",
  39149. "rules": [
  39150. {
  39151. "mdmh": "motorola/*/XT1021/*"
  39152. },
  39153. {
  39154. "ua": "XT1021"
  39155. }
  39156. ],
  39157. "dpi": [
  39158. 254,
  39159. 256.7
  39160. ],
  39161. "bw": 3,
  39162. "ac": 500
  39163. },
  39164. {
  39165. "type": "android",
  39166. "rules": [
  39167. {
  39168. "mdmh": "motorola/*/XT1023/*"
  39169. },
  39170. {
  39171. "ua": "XT1023"
  39172. }
  39173. ],
  39174. "dpi": [
  39175. 254,
  39176. 256.7
  39177. ],
  39178. "bw": 3,
  39179. "ac": 500
  39180. },
  39181. {
  39182. "type": "android",
  39183. "rules": [
  39184. {
  39185. "mdmh": "motorola/*/XT1028/*"
  39186. },
  39187. {
  39188. "ua": "XT1028"
  39189. }
  39190. ],
  39191. "dpi": [
  39192. 326.6,
  39193. 327.6
  39194. ],
  39195. "bw": 3,
  39196. "ac": 1000
  39197. },
  39198. {
  39199. "type": "android",
  39200. "rules": [
  39201. {
  39202. "mdmh": "motorola/*/XT1034/*"
  39203. },
  39204. {
  39205. "ua": "XT1034"
  39206. }
  39207. ],
  39208. "dpi": [
  39209. 326.6,
  39210. 328.4
  39211. ],
  39212. "bw": 3,
  39213. "ac": 500
  39214. },
  39215. {
  39216. "type": "android",
  39217. "rules": [
  39218. {
  39219. "mdmh": "motorola/*/XT1053/*"
  39220. },
  39221. {
  39222. "ua": "XT1053"
  39223. }
  39224. ],
  39225. "dpi": [
  39226. 315.3,
  39227. 316.1
  39228. ],
  39229. "bw": 3,
  39230. "ac": 1000
  39231. },
  39232. {
  39233. "type": "android",
  39234. "rules": [
  39235. {
  39236. "mdmh": "motorola/*/XT1562/*"
  39237. },
  39238. {
  39239. "ua": "XT1562"
  39240. }
  39241. ],
  39242. "dpi": [
  39243. 403.4,
  39244. 402.7
  39245. ],
  39246. "bw": 3,
  39247. "ac": 1000
  39248. },
  39249. {
  39250. "type": "android",
  39251. "rules": [
  39252. {
  39253. "mdmh": "motorola/*/Nexus 6/*"
  39254. },
  39255. {
  39256. "ua": "Nexus 6 B"
  39257. }
  39258. ],
  39259. "dpi": [
  39260. 494.3,
  39261. 489.7
  39262. ],
  39263. "bw": 3,
  39264. "ac": 1000
  39265. },
  39266. {
  39267. "type": "android",
  39268. "rules": [
  39269. {
  39270. "mdmh": "motorola/*/XT1063/*"
  39271. },
  39272. {
  39273. "ua": "XT1063"
  39274. }
  39275. ],
  39276. "dpi": [
  39277. 295,
  39278. 296.6
  39279. ],
  39280. "bw": 3,
  39281. "ac": 1000
  39282. },
  39283. {
  39284. "type": "android",
  39285. "rules": [
  39286. {
  39287. "mdmh": "motorola/*/XT1064/*"
  39288. },
  39289. {
  39290. "ua": "XT1064"
  39291. }
  39292. ],
  39293. "dpi": [
  39294. 295,
  39295. 295.6
  39296. ],
  39297. "bw": 3,
  39298. "ac": 500
  39299. },
  39300. {
  39301. "type": "android",
  39302. "rules": [
  39303. {
  39304. "mdmh": "motorola/*/XT1092/*"
  39305. },
  39306. {
  39307. "ua": "XT1092"
  39308. }
  39309. ],
  39310. "dpi": [
  39311. 422,
  39312. 424.1
  39313. ],
  39314. "bw": 3,
  39315. "ac": 500
  39316. },
  39317. {
  39318. "type": "android",
  39319. "rules": [
  39320. {
  39321. "mdmh": "motorola/*/XT1095/*"
  39322. },
  39323. {
  39324. "ua": "XT1095"
  39325. }
  39326. ],
  39327. "dpi": [
  39328. 422,
  39329. 423.4
  39330. ],
  39331. "bw": 3,
  39332. "ac": 1000
  39333. },
  39334. {
  39335. "type": "android",
  39336. "rules": [
  39337. {
  39338. "mdmh": "motorola/*/G4/*"
  39339. },
  39340. {
  39341. "ua": "Moto G (4)"
  39342. }
  39343. ],
  39344. "dpi": 401,
  39345. "bw": 4,
  39346. "ac": 1000
  39347. },
  39348. {
  39349. "type": "android",
  39350. "rules": [
  39351. {
  39352. "mdmh": "OnePlus/*/A0001/*"
  39353. },
  39354. {
  39355. "ua": "A0001"
  39356. }
  39357. ],
  39358. "dpi": [
  39359. 403.4,
  39360. 401
  39361. ],
  39362. "bw": 3,
  39363. "ac": 1000
  39364. },
  39365. {
  39366. "type": "android",
  39367. "rules": [
  39368. {
  39369. "mdmh": "OnePlus/*/ONE E1005/*"
  39370. },
  39371. {
  39372. "ua": "ONE E1005"
  39373. }
  39374. ],
  39375. "dpi": [
  39376. 442.4,
  39377. 441.4
  39378. ],
  39379. "bw": 3,
  39380. "ac": 1000
  39381. },
  39382. {
  39383. "type": "android",
  39384. "rules": [
  39385. {
  39386. "mdmh": "OnePlus/*/ONE A2005/*"
  39387. },
  39388. {
  39389. "ua": "ONE A2005"
  39390. }
  39391. ],
  39392. "dpi": [
  39393. 391.9,
  39394. 405.4
  39395. ],
  39396. "bw": 3,
  39397. "ac": 1000
  39398. },
  39399. {
  39400. "type": "android",
  39401. "rules": [
  39402. {
  39403. "mdmh": "OPPO/*/X909/*"
  39404. },
  39405. {
  39406. "ua": "X909"
  39407. }
  39408. ],
  39409. "dpi": [
  39410. 442.4,
  39411. 444.1
  39412. ],
  39413. "bw": 3,
  39414. "ac": 1000
  39415. },
  39416. {
  39417. "type": "android",
  39418. "rules": [
  39419. {
  39420. "mdmh": "samsung/*/GT-I9082/*"
  39421. },
  39422. {
  39423. "ua": "GT-I9082"
  39424. }
  39425. ],
  39426. "dpi": [
  39427. 184.7,
  39428. 185.4
  39429. ],
  39430. "bw": 3,
  39431. "ac": 1000
  39432. },
  39433. {
  39434. "type": "android",
  39435. "rules": [
  39436. {
  39437. "mdmh": "samsung/*/SM-G360P/*"
  39438. },
  39439. {
  39440. "ua": "SM-G360P"
  39441. }
  39442. ],
  39443. "dpi": [
  39444. 196.7,
  39445. 205.4
  39446. ],
  39447. "bw": 3,
  39448. "ac": 1000
  39449. },
  39450. {
  39451. "type": "android",
  39452. "rules": [
  39453. {
  39454. "mdmh": "samsung/*/Nexus S/*"
  39455. },
  39456. {
  39457. "ua": "Nexus S"
  39458. }
  39459. ],
  39460. "dpi": [
  39461. 234.5,
  39462. 229.8
  39463. ],
  39464. "bw": 3,
  39465. "ac": 1000
  39466. },
  39467. {
  39468. "type": "android",
  39469. "rules": [
  39470. {
  39471. "mdmh": "samsung/*/GT-I9300/*"
  39472. },
  39473. {
  39474. "ua": "GT-I9300"
  39475. }
  39476. ],
  39477. "dpi": [
  39478. 304.8,
  39479. 303.9
  39480. ],
  39481. "bw": 5,
  39482. "ac": 500
  39483. },
  39484. {
  39485. "type": "android",
  39486. "rules": [
  39487. {
  39488. "mdmh": "samsung/*/SM-T230NU/*"
  39489. },
  39490. {
  39491. "ua": "SM-T230NU"
  39492. }
  39493. ],
  39494. "dpi": 216,
  39495. "bw": 3,
  39496. "ac": 500
  39497. },
  39498. {
  39499. "type": "android",
  39500. "rules": [
  39501. {
  39502. "mdmh": "samsung/*/SGH-T399/*"
  39503. },
  39504. {
  39505. "ua": "SGH-T399"
  39506. }
  39507. ],
  39508. "dpi": [
  39509. 217.7,
  39510. 231.4
  39511. ],
  39512. "bw": 3,
  39513. "ac": 1000
  39514. },
  39515. {
  39516. "type": "android",
  39517. "rules": [
  39518. {
  39519. "mdmh": "samsung/*/SGH-M919/*"
  39520. },
  39521. {
  39522. "ua": "SGH-M919"
  39523. }
  39524. ],
  39525. "dpi": [
  39526. 440.8,
  39527. 437.7
  39528. ],
  39529. "bw": 3,
  39530. "ac": 1000
  39531. },
  39532. {
  39533. "type": "android",
  39534. "rules": [
  39535. {
  39536. "mdmh": "samsung/*/SM-N9005/*"
  39537. },
  39538. {
  39539. "ua": "SM-N9005"
  39540. }
  39541. ],
  39542. "dpi": [
  39543. 386.4,
  39544. 387
  39545. ],
  39546. "bw": 3,
  39547. "ac": 500
  39548. },
  39549. {
  39550. "type": "android",
  39551. "rules": [
  39552. {
  39553. "mdmh": "samsung/*/SAMSUNG-SM-N900A/*"
  39554. },
  39555. {
  39556. "ua": "SAMSUNG-SM-N900A"
  39557. }
  39558. ],
  39559. "dpi": [
  39560. 386.4,
  39561. 387.7
  39562. ],
  39563. "bw": 3,
  39564. "ac": 1000
  39565. },
  39566. {
  39567. "type": "android",
  39568. "rules": [
  39569. {
  39570. "mdmh": "samsung/*/GT-I9500/*"
  39571. },
  39572. {
  39573. "ua": "GT-I9500"
  39574. }
  39575. ],
  39576. "dpi": [
  39577. 442.5,
  39578. 443.3
  39579. ],
  39580. "bw": 3,
  39581. "ac": 500
  39582. },
  39583. {
  39584. "type": "android",
  39585. "rules": [
  39586. {
  39587. "mdmh": "samsung/*/GT-I9505/*"
  39588. },
  39589. {
  39590. "ua": "GT-I9505"
  39591. }
  39592. ],
  39593. "dpi": 439.4,
  39594. "bw": 4,
  39595. "ac": 1000
  39596. },
  39597. {
  39598. "type": "android",
  39599. "rules": [
  39600. {
  39601. "mdmh": "samsung/*/SM-G900F/*"
  39602. },
  39603. {
  39604. "ua": "SM-G900F"
  39605. }
  39606. ],
  39607. "dpi": [
  39608. 415.6,
  39609. 431.6
  39610. ],
  39611. "bw": 5,
  39612. "ac": 1000
  39613. },
  39614. {
  39615. "type": "android",
  39616. "rules": [
  39617. {
  39618. "mdmh": "samsung/*/SM-G900M/*"
  39619. },
  39620. {
  39621. "ua": "SM-G900M"
  39622. }
  39623. ],
  39624. "dpi": [
  39625. 415.6,
  39626. 431.6
  39627. ],
  39628. "bw": 5,
  39629. "ac": 1000
  39630. },
  39631. {
  39632. "type": "android",
  39633. "rules": [
  39634. {
  39635. "mdmh": "samsung/*/SM-G800F/*"
  39636. },
  39637. {
  39638. "ua": "SM-G800F"
  39639. }
  39640. ],
  39641. "dpi": 326.8,
  39642. "bw": 3,
  39643. "ac": 1000
  39644. },
  39645. {
  39646. "type": "android",
  39647. "rules": [
  39648. {
  39649. "mdmh": "samsung/*/SM-G906S/*"
  39650. },
  39651. {
  39652. "ua": "SM-G906S"
  39653. }
  39654. ],
  39655. "dpi": [
  39656. 562.7,
  39657. 572.4
  39658. ],
  39659. "bw": 3,
  39660. "ac": 1000
  39661. },
  39662. {
  39663. "type": "android",
  39664. "rules": [
  39665. {
  39666. "mdmh": "samsung/*/GT-I9300/*"
  39667. },
  39668. {
  39669. "ua": "GT-I9300"
  39670. }
  39671. ],
  39672. "dpi": [
  39673. 306.7,
  39674. 304.8
  39675. ],
  39676. "bw": 5,
  39677. "ac": 1000
  39678. },
  39679. {
  39680. "type": "android",
  39681. "rules": [
  39682. {
  39683. "mdmh": "samsung/*/SM-T535/*"
  39684. },
  39685. {
  39686. "ua": "SM-T535"
  39687. }
  39688. ],
  39689. "dpi": [
  39690. 142.6,
  39691. 136.4
  39692. ],
  39693. "bw": 3,
  39694. "ac": 500
  39695. },
  39696. {
  39697. "type": "android",
  39698. "rules": [
  39699. {
  39700. "mdmh": "samsung/*/SM-N920C/*"
  39701. },
  39702. {
  39703. "ua": "SM-N920C"
  39704. }
  39705. ],
  39706. "dpi": [
  39707. 515.1,
  39708. 518.4
  39709. ],
  39710. "bw": 3,
  39711. "ac": 1000
  39712. },
  39713. {
  39714. "type": "android",
  39715. "rules": [
  39716. {
  39717. "mdmh": "samsung/*/SM-N920W8/*"
  39718. },
  39719. {
  39720. "ua": "SM-N920W8"
  39721. }
  39722. ],
  39723. "dpi": [
  39724. 515.1,
  39725. 518.4
  39726. ],
  39727. "bw": 3,
  39728. "ac": 1000
  39729. },
  39730. {
  39731. "type": "android",
  39732. "rules": [
  39733. {
  39734. "mdmh": "samsung/*/GT-I9300I/*"
  39735. },
  39736. {
  39737. "ua": "GT-I9300I"
  39738. }
  39739. ],
  39740. "dpi": [
  39741. 304.8,
  39742. 305.8
  39743. ],
  39744. "bw": 3,
  39745. "ac": 1000
  39746. },
  39747. {
  39748. "type": "android",
  39749. "rules": [
  39750. {
  39751. "mdmh": "samsung/*/GT-I9195/*"
  39752. },
  39753. {
  39754. "ua": "GT-I9195"
  39755. }
  39756. ],
  39757. "dpi": [
  39758. 249.4,
  39759. 256.7
  39760. ],
  39761. "bw": 3,
  39762. "ac": 500
  39763. },
  39764. {
  39765. "type": "android",
  39766. "rules": [
  39767. {
  39768. "mdmh": "samsung/*/SPH-L520/*"
  39769. },
  39770. {
  39771. "ua": "SPH-L520"
  39772. }
  39773. ],
  39774. "dpi": [
  39775. 249.4,
  39776. 255.9
  39777. ],
  39778. "bw": 3,
  39779. "ac": 1000
  39780. },
  39781. {
  39782. "type": "android",
  39783. "rules": [
  39784. {
  39785. "mdmh": "samsung/*/SAMSUNG-SGH-I717/*"
  39786. },
  39787. {
  39788. "ua": "SAMSUNG-SGH-I717"
  39789. }
  39790. ],
  39791. "dpi": 285.8,
  39792. "bw": 3,
  39793. "ac": 1000
  39794. },
  39795. {
  39796. "type": "android",
  39797. "rules": [
  39798. {
  39799. "mdmh": "samsung/*/SPH-D710/*"
  39800. },
  39801. {
  39802. "ua": "SPH-D710"
  39803. }
  39804. ],
  39805. "dpi": [
  39806. 217.7,
  39807. 204.2
  39808. ],
  39809. "bw": 3,
  39810. "ac": 1000
  39811. },
  39812. {
  39813. "type": "android",
  39814. "rules": [
  39815. {
  39816. "mdmh": "samsung/*/GT-N7100/*"
  39817. },
  39818. {
  39819. "ua": "GT-N7100"
  39820. }
  39821. ],
  39822. "dpi": 265.1,
  39823. "bw": 3,
  39824. "ac": 1000
  39825. },
  39826. {
  39827. "type": "android",
  39828. "rules": [
  39829. {
  39830. "mdmh": "samsung/*/SCH-I605/*"
  39831. },
  39832. {
  39833. "ua": "SCH-I605"
  39834. }
  39835. ],
  39836. "dpi": 265.1,
  39837. "bw": 3,
  39838. "ac": 1000
  39839. },
  39840. {
  39841. "type": "android",
  39842. "rules": [
  39843. {
  39844. "mdmh": "samsung/*/Galaxy Nexus/*"
  39845. },
  39846. {
  39847. "ua": "Galaxy Nexus"
  39848. }
  39849. ],
  39850. "dpi": [
  39851. 315.3,
  39852. 314.2
  39853. ],
  39854. "bw": 3,
  39855. "ac": 1000
  39856. },
  39857. {
  39858. "type": "android",
  39859. "rules": [
  39860. {
  39861. "mdmh": "samsung/*/SM-N910H/*"
  39862. },
  39863. {
  39864. "ua": "SM-N910H"
  39865. }
  39866. ],
  39867. "dpi": [
  39868. 515.1,
  39869. 518
  39870. ],
  39871. "bw": 3,
  39872. "ac": 1000
  39873. },
  39874. {
  39875. "type": "android",
  39876. "rules": [
  39877. {
  39878. "mdmh": "samsung/*/SM-N910C/*"
  39879. },
  39880. {
  39881. "ua": "SM-N910C"
  39882. }
  39883. ],
  39884. "dpi": [
  39885. 515.2,
  39886. 520.2
  39887. ],
  39888. "bw": 3,
  39889. "ac": 500
  39890. },
  39891. {
  39892. "type": "android",
  39893. "rules": [
  39894. {
  39895. "mdmh": "samsung/*/SM-G130M/*"
  39896. },
  39897. {
  39898. "ua": "SM-G130M"
  39899. }
  39900. ],
  39901. "dpi": [
  39902. 165.9,
  39903. 164.8
  39904. ],
  39905. "bw": 3,
  39906. "ac": 500
  39907. },
  39908. {
  39909. "type": "android",
  39910. "rules": [
  39911. {
  39912. "mdmh": "samsung/*/SM-G928I/*"
  39913. },
  39914. {
  39915. "ua": "SM-G928I"
  39916. }
  39917. ],
  39918. "dpi": [
  39919. 515.1,
  39920. 518.4
  39921. ],
  39922. "bw": 3,
  39923. "ac": 1000
  39924. },
  39925. {
  39926. "type": "android",
  39927. "rules": [
  39928. {
  39929. "mdmh": "samsung/*/SM-G920F/*"
  39930. },
  39931. {
  39932. "ua": "SM-G920F"
  39933. }
  39934. ],
  39935. "dpi": 580.6,
  39936. "bw": 3,
  39937. "ac": 500
  39938. },
  39939. {
  39940. "type": "android",
  39941. "rules": [
  39942. {
  39943. "mdmh": "samsung/*/SM-G920P/*"
  39944. },
  39945. {
  39946. "ua": "SM-G920P"
  39947. }
  39948. ],
  39949. "dpi": [
  39950. 522.5,
  39951. 577
  39952. ],
  39953. "bw": 3,
  39954. "ac": 1000
  39955. },
  39956. {
  39957. "type": "android",
  39958. "rules": [
  39959. {
  39960. "mdmh": "samsung/*/SM-G925F/*"
  39961. },
  39962. {
  39963. "ua": "SM-G925F"
  39964. }
  39965. ],
  39966. "dpi": 580.6,
  39967. "bw": 3,
  39968. "ac": 500
  39969. },
  39970. {
  39971. "type": "android",
  39972. "rules": [
  39973. {
  39974. "mdmh": "samsung/*/SM-G925V/*"
  39975. },
  39976. {
  39977. "ua": "SM-G925V"
  39978. }
  39979. ],
  39980. "dpi": [
  39981. 522.5,
  39982. 576.6
  39983. ],
  39984. "bw": 3,
  39985. "ac": 1000
  39986. },
  39987. {
  39988. "type": "android",
  39989. "rules": [
  39990. {
  39991. "mdmh": "samsung/*/SM-G930F/*"
  39992. },
  39993. {
  39994. "ua": "SM-G930F"
  39995. }
  39996. ],
  39997. "dpi": 576.6,
  39998. "bw": 3,
  39999. "ac": 1000
  40000. },
  40001. {
  40002. "type": "android",
  40003. "rules": [
  40004. {
  40005. "mdmh": "samsung/*/SM-G935F/*"
  40006. },
  40007. {
  40008. "ua": "SM-G935F"
  40009. }
  40010. ],
  40011. "dpi": 533,
  40012. "bw": 3,
  40013. "ac": 500
  40014. },
  40015. {
  40016. "type": "android",
  40017. "rules": [
  40018. {
  40019. "mdmh": "samsung/*/SM-G950F/*"
  40020. },
  40021. {
  40022. "ua": "SM-G950F"
  40023. }
  40024. ],
  40025. "dpi": [
  40026. 562.707,
  40027. 565.293
  40028. ],
  40029. "bw": 3,
  40030. "ac": 500
  40031. },
  40032. {
  40033. "type": "android",
  40034. "rules": [
  40035. {
  40036. "mdmh": "samsung/*/SM-G955U/*"
  40037. },
  40038. {
  40039. "ua": "SM-G955U"
  40040. }
  40041. ],
  40042. "dpi": [
  40043. 522.514,
  40044. 525.762
  40045. ],
  40046. "bw": 3,
  40047. "ac": 500
  40048. },
  40049. {
  40050. "type": "android",
  40051. "rules": [
  40052. {
  40053. "mdmh": "Sony/*/C6903/*"
  40054. },
  40055. {
  40056. "ua": "C6903"
  40057. }
  40058. ],
  40059. "dpi": [
  40060. 442.5,
  40061. 443.3
  40062. ],
  40063. "bw": 3,
  40064. "ac": 500
  40065. },
  40066. {
  40067. "type": "android",
  40068. "rules": [
  40069. {
  40070. "mdmh": "Sony/*/D6653/*"
  40071. },
  40072. {
  40073. "ua": "D6653"
  40074. }
  40075. ],
  40076. "dpi": [
  40077. 428.6,
  40078. 427.6
  40079. ],
  40080. "bw": 3,
  40081. "ac": 1000
  40082. },
  40083. {
  40084. "type": "android",
  40085. "rules": [
  40086. {
  40087. "mdmh": "Sony/*/E6653/*"
  40088. },
  40089. {
  40090. "ua": "E6653"
  40091. }
  40092. ],
  40093. "dpi": [
  40094. 428.6,
  40095. 425.7
  40096. ],
  40097. "bw": 3,
  40098. "ac": 1000
  40099. },
  40100. {
  40101. "type": "android",
  40102. "rules": [
  40103. {
  40104. "mdmh": "Sony/*/E6853/*"
  40105. },
  40106. {
  40107. "ua": "E6853"
  40108. }
  40109. ],
  40110. "dpi": [
  40111. 403.4,
  40112. 401.9
  40113. ],
  40114. "bw": 3,
  40115. "ac": 1000
  40116. },
  40117. {
  40118. "type": "android",
  40119. "rules": [
  40120. {
  40121. "mdmh": "Sony/*/SGP321/*"
  40122. },
  40123. {
  40124. "ua": "SGP321"
  40125. }
  40126. ],
  40127. "dpi": [
  40128. 224.7,
  40129. 224.1
  40130. ],
  40131. "bw": 3,
  40132. "ac": 500
  40133. },
  40134. {
  40135. "type": "android",
  40136. "rules": [
  40137. {
  40138. "mdmh": "TCT/*/ALCATEL ONE TOUCH Fierce/*"
  40139. },
  40140. {
  40141. "ua": "ALCATEL ONE TOUCH Fierce"
  40142. }
  40143. ],
  40144. "dpi": [
  40145. 240,
  40146. 247.5
  40147. ],
  40148. "bw": 3,
  40149. "ac": 1000
  40150. },
  40151. {
  40152. "type": "android",
  40153. "rules": [
  40154. {
  40155. "mdmh": "THL/*/thl 5000/*"
  40156. },
  40157. {
  40158. "ua": "thl 5000"
  40159. }
  40160. ],
  40161. "dpi": [
  40162. 480,
  40163. 443.3
  40164. ],
  40165. "bw": 3,
  40166. "ac": 1000
  40167. },
  40168. {
  40169. "type": "android",
  40170. "rules": [
  40171. {
  40172. "mdmh": "ZTE/*/ZTE Blade L2/*"
  40173. },
  40174. {
  40175. "ua": "ZTE Blade L2"
  40176. }
  40177. ],
  40178. "dpi": 240,
  40179. "bw": 3,
  40180. "ac": 500
  40181. },
  40182. {
  40183. "type": "ios",
  40184. "rules": [
  40185. {
  40186. "res": [
  40187. 640,
  40188. 960
  40189. ]
  40190. }
  40191. ],
  40192. "dpi": [
  40193. 325.1,
  40194. 328.4
  40195. ],
  40196. "bw": 4,
  40197. "ac": 1000
  40198. },
  40199. {
  40200. "type": "ios",
  40201. "rules": [
  40202. {
  40203. "res": [
  40204. 640,
  40205. 1136
  40206. ]
  40207. }
  40208. ],
  40209. "dpi": [
  40210. 317.1,
  40211. 320.2
  40212. ],
  40213. "bw": 3,
  40214. "ac": 1000
  40215. },
  40216. {
  40217. "type": "ios",
  40218. "rules": [
  40219. {
  40220. "res": [
  40221. 750,
  40222. 1334
  40223. ]
  40224. }
  40225. ],
  40226. "dpi": 326.4,
  40227. "bw": 4,
  40228. "ac": 1000
  40229. },
  40230. {
  40231. "type": "ios",
  40232. "rules": [
  40233. {
  40234. "res": [
  40235. 1242,
  40236. 2208
  40237. ]
  40238. }
  40239. ],
  40240. "dpi": [
  40241. 453.6,
  40242. 458.4
  40243. ],
  40244. "bw": 4,
  40245. "ac": 1000
  40246. },
  40247. {
  40248. "type": "ios",
  40249. "rules": [
  40250. {
  40251. "res": [
  40252. 1125,
  40253. 2001
  40254. ]
  40255. }
  40256. ],
  40257. "dpi": [
  40258. 410.9,
  40259. 415.4
  40260. ],
  40261. "bw": 4,
  40262. "ac": 1000
  40263. }
  40264. ]
  40265. }
  40266. },{}],57:[function(_dereq_,module,exports){
  40267. /*
  40268. * Copyright 2015 Google Inc. All Rights Reserved.
  40269. * Licensed under the Apache License, Version 2.0 (the "License");
  40270. * you may not use this file except in compliance with the License.
  40271. * You may obtain a copy of the License at
  40272. *
  40273. * http://www.apache.org/licenses/LICENSE-2.0
  40274. *
  40275. * Unless required by applicable law or agreed to in writing, software
  40276. * distributed under the License is distributed on an "AS IS" BASIS,
  40277. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40278. * See the License for the specific language governing permissions and
  40279. * limitations under the License.
  40280. */
  40281. // Offline cache of the DPDB, to be used until we load the online one (and
  40282. // as a fallback in case we can't load the online one).
  40283. var DPDB_CACHE = _dereq_('./dpdb.json');
  40284. var Util = _dereq_('../util.js');
  40285. // Online DPDB URL.
  40286. var ONLINE_DPDB_URL =
  40287. 'https://dpdb.webvr.rocks/dpdb.json';
  40288. /**
  40289. * Calculates device parameters based on the DPDB (Device Parameter Database).
  40290. * Initially, uses the cached DPDB values.
  40291. *
  40292. * If fetchOnline == true, then this object tries to fetch the online version
  40293. * of the DPDB and updates the device info if a better match is found.
  40294. * Calls the onDeviceParamsUpdated callback when there is an update to the
  40295. * device information.
  40296. */
  40297. function Dpdb(fetchOnline, onDeviceParamsUpdated) {
  40298. // Start with the offline DPDB cache while we are loading the real one.
  40299. this.dpdb = DPDB_CACHE;
  40300. // Calculate device params based on the offline version of the DPDB.
  40301. this.recalculateDeviceParams_();
  40302. // XHR to fetch online DPDB file, if requested.
  40303. if (fetchOnline) {
  40304. // Set the callback.
  40305. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  40306. var xhr = new XMLHttpRequest();
  40307. var obj = this;
  40308. xhr.open('GET', ONLINE_DPDB_URL, true);
  40309. xhr.addEventListener('load', function() {
  40310. obj.loading = false;
  40311. if (xhr.status >= 200 && xhr.status <= 299) {
  40312. // Success.
  40313. obj.dpdb = JSON.parse(xhr.response);
  40314. obj.recalculateDeviceParams_();
  40315. } else {
  40316. // Error loading the DPDB.
  40317. console.error('Error loading online DPDB!');
  40318. }
  40319. });
  40320. xhr.send();
  40321. }
  40322. }
  40323. // Returns the current device parameters.
  40324. Dpdb.prototype.getDeviceParams = function() {
  40325. return this.deviceParams;
  40326. };
  40327. // Recalculates this device's parameters based on the DPDB.
  40328. Dpdb.prototype.recalculateDeviceParams_ = function() {
  40329. var newDeviceParams = this.calcDeviceParams_();
  40330. if (newDeviceParams) {
  40331. this.deviceParams = newDeviceParams;
  40332. // Invoke callback, if it is set.
  40333. if (this.onDeviceParamsUpdated) {
  40334. this.onDeviceParamsUpdated(this.deviceParams);
  40335. }
  40336. } else {
  40337. console.error('Failed to recalculate device parameters.');
  40338. }
  40339. };
  40340. // Returns a DeviceParams object that represents the best guess as to this
  40341. // device's parameters. Can return null if the device does not match any
  40342. // known devices.
  40343. Dpdb.prototype.calcDeviceParams_ = function() {
  40344. var db = this.dpdb; // shorthand
  40345. if (!db) {
  40346. console.error('DPDB not available.');
  40347. return null;
  40348. }
  40349. if (db.format != 1) {
  40350. console.error('DPDB has unexpected format version.');
  40351. return null;
  40352. }
  40353. if (!db.devices || !db.devices.length) {
  40354. console.error('DPDB does not have a devices section.');
  40355. return null;
  40356. }
  40357. // Get the actual user agent and screen dimensions in pixels.
  40358. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  40359. var width = Util.getScreenWidth();
  40360. var height = Util.getScreenHeight();
  40361. if (!db.devices) {
  40362. console.error('DPDB has no devices section.');
  40363. return null;
  40364. }
  40365. for (var i = 0; i < db.devices.length; i++) {
  40366. var device = db.devices[i];
  40367. if (!device.rules) {
  40368. console.warn('Device[' + i + '] has no rules section.');
  40369. continue;
  40370. }
  40371. if (device.type != 'ios' && device.type != 'android') {
  40372. console.warn('Device[' + i + '] has invalid type.');
  40373. continue;
  40374. }
  40375. // See if this device is of the appropriate type.
  40376. if (Util.isIOS() != (device.type == 'ios')) continue;
  40377. // See if this device matches any of the rules:
  40378. var matched = false;
  40379. for (var j = 0; j < device.rules.length; j++) {
  40380. var rule = device.rules[j];
  40381. if (this.matchRule_(rule, userAgent, width, height)) {
  40382. matched = true;
  40383. break;
  40384. }
  40385. }
  40386. if (!matched) continue;
  40387. // device.dpi might be an array of [ xdpi, ydpi] or just a scalar.
  40388. var xdpi = device.dpi[0] || device.dpi;
  40389. var ydpi = device.dpi[1] || device.dpi;
  40390. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  40391. }
  40392. console.warn('No DPDB device match.');
  40393. return null;
  40394. };
  40395. Dpdb.prototype.matchRule_ = function(rule, ua, screenWidth, screenHeight) {
  40396. // We can only match 'ua' and 'res' rules, not other types like 'mdmh'
  40397. // (which are meant for native platforms).
  40398. if (!rule.ua && !rule.res) return false;
  40399. // If our user agent string doesn't contain the indicated user agent string,
  40400. // the match fails.
  40401. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  40402. // If the rule specifies screen dimensions that don't correspond to ours,
  40403. // the match fails.
  40404. if (rule.res) {
  40405. if (!rule.res[0] || !rule.res[1]) return false;
  40406. var resX = rule.res[0];
  40407. var resY = rule.res[1];
  40408. // Compare min and max so as to make the order not matter, i.e., it should
  40409. // be true that 640x480 == 480x640.
  40410. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) ||
  40411. (Math.max(screenWidth, screenHeight) != Math.max(resX, resY))) {
  40412. return false;
  40413. }
  40414. }
  40415. return true;
  40416. }
  40417. function DeviceParams(params) {
  40418. this.xdpi = params.xdpi;
  40419. this.ydpi = params.ydpi;
  40420. this.bevelMm = params.bevelMm;
  40421. }
  40422. module.exports = Dpdb;
  40423. },{"../util.js":68,"./dpdb.json":56}],58:[function(_dereq_,module,exports){
  40424. /*
  40425. * Copyright 2015 Google Inc. All Rights Reserved.
  40426. * Licensed under the Apache License, Version 2.0 (the "License");
  40427. * you may not use this file except in compliance with the License.
  40428. * You may obtain a copy of the License at
  40429. *
  40430. * http://www.apache.org/licenses/LICENSE-2.0
  40431. *
  40432. * Unless required by applicable law or agreed to in writing, software
  40433. * distributed under the License is distributed on an "AS IS" BASIS,
  40434. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40435. * See the License for the specific language governing permissions and
  40436. * limitations under the License.
  40437. */
  40438. var Util = _dereq_('./util.js');
  40439. var WebVRPolyfill = _dereq_('./webvr-polyfill.js').WebVRPolyfill;
  40440. // Initialize a WebVRConfig just in case.
  40441. window.WebVRConfig = Util.extend({
  40442. // Forces availability of VR mode, even for non-mobile devices.
  40443. FORCE_ENABLE_VR: false,
  40444. // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  40445. K_FILTER: 0.98,
  40446. // How far into the future to predict during fast motion (in seconds).
  40447. PREDICTION_TIME_S: 0.040,
  40448. // Flag to enable touch panner. In case you have your own touch controls.
  40449. TOUCH_PANNER_DISABLED: true,
  40450. // Flag to disabled the UI in VR Mode.
  40451. CARDBOARD_UI_DISABLED: false, // Default: false
  40452. // Flag to disable the instructions to rotate your device.
  40453. ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.
  40454. // Enable yaw panning only, disabling roll and pitch. This can be useful
  40455. // for panoramas with nothing interesting above or below.
  40456. YAW_ONLY: false,
  40457. // To disable keyboard and mouse controls, if you want to use your own
  40458. // implementation.
  40459. MOUSE_KEYBOARD_CONTROLS_DISABLED: false,
  40460. // Prevent the polyfill from initializing immediately. Requires the app
  40461. // to call InitializeWebVRPolyfill() before it can be used.
  40462. DEFER_INITIALIZATION: false,
  40463. // Enable the deprecated version of the API (navigator.getVRDevices).
  40464. ENABLE_DEPRECATED_API: false,
  40465. // Scales the recommended buffer size reported by WebVR, which can improve
  40466. // performance.
  40467. // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  40468. // perform well on many mobile devices.
  40469. BUFFER_SCALE: 0.5,
  40470. // Allow VRDisplay.submitFrame to change gl bindings, which is more
  40471. // efficient if the application code will re-bind its resources on the
  40472. // next frame anyway. This has been seen to cause rendering glitches with
  40473. // THREE.js.
  40474. // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  40475. // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  40476. // and gl.TEXTURE_BINDING_2D for texture unit 0.
  40477. DIRTY_SUBMIT_FRAME_BINDINGS: false,
  40478. // When set to true, this will cause a polyfilled VRDisplay to always be
  40479. // appended to the list returned by navigator.getVRDisplays(), even if that
  40480. // list includes a native VRDisplay.
  40481. ALWAYS_APPEND_POLYFILL_DISPLAY: false,
  40482. // There are versions of Chrome (M58-M60?) where the native WebVR API exists,
  40483. // and instead of returning 0 VR displays when none are detected,
  40484. // `navigator.getVRDisplays()`'s promise never resolves. This results
  40485. // in the polyfill hanging and not being able to provide fallback
  40486. // displays, so set a timeout in milliseconds to stop waiting for a response
  40487. // and just use polyfilled displays.
  40488. // https://bugs.chromium.org/p/chromium/issues/detail?id=727969
  40489. GET_VR_DISPLAYS_TIMEOUT: 1000,
  40490. }, window.WebVRConfig);
  40491. if (!window.WebVRConfig.DEFER_INITIALIZATION) {
  40492. new WebVRPolyfill();
  40493. } else {
  40494. window.InitializeWebVRPolyfill = function() {
  40495. new WebVRPolyfill();
  40496. }
  40497. }
  40498. window.WebVRPolyfill = WebVRPolyfill;
  40499. },{"./util.js":68,"./webvr-polyfill.js":71}],59:[function(_dereq_,module,exports){
  40500. /*
  40501. * Copyright 2016 Google Inc. All Rights Reserved.
  40502. * Licensed under the Apache License, Version 2.0 (the "License");
  40503. * you may not use this file except in compliance with the License.
  40504. * You may obtain a copy of the License at
  40505. *
  40506. * http://www.apache.org/licenses/LICENSE-2.0
  40507. *
  40508. * Unless required by applicable law or agreed to in writing, software
  40509. * distributed under the License is distributed on an "AS IS" BASIS,
  40510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40511. * See the License for the specific language governing permissions and
  40512. * limitations under the License.
  40513. */
  40514. var MathUtil = window.MathUtil || {};
  40515. MathUtil.degToRad = Math.PI / 180;
  40516. MathUtil.radToDeg = 180 / Math.PI;
  40517. // Some minimal math functionality borrowed from THREE.Math and stripped down
  40518. // for the purposes of this library.
  40519. MathUtil.Vector2 = function ( x, y ) {
  40520. this.x = x || 0;
  40521. this.y = y || 0;
  40522. };
  40523. MathUtil.Vector2.prototype = {
  40524. constructor: MathUtil.Vector2,
  40525. set: function ( x, y ) {
  40526. this.x = x;
  40527. this.y = y;
  40528. return this;
  40529. },
  40530. copy: function ( v ) {
  40531. this.x = v.x;
  40532. this.y = v.y;
  40533. return this;
  40534. },
  40535. subVectors: function ( a, b ) {
  40536. this.x = a.x - b.x;
  40537. this.y = a.y - b.y;
  40538. return this;
  40539. },
  40540. };
  40541. MathUtil.Vector3 = function ( x, y, z ) {
  40542. this.x = x || 0;
  40543. this.y = y || 0;
  40544. this.z = z || 0;
  40545. };
  40546. MathUtil.Vector3.prototype = {
  40547. constructor: MathUtil.Vector3,
  40548. set: function ( x, y, z ) {
  40549. this.x = x;
  40550. this.y = y;
  40551. this.z = z;
  40552. return this;
  40553. },
  40554. copy: function ( v ) {
  40555. this.x = v.x;
  40556. this.y = v.y;
  40557. this.z = v.z;
  40558. return this;
  40559. },
  40560. length: function () {
  40561. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  40562. },
  40563. normalize: function () {
  40564. var scalar = this.length();
  40565. if ( scalar !== 0 ) {
  40566. var invScalar = 1 / scalar;
  40567. this.multiplyScalar(invScalar);
  40568. } else {
  40569. this.x = 0;
  40570. this.y = 0;
  40571. this.z = 0;
  40572. }
  40573. return this;
  40574. },
  40575. multiplyScalar: function ( scalar ) {
  40576. this.x *= scalar;
  40577. this.y *= scalar;
  40578. this.z *= scalar;
  40579. },
  40580. applyQuaternion: function ( q ) {
  40581. var x = this.x;
  40582. var y = this.y;
  40583. var z = this.z;
  40584. var qx = q.x;
  40585. var qy = q.y;
  40586. var qz = q.z;
  40587. var qw = q.w;
  40588. // calculate quat * vector
  40589. var ix = qw * x + qy * z - qz * y;
  40590. var iy = qw * y + qz * x - qx * z;
  40591. var iz = qw * z + qx * y - qy * x;
  40592. var iw = - qx * x - qy * y - qz * z;
  40593. // calculate result * inverse quat
  40594. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  40595. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  40596. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  40597. return this;
  40598. },
  40599. dot: function ( v ) {
  40600. return this.x * v.x + this.y * v.y + this.z * v.z;
  40601. },
  40602. crossVectors: function ( a, b ) {
  40603. var ax = a.x, ay = a.y, az = a.z;
  40604. var bx = b.x, by = b.y, bz = b.z;
  40605. this.x = ay * bz - az * by;
  40606. this.y = az * bx - ax * bz;
  40607. this.z = ax * by - ay * bx;
  40608. return this;
  40609. },
  40610. };
  40611. MathUtil.Quaternion = function ( x, y, z, w ) {
  40612. this.x = x || 0;
  40613. this.y = y || 0;
  40614. this.z = z || 0;
  40615. this.w = ( w !== undefined ) ? w : 1;
  40616. };
  40617. MathUtil.Quaternion.prototype = {
  40618. constructor: MathUtil.Quaternion,
  40619. set: function ( x, y, z, w ) {
  40620. this.x = x;
  40621. this.y = y;
  40622. this.z = z;
  40623. this.w = w;
  40624. return this;
  40625. },
  40626. copy: function ( quaternion ) {
  40627. this.x = quaternion.x;
  40628. this.y = quaternion.y;
  40629. this.z = quaternion.z;
  40630. this.w = quaternion.w;
  40631. return this;
  40632. },
  40633. setFromEulerXYZ: function( x, y, z ) {
  40634. var c1 = Math.cos( x / 2 );
  40635. var c2 = Math.cos( y / 2 );
  40636. var c3 = Math.cos( z / 2 );
  40637. var s1 = Math.sin( x / 2 );
  40638. var s2 = Math.sin( y / 2 );
  40639. var s3 = Math.sin( z / 2 );
  40640. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40641. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40642. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  40643. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  40644. return this;
  40645. },
  40646. setFromEulerYXZ: function( x, y, z ) {
  40647. var c1 = Math.cos( x / 2 );
  40648. var c2 = Math.cos( y / 2 );
  40649. var c3 = Math.cos( z / 2 );
  40650. var s1 = Math.sin( x / 2 );
  40651. var s2 = Math.sin( y / 2 );
  40652. var s3 = Math.sin( z / 2 );
  40653. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40654. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40655. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  40656. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  40657. return this;
  40658. },
  40659. setFromAxisAngle: function ( axis, angle ) {
  40660. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  40661. // assumes axis is normalized
  40662. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  40663. this.x = axis.x * s;
  40664. this.y = axis.y * s;
  40665. this.z = axis.z * s;
  40666. this.w = Math.cos( halfAngle );
  40667. return this;
  40668. },
  40669. multiply: function ( q ) {
  40670. return this.multiplyQuaternions( this, q );
  40671. },
  40672. multiplyQuaternions: function ( a, b ) {
  40673. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  40674. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  40675. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  40676. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  40677. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  40678. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  40679. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  40680. return this;
  40681. },
  40682. inverse: function () {
  40683. this.x *= -1;
  40684. this.y *= -1;
  40685. this.z *= -1;
  40686. this.normalize();
  40687. return this;
  40688. },
  40689. normalize: function () {
  40690. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  40691. if ( l === 0 ) {
  40692. this.x = 0;
  40693. this.y = 0;
  40694. this.z = 0;
  40695. this.w = 1;
  40696. } else {
  40697. l = 1 / l;
  40698. this.x = this.x * l;
  40699. this.y = this.y * l;
  40700. this.z = this.z * l;
  40701. this.w = this.w * l;
  40702. }
  40703. return this;
  40704. },
  40705. slerp: function ( qb, t ) {
  40706. if ( t === 0 ) return this;
  40707. if ( t === 1 ) return this.copy( qb );
  40708. var x = this.x, y = this.y, z = this.z, w = this.w;
  40709. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  40710. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  40711. if ( cosHalfTheta < 0 ) {
  40712. this.w = - qb.w;
  40713. this.x = - qb.x;
  40714. this.y = - qb.y;
  40715. this.z = - qb.z;
  40716. cosHalfTheta = - cosHalfTheta;
  40717. } else {
  40718. this.copy( qb );
  40719. }
  40720. if ( cosHalfTheta >= 1.0 ) {
  40721. this.w = w;
  40722. this.x = x;
  40723. this.y = y;
  40724. this.z = z;
  40725. return this;
  40726. }
  40727. var halfTheta = Math.acos( cosHalfTheta );
  40728. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  40729. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  40730. this.w = 0.5 * ( w + this.w );
  40731. this.x = 0.5 * ( x + this.x );
  40732. this.y = 0.5 * ( y + this.y );
  40733. this.z = 0.5 * ( z + this.z );
  40734. return this;
  40735. }
  40736. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  40737. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  40738. this.w = ( w * ratioA + this.w * ratioB );
  40739. this.x = ( x * ratioA + this.x * ratioB );
  40740. this.y = ( y * ratioA + this.y * ratioB );
  40741. this.z = ( z * ratioA + this.z * ratioB );
  40742. return this;
  40743. },
  40744. setFromUnitVectors: function () {
  40745. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  40746. // assumes direction vectors vFrom and vTo are normalized
  40747. var v1, r;
  40748. var EPS = 0.000001;
  40749. return function ( vFrom, vTo ) {
  40750. if ( v1 === undefined ) v1 = new MathUtil.Vector3();
  40751. r = vFrom.dot( vTo ) + 1;
  40752. if ( r < EPS ) {
  40753. r = 0;
  40754. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  40755. v1.set( - vFrom.y, vFrom.x, 0 );
  40756. } else {
  40757. v1.set( 0, - vFrom.z, vFrom.y );
  40758. }
  40759. } else {
  40760. v1.crossVectors( vFrom, vTo );
  40761. }
  40762. this.x = v1.x;
  40763. this.y = v1.y;
  40764. this.z = v1.z;
  40765. this.w = r;
  40766. this.normalize();
  40767. return this;
  40768. }
  40769. }(),
  40770. };
  40771. module.exports = MathUtil;
  40772. },{}],60:[function(_dereq_,module,exports){
  40773. /*
  40774. * Copyright 2016 Google Inc. All Rights Reserved.
  40775. * Licensed under the Apache License, Version 2.0 (the "License");
  40776. * you may not use this file except in compliance with the License.
  40777. * You may obtain a copy of the License at
  40778. *
  40779. * http://www.apache.org/licenses/LICENSE-2.0
  40780. *
  40781. * Unless required by applicable law or agreed to in writing, software
  40782. * distributed under the License is distributed on an "AS IS" BASIS,
  40783. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40784. * See the License for the specific language governing permissions and
  40785. * limitations under the License.
  40786. */
  40787. var VRDisplay = _dereq_('./base.js').VRDisplay;
  40788. var MathUtil = _dereq_('./math-util.js');
  40789. var Util = _dereq_('./util.js');
  40790. // How much to rotate per key stroke.
  40791. var KEY_SPEED = 0.15;
  40792. var KEY_ANIMATION_DURATION = 80;
  40793. // How much to rotate for mouse events.
  40794. var MOUSE_SPEED_X = 0.5;
  40795. var MOUSE_SPEED_Y = 0.3;
  40796. /**
  40797. * VRDisplay based on mouse and keyboard input. Designed for desktops/laptops
  40798. * where orientation events aren't supported. Cannot present.
  40799. */
  40800. function MouseKeyboardVRDisplay() {
  40801. this.displayName = 'Mouse and Keyboard VRDisplay (webvr-polyfill)';
  40802. this.capabilities.hasOrientation = true;
  40803. // Attach to mouse and keyboard events.
  40804. window.addEventListener('keydown', this.onKeyDown_.bind(this));
  40805. window.addEventListener('mousemove', this.onMouseMove_.bind(this));
  40806. window.addEventListener('mousedown', this.onMouseDown_.bind(this));
  40807. window.addEventListener('mouseup', this.onMouseUp_.bind(this));
  40808. // "Private" members.
  40809. this.phi_ = 0;
  40810. this.theta_ = 0;
  40811. // Variables for keyboard-based rotation animation.
  40812. this.targetAngle_ = null;
  40813. this.angleAnimation_ = null;
  40814. // State variables for calculations.
  40815. this.orientation_ = new MathUtil.Quaternion();
  40816. // Variables for mouse-based rotation.
  40817. this.rotateStart_ = new MathUtil.Vector2();
  40818. this.rotateEnd_ = new MathUtil.Vector2();
  40819. this.rotateDelta_ = new MathUtil.Vector2();
  40820. this.isDragging_ = false;
  40821. this.orientationOut_ = new Float32Array(4);
  40822. }
  40823. MouseKeyboardVRDisplay.prototype = new VRDisplay();
  40824. MouseKeyboardVRDisplay.prototype.getImmediatePose = function() {
  40825. this.orientation_.setFromEulerYXZ(this.phi_, this.theta_, 0);
  40826. this.orientationOut_[0] = this.orientation_.x;
  40827. this.orientationOut_[1] = this.orientation_.y;
  40828. this.orientationOut_[2] = this.orientation_.z;
  40829. this.orientationOut_[3] = this.orientation_.w;
  40830. return {
  40831. position: null,
  40832. orientation: this.orientationOut_,
  40833. linearVelocity: null,
  40834. linearAcceleration: null,
  40835. angularVelocity: null,
  40836. angularAcceleration: null
  40837. };
  40838. };
  40839. MouseKeyboardVRDisplay.prototype.onKeyDown_ = function(e) {
  40840. // Track WASD and arrow keys.
  40841. if (e.keyCode == 38) { // Up key.
  40842. this.animatePhi_(this.phi_ + KEY_SPEED);
  40843. } else if (e.keyCode == 39) { // Right key.
  40844. this.animateTheta_(this.theta_ - KEY_SPEED);
  40845. } else if (e.keyCode == 40) { // Down key.
  40846. this.animatePhi_(this.phi_ - KEY_SPEED);
  40847. } else if (e.keyCode == 37) { // Left key.
  40848. this.animateTheta_(this.theta_ + KEY_SPEED);
  40849. }
  40850. };
  40851. MouseKeyboardVRDisplay.prototype.animateTheta_ = function(targetAngle) {
  40852. this.animateKeyTransitions_('theta_', targetAngle);
  40853. };
  40854. MouseKeyboardVRDisplay.prototype.animatePhi_ = function(targetAngle) {
  40855. // Prevent looking too far up or down.
  40856. targetAngle = Util.clamp(targetAngle, -Math.PI/2, Math.PI/2);
  40857. this.animateKeyTransitions_('phi_', targetAngle);
  40858. };
  40859. /**
  40860. * Start an animation to transition an angle from one value to another.
  40861. */
  40862. MouseKeyboardVRDisplay.prototype.animateKeyTransitions_ = function(angleName, targetAngle) {
  40863. // If an animation is currently running, cancel it.
  40864. if (this.angleAnimation_) {
  40865. cancelAnimationFrame(this.angleAnimation_);
  40866. }
  40867. var startAngle = this[angleName];
  40868. var startTime = new Date();
  40869. // Set up an interval timer to perform the animation.
  40870. this.angleAnimation_ = requestAnimationFrame(function animate() {
  40871. // Once we're finished the animation, we're done.
  40872. var elapsed = new Date() - startTime;
  40873. if (elapsed >= KEY_ANIMATION_DURATION) {
  40874. this[angleName] = targetAngle;
  40875. cancelAnimationFrame(this.angleAnimation_);
  40876. return;
  40877. }
  40878. // loop with requestAnimationFrame
  40879. this.angleAnimation_ = requestAnimationFrame(animate.bind(this))
  40880. // Linearly interpolate the angle some amount.
  40881. var percent = elapsed / KEY_ANIMATION_DURATION;
  40882. this[angleName] = startAngle + (targetAngle - startAngle) * percent;
  40883. }.bind(this));
  40884. };
  40885. MouseKeyboardVRDisplay.prototype.onMouseDown_ = function(e) {
  40886. this.rotateStart_.set(e.clientX, e.clientY);
  40887. this.isDragging_ = true;
  40888. };
  40889. // Very similar to https://gist.github.com/mrflix/8351020
  40890. MouseKeyboardVRDisplay.prototype.onMouseMove_ = function(e) {
  40891. if (!this.isDragging_ && !this.isPointerLocked_()) {
  40892. return;
  40893. }
  40894. // Support pointer lock API.
  40895. if (this.isPointerLocked_()) {
  40896. var movementX = e.movementX || e.mozMovementX || 0;
  40897. var movementY = e.movementY || e.mozMovementY || 0;
  40898. this.rotateEnd_.set(this.rotateStart_.x - movementX, this.rotateStart_.y - movementY);
  40899. } else {
  40900. this.rotateEnd_.set(e.clientX, e.clientY);
  40901. }
  40902. // Calculate how much we moved in mouse space.
  40903. this.rotateDelta_.subVectors(this.rotateEnd_, this.rotateStart_);
  40904. this.rotateStart_.copy(this.rotateEnd_);
  40905. // Keep track of the cumulative euler angles.
  40906. this.phi_ += 2 * Math.PI * this.rotateDelta_.y / screen.height * MOUSE_SPEED_Y;
  40907. this.theta_ += 2 * Math.PI * this.rotateDelta_.x / screen.width * MOUSE_SPEED_X;
  40908. // Prevent looking too far up or down.
  40909. this.phi_ = Util.clamp(this.phi_, -Math.PI/2, Math.PI/2);
  40910. };
  40911. MouseKeyboardVRDisplay.prototype.onMouseUp_ = function(e) {
  40912. this.isDragging_ = false;
  40913. };
  40914. MouseKeyboardVRDisplay.prototype.isPointerLocked_ = function() {
  40915. var el = document.pointerLockElement || document.mozPointerLockElement ||
  40916. document.webkitPointerLockElement;
  40917. return el !== undefined;
  40918. };
  40919. MouseKeyboardVRDisplay.prototype.resetPose = function() {
  40920. this.phi_ = 0;
  40921. this.theta_ = 0;
  40922. };
  40923. module.exports = MouseKeyboardVRDisplay;
  40924. },{"./base.js":48,"./math-util.js":59,"./util.js":68}],61:[function(_dereq_,module,exports){
  40925. (function (global){
  40926. // This is the entry point if requiring/importing via node, or
  40927. // a build tool that uses package.json entry (like browserify, webpack).
  40928. // If running in node with a window mock available, globalize its members
  40929. // if needed. Otherwise, just continue to `./main`
  40930. if (typeof global !== 'undefined' && global.window) {
  40931. global.document = global.window.document;
  40932. global.navigator = global.window.navigator;
  40933. }
  40934. _dereq_('./main');
  40935. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40936. },{"./main":58}],62:[function(_dereq_,module,exports){
  40937. /*
  40938. * Copyright 2015 Google Inc. All Rights Reserved.
  40939. * Licensed under the Apache License, Version 2.0 (the "License");
  40940. * you may not use this file except in compliance with the License.
  40941. * You may obtain a copy of the License at
  40942. *
  40943. * http://www.apache.org/licenses/LICENSE-2.0
  40944. *
  40945. * Unless required by applicable law or agreed to in writing, software
  40946. * distributed under the License is distributed on an "AS IS" BASIS,
  40947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40948. * See the License for the specific language governing permissions and
  40949. * limitations under the License.
  40950. */
  40951. var Util = _dereq_('./util.js');
  40952. function RotateInstructions() {
  40953. this.loadIcon_();
  40954. var overlay = document.createElement('div');
  40955. var s = overlay.style;
  40956. s.position = 'fixed';
  40957. s.top = 0;
  40958. s.right = 0;
  40959. s.bottom = 0;
  40960. s.left = 0;
  40961. s.backgroundColor = 'gray';
  40962. s.fontFamily = 'sans-serif';
  40963. // Force this to be above the fullscreen canvas, which is at zIndex: 999999.
  40964. s.zIndex = 1000000;
  40965. var img = document.createElement('img');
  40966. img.src = this.icon;
  40967. var s = img.style;
  40968. s.marginLeft = '25%';
  40969. s.marginTop = '25%';
  40970. s.width = '50%';
  40971. overlay.appendChild(img);
  40972. var text = document.createElement('div');
  40973. var s = text.style;
  40974. s.textAlign = 'center';
  40975. s.fontSize = '16px';
  40976. s.lineHeight = '24px';
  40977. s.margin = '24px 25%';
  40978. s.width = '50%';
  40979. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  40980. overlay.appendChild(text);
  40981. var snackbar = document.createElement('div');
  40982. var s = snackbar.style;
  40983. s.backgroundColor = '#CFD8DC';
  40984. s.position = 'fixed';
  40985. s.bottom = 0;
  40986. s.width = '100%';
  40987. s.height = '48px';
  40988. s.padding = '14px 24px';
  40989. s.boxSizing = 'border-box';
  40990. s.color = '#656A6B';
  40991. overlay.appendChild(snackbar);
  40992. var snackbarText = document.createElement('div');
  40993. snackbarText.style.float = 'left';
  40994. snackbarText.innerHTML = 'No Cardboard viewer?';
  40995. var snackbarButton = document.createElement('a');
  40996. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  40997. snackbarButton.innerHTML = 'get one';
  40998. snackbarButton.target = '_blank';
  40999. var s = snackbarButton.style;
  41000. s.float = 'right';
  41001. s.fontWeight = 600;
  41002. s.textTransform = 'uppercase';
  41003. s.borderLeft = '1px solid gray';
  41004. s.paddingLeft = '24px';
  41005. s.textDecoration = 'none';
  41006. s.color = '#656A6B';
  41007. snackbar.appendChild(snackbarText);
  41008. snackbar.appendChild(snackbarButton);
  41009. this.overlay = overlay;
  41010. this.text = text;
  41011. this.hide();
  41012. }
  41013. RotateInstructions.prototype.show = function(parent) {
  41014. if (!parent && !this.overlay.parentElement) {
  41015. document.body.appendChild(this.overlay);
  41016. } else if (parent) {
  41017. if (this.overlay.parentElement && this.overlay.parentElement != parent)
  41018. this.overlay.parentElement.removeChild(this.overlay);
  41019. parent.appendChild(this.overlay);
  41020. }
  41021. this.overlay.style.display = 'block';
  41022. var img = this.overlay.querySelector('img');
  41023. var s = img.style;
  41024. if (Util.isLandscapeMode()) {
  41025. s.width = '20%';
  41026. s.marginLeft = '40%';
  41027. s.marginTop = '3%';
  41028. } else {
  41029. s.width = '50%';
  41030. s.marginLeft = '25%';
  41031. s.marginTop = '25%';
  41032. }
  41033. };
  41034. RotateInstructions.prototype.hide = function() {
  41035. this.overlay.style.display = 'none';
  41036. };
  41037. RotateInstructions.prototype.showTemporarily = function(ms, parent) {
  41038. this.show(parent);
  41039. this.timer = setTimeout(this.hide.bind(this), ms);
  41040. };
  41041. RotateInstructions.prototype.disableShowTemporarily = function() {
  41042. clearTimeout(this.timer);
  41043. };
  41044. RotateInstructions.prototype.update = function() {
  41045. this.disableShowTemporarily();
  41046. // In portrait VR mode, tell the user to rotate to landscape. Otherwise, hide
  41047. // the instructions.
  41048. if (!Util.isLandscapeMode() && Util.isMobile()) {
  41049. this.show();
  41050. } else {
  41051. this.hide();
  41052. }
  41053. };
  41054. RotateInstructions.prototype.loadIcon_ = function() {
  41055. // Encoded asset_src/rotate-instructions.svg
  41056. this.icon = Util.base64('image/svg+xml', 'PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjE5OHB4IiBoZWlnaHQ9IjI0MHB4IiB2aWV3Qm94PSIwIDAgMTk4IDI0MCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpza2V0Y2g9Imh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaC9ucyI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDMuMy4zICgxMjA4MSkgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+dHJhbnNpdGlvbjwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJ0cmFuc2l0aW9uIiBza2V0Y2g6dHlwZT0iTVNBcnRib2FyZEdyb3VwIj4KICAgICAgICAgICAgPGcgaWQ9IkltcG9ydGVkLUxheWVycy1Db3B5LTQtKy1JbXBvcnRlZC1MYXllcnMtQ29weS0rLUltcG9ydGVkLUxheWVycy1Db3B5LTItQ29weSIgc2tldGNoOnR5cGU9Ik1TTGF5ZXJHcm91cCI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iSW1wb3J0ZWQtTGF5ZXJzLUNvcHktNCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsIDEwNy4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ5LjYyNSwyLjUyNyBDMTQ5LjYyNSwyLjUyNyAxNTUuODA1LDYuMDk2IDE1Ni4zNjIsNi40MTggTDE1Ni4zNjIsNy4zMDQgQzE1Ni4zNjIsNy40ODEgMTU2LjM3NSw3LjY2NCAxNTYuNCw3Ljg1MyBDMTU2LjQxLDcuOTM0IDE1Ni40Miw4LjAxNSAxNTYuNDI3LDguMDk1IEMxNTYuNTY3LDkuNTEgMTU3LjQwMSwxMS4wOTMgMTU4LjUzMiwxMi4wOTQgTDE2NC4yNTIsMTcuMTU2IEwxNjQuMzMzLDE3LjA2NiBDMTY0LjMzMywxNy4wNjYgMTY4LjcxNSwxNC41MzYgMTY5LjU2OCwxNC4wNDIgQzE3MS4wMjUsMTQuODgzIDE5NS41MzgsMjkuMDM1IDE5NS41MzgsMjkuMDM1IEwxOTUuNTM4LDgzLjAzNiBDMTk1LjUzOCw4My44MDcgMTk1LjE1Miw4NC4yNTMgMTk0LjU5LDg0LjI1MyBDMTk0LjM1Nyw4NC4yNTMgMTk0LjA5NSw4NC4xNzcgMTkzLjgxOCw4NC4wMTcgTDE2OS44NTEsNzAuMTc5IEwxNjkuODM3LDcwLjIwMyBMMTQyLjUxNSw4NS45NzggTDE0MS42NjUsODQuNjU1IEMxMzYuOTM0LDgzLjEyNiAxMzEuOTE3LDgxLjkxNSAxMjYuNzE0LDgxLjA0NSBDMTI2LjcwOSw4MS4wNiAxMjYuNzA3LDgxLjA2OSAxMjYuNzA3LDgxLjA2OSBMMTIxLjY0LDk4LjAzIEwxMTMuNzQ5LDEwMi41ODYgTDExMy43MTIsMTAyLjUyMyBMMTEzLjcxMiwxMzAuMTEzIEMxMTMuNzEyLDEzMC44ODUgMTEzLjMyNiwxMzEuMzMgMTEyLjc2NCwxMzEuMzMgQzExMi41MzIsMTMxLjMzIDExMi4yNjksMTMxLjI1NCAxMTEuOTkyLDEzMS4wOTQgTDY5LjUxOSwxMDYuNTcyIEM2OC41NjksMTA2LjAyMyA2Ny43OTksMTA0LjY5NSA2Ny43OTksMTAzLjYwNSBMNjcuNzk5LDEwMi41NyBMNjcuNzc4LDEwMi42MTcgQzY3LjI3LDEwMi4zOTMgNjYuNjQ4LDEwMi4yNDkgNjUuOTYyLDEwMi4yMTggQzY1Ljg3NSwxMDIuMjE0IDY1Ljc4OCwxMDIuMjEyIDY1LjcwMSwxMDIuMjEyIEM2NS42MDYsMTAyLjIxMiA2NS41MTEsMTAyLjIxNSA2NS40MTYsMTAyLjIxOSBDNjUuMTk1LDEwMi4yMjkgNjQuOTc0LDEwMi4yMzUgNjQuNzU0LDEwMi4yMzUgQzY0LjMzMSwxMDIuMjM1IDYzLjkxMSwxMDIuMjE2IDYzLjQ5OCwxMDIuMTc4IEM2MS44NDMsMTAyLjAyNSA2MC4yOTgsMTAxLjU3OCA1OS4wOTQsMTAwLjg4MiBMMTIuNTE4LDczLjk5MiBMMTIuNTIzLDc0LjAwNCBMMi4yNDUsNTUuMjU0IEMxLjI0NCw1My40MjcgMi4wMDQsNTEuMDM4IDMuOTQzLDQ5LjkxOCBMNTkuOTU0LDE3LjU3MyBDNjAuNjI2LDE3LjE4NSA2MS4zNSwxNy4wMDEgNjIuMDUzLDE3LjAwMSBDNjMuMzc5LDE3LjAwMSA2NC42MjUsMTcuNjYgNjUuMjgsMTguODU0IEw2NS4yODUsMTguODUxIEw2NS41MTIsMTkuMjY0IEw2NS41MDYsMTkuMjY4IEM2NS45MDksMjAuMDAzIDY2LjQwNSwyMC42OCA2Ni45ODMsMjEuMjg2IEw2Ny4yNiwyMS41NTYgQzY5LjE3NCwyMy40MDYgNzEuNzI4LDI0LjM1NyA3NC4zNzMsMjQuMzU3IEM3Ni4zMjIsMjQuMzU3IDc4LjMyMSwyMy44NCA4MC4xNDgsMjIuNzg1IEM4MC4xNjEsMjIuNzg1IDg3LjQ2NywxOC41NjYgODcuNDY3LDE4LjU2NiBDODguMTM5LDE4LjE3OCA4OC44NjMsMTcuOTk0IDg5LjU2NiwxNy45OTQgQzkwLjg5MiwxNy45OTQgOTIuMTM4LDE4LjY1MiA5Mi43OTIsMTkuODQ3IEw5Ni4wNDIsMjUuNzc1IEw5Ni4wNjQsMjUuNzU3IEwxMDIuODQ5LDI5LjY3NCBMMTAyLjc0NCwyOS40OTIgTDE0OS42MjUsMi41MjcgTTE0OS42MjUsMC44OTIgQzE0OS4zNDMsMC44OTIgMTQ5LjA2MiwwLjk2NSAxNDguODEsMS4xMSBMMTAyLjY0MSwyNy42NjYgTDk3LjIzMSwyNC41NDIgTDk0LjIyNiwxOS4wNjEgQzkzLjMxMywxNy4zOTQgOTEuNTI3LDE2LjM1OSA4OS41NjYsMTYuMzU4IEM4OC41NTUsMTYuMzU4IDg3LjU0NiwxNi42MzIgODYuNjQ5LDE3LjE1IEM4My44NzgsMTguNzUgNzkuNjg3LDIxLjE2OSA3OS4zNzQsMjEuMzQ1IEM3OS4zNTksMjEuMzUzIDc5LjM0NSwyMS4zNjEgNzkuMzMsMjEuMzY5IEM3Ny43OTgsMjIuMjU0IDc2LjA4NCwyMi43MjIgNzQuMzczLDIyLjcyMiBDNzIuMDgxLDIyLjcyMiA2OS45NTksMjEuODkgNjguMzk3LDIwLjM4IEw2OC4xNDUsMjAuMTM1IEM2Ny43MDYsMTkuNjcyIDY3LjMyMywxOS4xNTYgNjcuMDA2LDE4LjYwMSBDNjYuOTg4LDE4LjU1OSA2Ni45NjgsMTguNTE5IDY2Ljk0NiwxOC40NzkgTDY2LjcxOSwxOC4wNjUgQzY2LjY5LDE4LjAxMiA2Ni42NTgsMTcuOTYgNjYuNjI0LDE3LjkxMSBDNjUuNjg2LDE2LjMzNyA2My45NTEsMTUuMzY2IDYyLjA1MywxNS4zNjYgQzYxLjA0MiwxNS4zNjYgNjAuMDMzLDE1LjY0IDU5LjEzNiwxNi4xNTggTDMuMTI1LDQ4LjUwMiBDMC40MjYsNTAuMDYxIC0wLjYxMyw1My40NDIgMC44MTEsNTYuMDQgTDExLjA4OSw3NC43OSBDMTEuMjY2LDc1LjExMyAxMS41MzcsNzUuMzUzIDExLjg1LDc1LjQ5NCBMNTguMjc2LDEwMi4yOTggQzU5LjY3OSwxMDMuMTA4IDYxLjQzMywxMDMuNjMgNjMuMzQ4LDEwMy44MDYgQzYzLjgxMiwxMDMuODQ4IDY0LjI4NSwxMDMuODcgNjQuNzU0LDEwMy44NyBDNjUsMTAzLjg3IDY1LjI0OSwxMDMuODY0IDY1LjQ5NCwxMDMuODUyIEM2NS41NjMsMTAzLjg0OSA2NS42MzIsMTAzLjg0NyA2NS43MDEsMTAzLjg0NyBDNjUuNzY0LDEwMy44NDcgNjUuODI4LDEwMy44NDkgNjUuODksMTAzLjg1MiBDNjUuOTg2LDEwMy44NTYgNjYuMDgsMTAzLjg2MyA2Ni4xNzMsMTAzLjg3NCBDNjYuMjgyLDEwNS40NjcgNjcuMzMyLDEwNy4xOTcgNjguNzAyLDEwNy45ODggTDExMS4xNzQsMTMyLjUxIEMxMTEuNjk4LDEzMi44MTIgMTEyLjIzMiwxMzIuOTY1IDExMi43NjQsMTMyLjk2NSBDMTE0LjI2MSwxMzIuOTY1IDExNS4zNDcsMTMxLjc2NSAxMTUuMzQ3LDEzMC4xMTMgTDExNS4zNDcsMTAzLjU1MSBMMTIyLjQ1OCw5OS40NDYgQzEyMi44MTksOTkuMjM3IDEyMy4wODcsOTguODk4IDEyMy4yMDcsOTguNDk4IEwxMjcuODY1LDgyLjkwNSBDMTMyLjI3OSw4My43MDIgMTM2LjU1Nyw4NC43NTMgMTQwLjYwNyw4Ni4wMzMgTDE0MS4xNCw4Ni44NjIgQzE0MS40NTEsODcuMzQ2IDE0MS45NzcsODcuNjEzIDE0Mi41MTYsODcuNjEzIEMxNDIuNzk0LDg3LjYxMyAxNDMuMDc2LDg3LjU0MiAxNDMuMzMzLDg3LjM5MyBMMTY5Ljg2NSw3Mi4wNzYgTDE5Myw4NS40MzMgQzE5My41MjMsODUuNzM1IDE5NC4wNTgsODUuODg4IDE5NC41OSw4NS44ODggQzE5Ni4wODcsODUuODg4IDE5Ny4xNzMsODQuNjg5IDE5Ny4xNzMsODMuMDM2IEwxOTcuMTczLDI5LjAzNSBDMTk3LjE3MywyOC40NTEgMTk2Ljg2MSwyNy45MTEgMTk2LjM1NSwyNy42MTkgQzE5Ni4zNTUsMjcuNjE5IDE3MS44NDMsMTMuNDY3IDE3MC4zODUsMTIuNjI2IEMxNzAuMTMyLDEyLjQ4IDE2OS44NSwxMi40MDcgMTY5LjU2OCwxMi40MDcgQzE2OS4yODUsMTIuNDA3IDE2OS4wMDIsMTIuNDgxIDE2OC43NDksMTIuNjI3IEMxNjguMTQzLDEyLjk3OCAxNjUuNzU2LDE0LjM1NyAxNjQuNDI0LDE1LjEyNSBMMTU5LjYxNSwxMC44NyBDMTU4Ljc5NiwxMC4xNDUgMTU4LjE1NCw4LjkzNyAxNTguMDU0LDcuOTM0IEMxNTguMDQ1LDcuODM3IDE1OC4wMzQsNy43MzkgMTU4LjAyMSw3LjY0IEMxNTguMDA1LDcuNTIzIDE1Ny45OTgsNy40MSAxNTcuOTk4LDcuMzA0IEwxNTcuOTk4LDYuNDE4IEMxNTcuOTk4LDUuODM0IDE1Ny42ODYsNS4yOTUgMTU3LjE4MSw1LjAwMiBDMTU2LjYyNCw0LjY4IDE1MC40NDIsMS4xMTEgMTUwLjQ0MiwxLjExMSBDMTUwLjE4OSwwLjk2NSAxNDkuOTA3LDAuODkyIDE0OS42MjUsMC44OTIiIGlkPSJGaWxsLTEiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTYuMDI3LDI1LjYzNiBMMTQyLjYwMyw1Mi41MjcgQzE0My44MDcsNTMuMjIyIDE0NC41ODIsNTQuMTE0IDE0NC44NDUsNTUuMDY4IEwxNDQuODM1LDU1LjA3NSBMNjMuNDYxLDEwMi4wNTcgTDYzLjQ2LDEwMi4wNTcgQzYxLjgwNiwxMDEuOTA1IDYwLjI2MSwxMDEuNDU3IDU5LjA1NywxMDAuNzYyIEwxMi40ODEsNzMuODcxIEw5Ni4wMjcsMjUuNjM2IiBpZD0iRmlsbC0yIiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTYzLjQ2MSwxMDIuMTc0IEM2My40NTMsMTAyLjE3NCA2My40NDYsMTAyLjE3NCA2My40MzksMTAyLjE3MiBDNjEuNzQ2LDEwMi4wMTYgNjAuMjExLDEwMS41NjMgNTguOTk4LDEwMC44NjMgTDEyLjQyMiw3My45NzMgQzEyLjM4Niw3My45NTIgMTIuMzY0LDczLjkxNCAxMi4zNjQsNzMuODcxIEMxMi4zNjQsNzMuODMgMTIuMzg2LDczLjc5MSAxMi40MjIsNzMuNzcgTDk1Ljk2OCwyNS41MzUgQzk2LjAwNCwyNS41MTQgOTYuMDQ5LDI1LjUxNCA5Ni4wODUsMjUuNTM1IEwxNDIuNjYxLDUyLjQyNiBDMTQzLjg4OCw1My4xMzQgMTQ0LjY4Miw1NC4wMzggMTQ0Ljk1Nyw1NS4wMzcgQzE0NC45Nyw1NS4wODMgMTQ0Ljk1Myw1NS4xMzMgMTQ0LjkxNSw1NS4xNjEgQzE0NC45MTEsNTUuMTY1IDE0NC44OTgsNTUuMTc0IDE0NC44OTQsNTUuMTc3IEw2My41MTksMTAyLjE1OCBDNjMuNTAxLDEwMi4xNjkgNjMuNDgxLDEwMi4xNzQgNjMuNDYxLDEwMi4xNzQgTDYzLjQ2MSwxMDIuMTc0IFogTTEyLjcxNCw3My44NzEgTDU5LjExNSwxMDAuNjYxIEM2MC4yOTMsMTAxLjM0MSA2MS43ODYsMTAxLjc4MiA2My40MzUsMTAxLjkzNyBMMTQ0LjcwNyw1NS4wMTUgQzE0NC40MjgsNTQuMTA4IDE0My42ODIsNTMuMjg1IDE0Mi41NDQsNTIuNjI4IEw5Ni4wMjcsMjUuNzcxIEwxMi43MTQsNzMuODcxIEwxMi43MTQsNzMuODcxIFoiIGlkPSJGaWxsLTMiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ4LjMyNyw1OC40NzEgQzE0OC4xNDUsNTguNDggMTQ3Ljk2Miw1OC40OCAxNDcuNzgxLDU4LjQ3MiBDMTQ1Ljg4Nyw1OC4zODkgMTQ0LjQ3OSw1Ny40MzQgMTQ0LjYzNiw1Ni4zNCBDMTQ0LjY4OSw1NS45NjcgMTQ0LjY2NCw1NS41OTcgMTQ0LjU2NCw1NS4yMzUgTDYzLjQ2MSwxMDIuMDU3IEM2NC4wODksMTAyLjExNSA2NC43MzMsMTAyLjEzIDY1LjM3OSwxMDIuMDk5IEM2NS41NjEsMTAyLjA5IDY1Ljc0MywxMDIuMDkgNjUuOTI1LDEwMi4wOTggQzY3LjgxOSwxMDIuMTgxIDY5LjIyNywxMDMuMTM2IDY5LjA3LDEwNC4yMyBMMTQ4LjMyNyw1OC40NzEiIGlkPSJGaWxsLTQiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNjkuMDcsMTA0LjM0NyBDNjkuMDQ4LDEwNC4zNDcgNjkuMDI1LDEwNC4zNCA2OS4wMDUsMTA0LjMyNyBDNjguOTY4LDEwNC4zMDEgNjguOTQ4LDEwNC4yNTcgNjguOTU1LDEwNC4yMTMgQzY5LDEwMy44OTYgNjguODk4LDEwMy41NzYgNjguNjU4LDEwMy4yODggQzY4LjE1MywxMDIuNjc4IDY3LjEwMywxMDIuMjY2IDY1LjkyLDEwMi4yMTQgQzY1Ljc0MiwxMDIuMjA2IDY1LjU2MywxMDIuMjA3IDY1LjM4NSwxMDIuMjE1IEM2NC43NDIsMTAyLjI0NiA2NC4wODcsMTAyLjIzMiA2My40NSwxMDIuMTc0IEM2My4zOTksMTAyLjE2OSA2My4zNTgsMTAyLjEzMiA2My4zNDcsMTAyLjA4MiBDNjMuMzM2LDEwMi4wMzMgNjMuMzU4LDEwMS45ODEgNjMuNDAyLDEwMS45NTYgTDE0NC41MDYsNTUuMTM0IEMxNDQuNTM3LDU1LjExNiAxNDQuNTc1LDU1LjExMyAxNDQuNjA5LDU1LjEyNyBDMTQ0LjY0Miw1NS4xNDEgMTQ0LjY2OCw1NS4xNyAxNDQuNjc3LDU1LjIwNCBDMTQ0Ljc4MSw1NS41ODUgMTQ0LjgwNiw1NS45NzIgMTQ0Ljc1MSw1Ni4zNTcgQzE0NC43MDYsNTYuNjczIDE0NC44MDgsNTYuOTk0IDE0NS4wNDcsNTcuMjgyIEMxNDUuNTUzLDU3Ljg5MiAxNDYuNjAyLDU4LjMwMyAxNDcuNzg2LDU4LjM1NSBDMTQ3Ljk2NCw1OC4zNjMgMTQ4LjE0Myw1OC4zNjMgMTQ4LjMyMSw1OC4zNTQgQzE0OC4zNzcsNTguMzUyIDE0OC40MjQsNTguMzg3IDE0OC40MzksNTguNDM4IEMxNDguNDU0LDU4LjQ5IDE0OC40MzIsNTguNTQ1IDE0OC4zODUsNTguNTcyIEw2OS4xMjksMTA0LjMzMSBDNjkuMTExLDEwNC4zNDIgNjkuMDksMTA0LjM0NyA2OS4wNywxMDQuMzQ3IEw2OS4wNywxMDQuMzQ3IFogTTY1LjY2NSwxMDEuOTc1IEM2NS43NTQsMTAxLjk3NSA2NS44NDIsMTAxLjk3NyA2NS45MywxMDEuOTgxIEM2Ny4xOTYsMTAyLjAzNyA2OC4yODMsMTAyLjQ2OSA2OC44MzgsMTAzLjEzOSBDNjkuMDY1LDEwMy40MTMgNjkuMTg4LDEwMy43MTQgNjkuMTk4LDEwNC4wMjEgTDE0Ny44ODMsNTguNTkyIEMxNDcuODQ3LDU4LjU5MiAxNDcuODExLDU4LjU5MSAxNDcuNzc2LDU4LjU4OSBDMTQ2LjUwOSw1OC41MzMgMTQ1LjQyMiw1OC4xIDE0NC44NjcsNTcuNDMxIEMxNDQuNTg1LDU3LjA5MSAxNDQuNDY1LDU2LjcwNyAxNDQuNTIsNTYuMzI0IEMxNDQuNTYzLDU2LjAyMSAxNDQuNTUyLDU1LjcxNiAxNDQuNDg4LDU1LjQxNCBMNjMuODQ2LDEwMS45NyBDNjQuMzUzLDEwMi4wMDIgNjQuODY3LDEwMi4wMDYgNjUuMzc0LDEwMS45ODIgQzY1LjQ3MSwxMDEuOTc3IDY1LjU2OCwxMDEuOTc1IDY1LjY2NSwxMDEuOTc1IEw2NS42NjUsMTAxLjk3NSBaIiBpZD0iRmlsbC01IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTIuMjA4LDU1LjEzNCBDMS4yMDcsNTMuMzA3IDEuOTY3LDUwLjkxNyAzLjkwNiw0OS43OTcgTDU5LjkxNywxNy40NTMgQzYxLjg1NiwxNi4zMzMgNjQuMjQxLDE2LjkwNyA2NS4yNDMsMTguNzM0IEw2NS40NzUsMTkuMTQ0IEM2NS44NzIsMTkuODgyIDY2LjM2OCwyMC41NiA2Ni45NDUsMjEuMTY1IEw2Ny4yMjMsMjEuNDM1IEM3MC41NDgsMjQuNjQ5IDc1LjgwNiwyNS4xNTEgODAuMTExLDIyLjY2NSBMODcuNDMsMTguNDQ1IEM4OS4zNywxNy4zMjYgOTEuNzU0LDE3Ljg5OSA5Mi43NTUsMTkuNzI3IEw5Ni4wMDUsMjUuNjU1IEwxMi40ODYsNzMuODg0IEwyLjIwOCw1NS4xMzQgWiIgaWQ9IkZpbGwtNiIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMi40ODYsNzQuMDAxIEMxMi40NzYsNzQuMDAxIDEyLjQ2NSw3My45OTkgMTIuNDU1LDczLjk5NiBDMTIuNDI0LDczLjk4OCAxMi4zOTksNzMuOTY3IDEyLjM4NCw3My45NCBMMi4xMDYsNTUuMTkgQzEuMDc1LDUzLjMxIDEuODU3LDUwLjg0NSAzLjg0OCw0OS42OTYgTDU5Ljg1OCwxNy4zNTIgQzYwLjUyNSwxNi45NjcgNjEuMjcxLDE2Ljc2NCA2Mi4wMTYsMTYuNzY0IEM2My40MzEsMTYuNzY0IDY0LjY2NiwxNy40NjYgNjUuMzI3LDE4LjY0NiBDNjUuMzM3LDE4LjY1NCA2NS4zNDUsMTguNjYzIDY1LjM1MSwxOC42NzQgTDY1LjU3OCwxOS4wODggQzY1LjU4NCwxOS4xIDY1LjU4OSwxOS4xMTIgNjUuNTkxLDE5LjEyNiBDNjUuOTg1LDE5LjgzOCA2Ni40NjksMjAuNDk3IDY3LjAzLDIxLjA4NSBMNjcuMzA1LDIxLjM1MSBDNjkuMTUxLDIzLjEzNyA3MS42NDksMjQuMTIgNzQuMzM2LDI0LjEyIEM3Ni4zMTMsMjQuMTIgNzguMjksMjMuNTgyIDgwLjA1MywyMi41NjMgQzgwLjA2NCwyMi41NTcgODAuMDc2LDIyLjU1MyA4MC4wODgsMjIuNTUgTDg3LjM3MiwxOC4zNDQgQzg4LjAzOCwxNy45NTkgODguNzg0LDE3Ljc1NiA4OS41MjksMTcuNzU2IEM5MC45NTYsMTcuNzU2IDkyLjIwMSwxOC40NzIgOTIuODU4LDE5LjY3IEw5Ni4xMDcsMjUuNTk5IEM5Ni4xMzgsMjUuNjU0IDk2LjExOCwyNS43MjQgOTYuMDYzLDI1Ljc1NiBMMTIuNTQ1LDczLjk4NSBDMTIuNTI2LDczLjk5NiAxMi41MDYsNzQuMDAxIDEyLjQ4Niw3NC4wMDEgTDEyLjQ4Niw3NC4wMDEgWiBNNjIuMDE2LDE2Ljk5NyBDNjEuMzEyLDE2Ljk5NyA2MC42MDYsMTcuMTkgNTkuOTc1LDE3LjU1NCBMMy45NjUsNDkuODk5IEMyLjA4Myw1MC45ODUgMS4zNDEsNTMuMzA4IDIuMzEsNTUuMDc4IEwxMi41MzEsNzMuNzIzIEw5NS44NDgsMjUuNjExIEw5Mi42NTMsMTkuNzgyIEM5Mi4wMzgsMTguNjYgOTAuODcsMTcuOTkgODkuNTI5LDE3Ljk5IEM4OC44MjUsMTcuOTkgODguMTE5LDE4LjE4MiA4Ny40ODksMTguNTQ3IEw4MC4xNzIsMjIuNzcyIEM4MC4xNjEsMjIuNzc4IDgwLjE0OSwyMi43ODIgODAuMTM3LDIyLjc4NSBDNzguMzQ2LDIzLjgxMSA3Ni4zNDEsMjQuMzU0IDc0LjMzNiwyNC4zNTQgQzcxLjU4OCwyNC4zNTQgNjkuMDMzLDIzLjM0NyA2Ny4xNDIsMjEuNTE5IEw2Ni44NjQsMjEuMjQ5IEM2Ni4yNzcsMjAuNjM0IDY1Ljc3NCwxOS45NDcgNjUuMzY3LDE5LjIwMyBDNjUuMzYsMTkuMTkyIDY1LjM1NiwxOS4xNzkgNjUuMzU0LDE5LjE2NiBMNjUuMTYzLDE4LjgxOSBDNjUuMTU0LDE4LjgxMSA2NS4xNDYsMTguODAxIDY1LjE0LDE4Ljc5IEM2NC41MjUsMTcuNjY3IDYzLjM1NywxNi45OTcgNjIuMDE2LDE2Ljk5NyBMNjIuMDE2LDE2Ljk5NyBaIiBpZD0iRmlsbC03IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTQyLjQzNCw0OC44MDggTDQyLjQzNCw0OC44MDggQzM5LjkyNCw0OC44MDcgMzcuNzM3LDQ3LjU1IDM2LjU4Miw0NS40NDMgQzM0Ljc3MSw0Mi4xMzkgMzYuMTQ0LDM3LjgwOSAzOS42NDEsMzUuNzg5IEw1MS45MzIsMjguNjkxIEM1My4xMDMsMjguMDE1IDU0LjQxMywyNy42NTggNTUuNzIxLDI3LjY1OCBDNTguMjMxLDI3LjY1OCA2MC40MTgsMjguOTE2IDYxLjU3MywzMS4wMjMgQzYzLjM4NCwzNC4zMjcgNjIuMDEyLDM4LjY1NyA1OC41MTQsNDAuNjc3IEw0Ni4yMjMsNDcuNzc1IEM0NS4wNTMsNDguNDUgNDMuNzQyLDQ4LjgwOCA0Mi40MzQsNDguODA4IEw0Mi40MzQsNDguODA4IFogTTU1LjcyMSwyOC4xMjUgQzU0LjQ5NSwyOC4xMjUgNTMuMjY1LDI4LjQ2MSA1Mi4xNjYsMjkuMDk2IEwzOS44NzUsMzYuMTk0IEMzNi41OTYsMzguMDg3IDM1LjMwMiw0Mi4xMzYgMzYuOTkyLDQ1LjIxOCBDMzguMDYzLDQ3LjE3MyA0MC4wOTgsNDguMzQgNDIuNDM0LDQ4LjM0IEM0My42NjEsNDguMzQgNDQuODksNDguMDA1IDQ1Ljk5LDQ3LjM3IEw1OC4yODEsNDAuMjcyIEM2MS41NiwzOC4zNzkgNjIuODUzLDM0LjMzIDYxLjE2NCwzMS4yNDggQzYwLjA5MiwyOS4yOTMgNTguMDU4LDI4LjEyNSA1NS43MjEsMjguMTI1IEw1NS43MjEsMjguMTI1IFoiIGlkPSJGaWxsLTgiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTQ5LjU4OCwyLjQwNyBDMTQ5LjU4OCwyLjQwNyAxNTUuNzY4LDUuOTc1IDE1Ni4zMjUsNi4yOTcgTDE1Ni4zMjUsNy4xODQgQzE1Ni4zMjUsNy4zNiAxNTYuMzM4LDcuNTQ0IDE1Ni4zNjIsNy43MzMgQzE1Ni4zNzMsNy44MTQgMTU2LjM4Miw3Ljg5NCAxNTYuMzksNy45NzUgQzE1Ni41Myw5LjM5IDE1Ny4zNjMsMTAuOTczIDE1OC40OTUsMTEuOTc0IEwxNjUuODkxLDE4LjUxOSBDMTY2LjA2OCwxOC42NzUgMTY2LjI0OSwxOC44MTQgMTY2LjQzMiwxOC45MzQgQzE2OC4wMTEsMTkuOTc0IDE2OS4zODIsMTkuNCAxNjkuNDk0LDE3LjY1MiBDMTY5LjU0MywxNi44NjggMTY5LjU1MSwxNi4wNTcgMTY5LjUxNywxNS4yMjMgTDE2OS41MTQsMTUuMDYzIEwxNjkuNTE0LDEzLjkxMiBDMTcwLjc4LDE0LjY0MiAxOTUuNTAxLDI4LjkxNSAxOTUuNTAxLDI4LjkxNSBMMTk1LjUwMSw4Mi45MTUgQzE5NS41MDEsODQuMDA1IDE5NC43MzEsODQuNDQ1IDE5My43ODEsODMuODk3IEwxNTEuMzA4LDU5LjM3NCBDMTUwLjM1OCw1OC44MjYgMTQ5LjU4OCw1Ny40OTcgMTQ5LjU4OCw1Ni40MDggTDE0OS41ODgsMjIuMzc1IiBpZD0iRmlsbC05IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE5NC41NTMsODQuMjUgQzE5NC4yOTYsODQuMjUgMTk0LjAxMyw4NC4xNjUgMTkzLjcyMiw4My45OTcgTDE1MS4yNSw1OS40NzYgQzE1MC4yNjksNTguOTA5IDE0OS40NzEsNTcuNTMzIDE0OS40NzEsNTYuNDA4IEwxNDkuNDcxLDIyLjM3NSBMMTQ5LjcwNSwyMi4zNzUgTDE0OS43MDUsNTYuNDA4IEMxNDkuNzA1LDU3LjQ1OSAxNTAuNDUsNTguNzQ0IDE1MS4zNjYsNTkuMjc0IEwxOTMuODM5LDgzLjc5NSBDMTk0LjI2Myw4NC4wNCAxOTQuNjU1LDg0LjA4MyAxOTQuOTQyLDgzLjkxNyBDMTk1LjIyNyw4My43NTMgMTk1LjM4NCw4My4zOTcgMTk1LjM4NCw4Mi45MTUgTDE5NS4zODQsMjguOTgyIEMxOTQuMTAyLDI4LjI0MiAxNzIuMTA0LDE1LjU0MiAxNjkuNjMxLDE0LjExNCBMMTY5LjYzNCwxNS4yMiBDMTY5LjY2OCwxNi4wNTIgMTY5LjY2LDE2Ljg3NCAxNjkuNjEsMTcuNjU5IEMxNjkuNTU2LDE4LjUwMyAxNjkuMjE0LDE5LjEyMyAxNjguNjQ3LDE5LjQwNSBDMTY4LjAyOCwxOS43MTQgMTY3LjE5NywxOS41NzggMTY2LjM2NywxOS4wMzIgQzE2Ni4xODEsMTguOTA5IDE2NS45OTUsMTguNzY2IDE2NS44MTQsMTguNjA2IEwxNTguNDE3LDEyLjA2MiBDMTU3LjI1OSwxMS4wMzYgMTU2LjQxOCw5LjQzNyAxNTYuMjc0LDcuOTg2IEMxNTYuMjY2LDcuOTA3IDE1Ni4yNTcsNy44MjcgMTU2LjI0Nyw3Ljc0OCBDMTU2LjIyMSw3LjU1NSAxNTYuMjA5LDcuMzY1IDE1Ni4yMDksNy4xODQgTDE1Ni4yMDksNi4zNjQgQzE1NS4zNzUsNS44ODMgMTQ5LjUyOSwyLjUwOCAxNDkuNTI5LDIuNTA4IEwxNDkuNjQ2LDIuMzA2IEMxNDkuNjQ2LDIuMzA2IDE1NS44MjcsNS44NzQgMTU2LjM4NCw2LjE5NiBMMTU2LjQ0Miw2LjIzIEwxNTYuNDQyLDcuMTg0IEMxNTYuNDQyLDcuMzU1IDE1Ni40NTQsNy41MzUgMTU2LjQ3OCw3LjcxNyBDMTU2LjQ4OSw3LjggMTU2LjQ5OSw3Ljg4MiAxNTYuNTA3LDcuOTYzIEMxNTYuNjQ1LDkuMzU4IDE1Ny40NTUsMTAuODk4IDE1OC41NzIsMTEuODg2IEwxNjUuOTY5LDE4LjQzMSBDMTY2LjE0MiwxOC41ODQgMTY2LjMxOSwxOC43MiAxNjYuNDk2LDE4LjgzNyBDMTY3LjI1NCwxOS4zMzYgMTY4LDE5LjQ2NyAxNjguNTQzLDE5LjE5NiBDMTY5LjAzMywxOC45NTMgMTY5LjMyOSwxOC40MDEgMTY5LjM3NywxNy42NDUgQzE2OS40MjcsMTYuODY3IDE2OS40MzQsMTYuMDU0IDE2OS40MDEsMTUuMjI4IEwxNjkuMzk3LDE1LjA2NSBMMTY5LjM5NywxMy43MSBMMTY5LjU3MiwxMy44MSBDMTcwLjgzOSwxNC41NDEgMTk1LjU1OSwyOC44MTQgMTk1LjU1OSwyOC44MTQgTDE5NS42MTgsMjguODQ3IEwxOTUuNjE4LDgyLjkxNSBDMTk1LjYxOCw4My40ODQgMTk1LjQyLDgzLjkxMSAxOTUuMDU5LDg0LjExOSBDMTk0LjkwOCw4NC4yMDYgMTk0LjczNyw4NC4yNSAxOTQuNTUzLDg0LjI1IiBpZD0iRmlsbC0xMCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNDUuNjg1LDU2LjE2MSBMMTY5LjgsNzAuMDgzIEwxNDMuODIyLDg1LjA4MSBMMTQyLjM2LDg0Ljc3NCBDMTM1LjgyNiw4Mi42MDQgMTI4LjczMiw4MS4wNDYgMTIxLjM0MSw4MC4xNTggQzExNi45NzYsNzkuNjM0IDExMi42NzgsODEuMjU0IDExMS43NDMsODMuNzc4IEMxMTEuNTA2LDg0LjQxNCAxMTEuNTAzLDg1LjA3MSAxMTEuNzMyLDg1LjcwNiBDMTEzLjI3LDg5Ljk3MyAxMTUuOTY4LDk0LjA2OSAxMTkuNzI3LDk3Ljg0MSBMMTIwLjI1OSw5OC42ODYgQzEyMC4yNiw5OC42ODUgOTQuMjgyLDExMy42ODMgOTQuMjgyLDExMy42ODMgTDcwLjE2Nyw5OS43NjEgTDE0NS42ODUsNTYuMTYxIiBpZD0iRmlsbC0xMSIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik05NC4yODIsMTEzLjgxOCBMOTQuMjIzLDExMy43ODUgTDY5LjkzMyw5OS43NjEgTDcwLjEwOCw5OS42NiBMMTQ1LjY4NSw1Ni4wMjYgTDE0NS43NDMsNTYuMDU5IEwxNzAuMDMzLDcwLjA4MyBMMTQzLjg0Miw4NS4yMDUgTDE0My43OTcsODUuMTk1IEMxNDMuNzcyLDg1LjE5IDE0Mi4zMzYsODQuODg4IDE0Mi4zMzYsODQuODg4IEMxMzUuNzg3LDgyLjcxNCAxMjguNzIzLDgxLjE2MyAxMjEuMzI3LDgwLjI3NCBDMTIwLjc4OCw4MC4yMDkgMTIwLjIzNiw4MC4xNzcgMTE5LjY4OSw4MC4xNzcgQzExNS45MzEsODAuMTc3IDExMi42MzUsODEuNzA4IDExMS44NTIsODMuODE5IEMxMTEuNjI0LDg0LjQzMiAxMTEuNjIxLDg1LjA1MyAxMTEuODQyLDg1LjY2NyBDMTEzLjM3Nyw4OS45MjUgMTE2LjA1OCw5My45OTMgMTE5LjgxLDk3Ljc1OCBMMTE5LjgyNiw5Ny43NzkgTDEyMC4zNTIsOTguNjE0IEMxMjAuMzU0LDk4LjYxNyAxMjAuMzU2LDk4LjYyIDEyMC4zNTgsOTguNjI0IEwxMjAuNDIyLDk4LjcyNiBMMTIwLjMxNyw5OC43ODcgQzEyMC4yNjQsOTguODE4IDk0LjU5OSwxMTMuNjM1IDk0LjM0LDExMy43ODUgTDk0LjI4MiwxMTMuODE4IEw5NC4yODIsMTEzLjgxOCBaIE03MC40MDEsOTkuNzYxIEw5NC4yODIsMTEzLjU0OSBMMTE5LjA4NCw5OS4yMjkgQzExOS42Myw5OC45MTQgMTE5LjkzLDk4Ljc0IDEyMC4xMDEsOTguNjU0IEwxMTkuNjM1LDk3LjkxNCBDMTE1Ljg2NCw5NC4xMjcgMTEzLjE2OCw5MC4wMzMgMTExLjYyMiw4NS43NDYgQzExMS4zODIsODUuMDc5IDExMS4zODYsODQuNDA0IDExMS42MzMsODMuNzM4IEMxMTIuNDQ4LDgxLjUzOSAxMTUuODM2LDc5Ljk0MyAxMTkuNjg5LDc5Ljk0MyBDMTIwLjI0Niw3OS45NDMgMTIwLjgwNiw3OS45NzYgMTIxLjM1NSw4MC4wNDIgQzEyOC43NjcsODAuOTMzIDEzNS44NDYsODIuNDg3IDE0Mi4zOTYsODQuNjYzIEMxNDMuMjMyLDg0LjgzOCAxNDMuNjExLDg0LjkxNyAxNDMuNzg2LDg0Ljk2NyBMMTY5LjU2Niw3MC4wODMgTDE0NS42ODUsNTYuMjk1IEw3MC40MDEsOTkuNzYxIEw3MC40MDEsOTkuNzYxIFoiIGlkPSJGaWxsLTEyIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2Ny4yMywxOC45NzkgTDE2Ny4yMyw2OS44NSBMMTM5LjkwOSw4NS42MjMgTDEzMy40NDgsNzEuNDU2IEMxMzIuNTM4LDY5LjQ2IDEzMC4wMiw2OS43MTggMTI3LjgyNCw3Mi4wMyBDMTI2Ljc2OSw3My4xNCAxMjUuOTMxLDc0LjU4NSAxMjUuNDk0LDc2LjA0OCBMMTE5LjAzNCw5Ny42NzYgTDkxLjcxMiwxMTMuNDUgTDkxLjcxMiw2Mi41NzkgTDE2Ny4yMywxOC45NzkiIGlkPSJGaWxsLTEzIiBmaWxsPSIjRkZGRkZGIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTkxLjcxMiwxMTMuNTY3IEM5MS42OTIsMTEzLjU2NyA5MS42NzIsMTEzLjU2MSA5MS42NTMsMTEzLjU1MSBDOTEuNjE4LDExMy41MyA5MS41OTUsMTEzLjQ5MiA5MS41OTUsMTEzLjQ1IEw5MS41OTUsNjIuNTc5IEM5MS41OTUsNjIuNTM3IDkxLjYxOCw2Mi40OTkgOTEuNjUzLDYyLjQ3OCBMMTY3LjE3MiwxOC44NzggQzE2Ny4yMDgsMTguODU3IDE2Ny4yNTIsMTguODU3IDE2Ny4yODgsMTguODc4IEMxNjcuMzI0LDE4Ljg5OSAxNjcuMzQ3LDE4LjkzNyAxNjcuMzQ3LDE4Ljk3OSBMMTY3LjM0Nyw2OS44NSBDMTY3LjM0Nyw2OS44OTEgMTY3LjMyNCw2OS45MyAxNjcuMjg4LDY5Ljk1IEwxMzkuOTY3LDg1LjcyNSBDMTM5LjkzOSw4NS43NDEgMTM5LjkwNSw4NS43NDUgMTM5Ljg3Myw4NS43MzUgQzEzOS44NDIsODUuNzI1IDEzOS44MTYsODUuNzAyIDEzOS44MDIsODUuNjcyIEwxMzMuMzQyLDcxLjUwNCBDMTMyLjk2Nyw3MC42ODIgMTMyLjI4LDcwLjIyOSAxMzEuNDA4LDcwLjIyOSBDMTMwLjMxOSw3MC4yMjkgMTI5LjA0NCw3MC45MTUgMTI3LjkwOCw3Mi4xMSBDMTI2Ljg3NCw3My4yIDEyNi4wMzQsNzQuNjQ3IDEyNS42MDYsNzYuMDgyIEwxMTkuMTQ2LDk3LjcwOSBDMTE5LjEzNyw5Ny43MzggMTE5LjExOCw5Ny43NjIgMTE5LjA5Miw5Ny43NzcgTDkxLjc3LDExMy41NTEgQzkxLjc1MiwxMTMuNTYxIDkxLjczMiwxMTMuNTY3IDkxLjcxMiwxMTMuNTY3IEw5MS43MTIsMTEzLjU2NyBaIE05MS44MjksNjIuNjQ3IEw5MS44MjksMTEzLjI0OCBMMTE4LjkzNSw5Ny41OTggTDEyNS4zODIsNzYuMDE1IEMxMjUuODI3LDc0LjUyNSAxMjYuNjY0LDczLjA4MSAxMjcuNzM5LDcxLjk1IEMxMjguOTE5LDcwLjcwOCAxMzAuMjU2LDY5Ljk5NiAxMzEuNDA4LDY5Ljk5NiBDMTMyLjM3Nyw2OS45OTYgMTMzLjEzOSw3MC40OTcgMTMzLjU1NCw3MS40MDcgTDEzOS45NjEsODUuNDU4IEwxNjcuMTEzLDY5Ljc4MiBMMTY3LjExMywxOS4xODEgTDkxLjgyOSw2Mi42NDcgTDkxLjgyOSw2Mi42NDcgWiIgaWQ9IkZpbGwtMTQiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTY4LjU0MywxOS4yMTMgTDE2OC41NDMsNzAuMDgzIEwxNDEuMjIxLDg1Ljg1NyBMMTM0Ljc2MSw3MS42ODkgQzEzMy44NTEsNjkuNjk0IDEzMS4zMzMsNjkuOTUxIDEyOS4xMzcsNzIuMjYzIEMxMjguMDgyLDczLjM3NCAxMjcuMjQ0LDc0LjgxOSAxMjYuODA3LDc2LjI4MiBMMTIwLjM0Niw5Ny45MDkgTDkzLjAyNSwxMTMuNjgzIEw5My4wMjUsNjIuODEzIEwxNjguNTQzLDE5LjIxMyIgaWQ9IkZpbGwtMTUiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTMuMDI1LDExMy44IEM5My4wMDUsMTEzLjggOTIuOTg0LDExMy43OTUgOTIuOTY2LDExMy43ODUgQzkyLjkzMSwxMTMuNzY0IDkyLjkwOCwxMTMuNzI1IDkyLjkwOCwxMTMuNjg0IEw5Mi45MDgsNjIuODEzIEM5Mi45MDgsNjIuNzcxIDkyLjkzMSw2Mi43MzMgOTIuOTY2LDYyLjcxMiBMMTY4LjQ4NCwxOS4xMTIgQzE2OC41MiwxOS4wOSAxNjguNTY1LDE5LjA5IDE2OC42MDEsMTkuMTEyIEMxNjguNjM3LDE5LjEzMiAxNjguNjYsMTkuMTcxIDE2OC42NiwxOS4yMTIgTDE2OC42Niw3MC4wODMgQzE2OC42Niw3MC4xMjUgMTY4LjYzNyw3MC4xNjQgMTY4LjYwMSw3MC4xODQgTDE0MS4yOCw4NS45NTggQzE0MS4yNTEsODUuOTc1IDE0MS4yMTcsODUuOTc5IDE0MS4xODYsODUuOTY4IEMxNDEuMTU0LDg1Ljk1OCAxNDEuMTI5LDg1LjkzNiAxNDEuMTE1LDg1LjkwNiBMMTM0LjY1NSw3MS43MzggQzEzNC4yOCw3MC45MTUgMTMzLjU5Myw3MC40NjMgMTMyLjcyLDcwLjQ2MyBDMTMxLjYzMiw3MC40NjMgMTMwLjM1Nyw3MS4xNDggMTI5LjIyMSw3Mi4zNDQgQzEyOC4xODYsNzMuNDMzIDEyNy4zNDcsNzQuODgxIDEyNi45MTksNzYuMzE1IEwxMjAuNDU4LDk3Ljk0MyBDMTIwLjQ1LDk3Ljk3MiAxMjAuNDMxLDk3Ljk5NiAxMjAuNDA1LDk4LjAxIEw5My4wODMsMTEzLjc4NSBDOTMuMDY1LDExMy43OTUgOTMuMDQ1LDExMy44IDkzLjAyNSwxMTMuOCBMOTMuMDI1LDExMy44IFogTTkzLjE0Miw2Mi44ODEgTDkzLjE0MiwxMTMuNDgxIEwxMjAuMjQ4LDk3LjgzMiBMMTI2LjY5NSw3Ni4yNDggQzEyNy4xNCw3NC43NTggMTI3Ljk3Nyw3My4zMTUgMTI5LjA1Miw3Mi4xODMgQzEzMC4yMzEsNzAuOTQyIDEzMS41NjgsNzAuMjI5IDEzMi43Miw3MC4yMjkgQzEzMy42ODksNzAuMjI5IDEzNC40NTIsNzAuNzMxIDEzNC44NjcsNzEuNjQxIEwxNDEuMjc0LDg1LjY5MiBMMTY4LjQyNiw3MC4wMTYgTDE2OC40MjYsMTkuNDE1IEw5My4xNDIsNjIuODgxIEw5My4xNDIsNjIuODgxIFoiIGlkPSJGaWxsLTE2IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2OS44LDcwLjA4MyBMMTQyLjQ3OCw4NS44NTcgTDEzNi4wMTgsNzEuNjg5IEMxMzUuMTA4LDY5LjY5NCAxMzIuNTksNjkuOTUxIDEzMC4zOTMsNzIuMjYzIEMxMjkuMzM5LDczLjM3NCAxMjguNSw3NC44MTkgMTI4LjA2NCw3Ni4yODIgTDEyMS42MDMsOTcuOTA5IEw5NC4yODIsMTEzLjY4MyBMOTQuMjgyLDYyLjgxMyBMMTY5LjgsMTkuMjEzIEwxNjkuOCw3MC4wODMgWiIgaWQ9IkZpbGwtMTciIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOTQuMjgyLDExMy45MTcgQzk0LjI0MSwxMTMuOTE3IDk0LjIwMSwxMTMuOTA3IDk0LjE2NSwxMTMuODg2IEM5NC4wOTMsMTEzLjg0NSA5NC4wNDgsMTEzLjc2NyA5NC4wNDgsMTEzLjY4NCBMOTQuMDQ4LDYyLjgxMyBDOTQuMDQ4LDYyLjczIDk0LjA5Myw2Mi42NTIgOTQuMTY1LDYyLjYxMSBMMTY5LjY4MywxOS4wMSBDMTY5Ljc1NSwxOC45NjkgMTY5Ljg0NCwxOC45NjkgMTY5LjkxNywxOS4wMSBDMTY5Ljk4OSwxOS4wNTIgMTcwLjAzMywxOS4xMjkgMTcwLjAzMywxOS4yMTIgTDE3MC4wMzMsNzAuMDgzIEMxNzAuMDMzLDcwLjE2NiAxNjkuOTg5LDcwLjI0NCAxNjkuOTE3LDcwLjI4NSBMMTQyLjU5NSw4Ni4wNiBDMTQyLjUzOCw4Ni4wOTIgMTQyLjQ2OSw4Ni4xIDE0Mi40MDcsODYuMDggQzE0Mi4zNDQsODYuMDYgMTQyLjI5Myw4Ni4wMTQgMTQyLjI2Niw4NS45NTQgTDEzNS44MDUsNzEuNzg2IEMxMzUuNDQ1LDcwLjk5NyAxMzQuODEzLDcwLjU4IDEzMy45NzcsNzAuNTggQzEzMi45MjEsNzAuNTggMTMxLjY3Niw3MS4yNTIgMTMwLjU2Miw3Mi40MjQgQzEyOS41NCw3My41MDEgMTI4LjcxMSw3NC45MzEgMTI4LjI4Nyw3Ni4zNDggTDEyMS44MjcsOTcuOTc2IEMxMjEuODEsOTguMDM0IDEyMS43NzEsOTguMDgyIDEyMS43Miw5OC4xMTIgTDk0LjM5OCwxMTMuODg2IEM5NC4zNjIsMTEzLjkwNyA5NC4zMjIsMTEzLjkxNyA5NC4yODIsMTEzLjkxNyBMOTQuMjgyLDExMy45MTcgWiBNOTQuNTE1LDYyLjk0OCBMOTQuNTE1LDExMy4yNzkgTDEyMS40MDYsOTcuNzU0IEwxMjcuODQsNzYuMjE1IEMxMjguMjksNzQuNzA4IDEyOS4xMzcsNzMuMjQ3IDEzMC4yMjQsNzIuMTAzIEMxMzEuNDI1LDcwLjgzOCAxMzIuNzkzLDcwLjExMiAxMzMuOTc3LDcwLjExMiBDMTM0Ljk5NSw3MC4xMTIgMTM1Ljc5NSw3MC42MzggMTM2LjIzLDcxLjU5MiBMMTQyLjU4NCw4NS41MjYgTDE2OS41NjYsNjkuOTQ4IEwxNjkuNTY2LDE5LjYxNyBMOTQuNTE1LDYyLjk0OCBMOTQuNTE1LDYyLjk0OCBaIiBpZD0iRmlsbC0xOCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMDkuODk0LDkyLjk0MyBMMTA5Ljg5NCw5Mi45NDMgQzEwOC4xMiw5Mi45NDMgMTA2LjY1Myw5Mi4yMTggMTA1LjY1LDkwLjgyMyBDMTA1LjU4Myw5MC43MzEgMTA1LjU5Myw5MC42MSAxMDUuNjczLDkwLjUyOSBDMTA1Ljc1Myw5MC40NDggMTA1Ljg4LDkwLjQ0IDEwNS45NzQsOTAuNTA2IEMxMDYuNzU0LDkxLjA1MyAxMDcuNjc5LDkxLjMzMyAxMDguNzI0LDkxLjMzMyBDMTEwLjA0Nyw5MS4zMzMgMTExLjQ3OCw5MC44OTQgMTEyLjk4LDkwLjAyNyBDMTE4LjI5MSw4Ni45NiAxMjIuNjExLDc5LjUwOSAxMjIuNjExLDczLjQxNiBDMTIyLjYxMSw3MS40ODkgMTIyLjE2OSw2OS44NTYgMTIxLjMzMyw2OC42OTIgQzEyMS4yNjYsNjguNiAxMjEuMjc2LDY4LjQ3MyAxMjEuMzU2LDY4LjM5MiBDMTIxLjQzNiw2OC4zMTEgMTIxLjU2Myw2OC4yOTkgMTIxLjY1Niw2OC4zNjUgQzEyMy4zMjcsNjkuNTM3IDEyNC4yNDcsNzEuNzQ2IDEyNC4yNDcsNzQuNTg0IEMxMjQuMjQ3LDgwLjgyNiAxMTkuODIxLDg4LjQ0NyAxMTQuMzgyLDkxLjU4NyBDMTEyLjgwOCw5Mi40OTUgMTExLjI5OCw5Mi45NDMgMTA5Ljg5NCw5Mi45NDMgTDEwOS44OTQsOTIuOTQzIFogTTEwNi45MjUsOTEuNDAxIEMxMDcuNzM4LDkyLjA1MiAxMDguNzQ1LDkyLjI3OCAxMDkuODkzLDkyLjI3OCBMMTA5Ljg5NCw5Mi4yNzggQzExMS4yMTUsOTIuMjc4IDExMi42NDcsOTEuOTUxIDExNC4xNDgsOTEuMDg0IEMxMTkuNDU5LDg4LjAxNyAxMjMuNzgsODAuNjIxIDEyMy43OCw3NC41MjggQzEyMy43OCw3Mi41NDkgMTIzLjMxNyw3MC45MjkgMTIyLjQ1NCw2OS43NjcgQzEyMi44NjUsNzAuODAyIDEyMy4wNzksNzIuMDQyIDEyMy4wNzksNzMuNDAyIEMxMjMuMDc5LDc5LjY0NSAxMTguNjUzLDg3LjI4NSAxMTMuMjE0LDkwLjQyNSBDMTExLjY0LDkxLjMzNCAxMTAuMTMsOTEuNzQyIDEwOC43MjQsOTEuNzQyIEMxMDguMDgzLDkxLjc0MiAxMDcuNDgxLDkxLjU5MyAxMDYuOTI1LDkxLjQwMSBMMTA2LjkyNSw5MS40MDEgWiIgaWQ9IkZpbGwtMTkiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjA5Nyw5MC4yMyBDMTE4LjQ4MSw4Ny4xMjIgMTIyLjg0NSw3OS41OTQgMTIyLjg0NSw3My40MTYgQzEyMi44NDUsNzEuMzY1IDEyMi4zNjIsNjkuNzI0IDEyMS41MjIsNjguNTU2IEMxMTkuNzM4LDY3LjMwNCAxMTcuMTQ4LDY3LjM2MiAxMTQuMjY1LDY5LjAyNiBDMTA4Ljg4MSw3Mi4xMzQgMTA0LjUxNyw3OS42NjIgMTA0LjUxNyw4NS44NCBDMTA0LjUxNyw4Ny44OTEgMTA1LDg5LjUzMiAxMDUuODQsOTAuNyBDMTA3LjYyNCw5MS45NTIgMTEwLjIxNCw5MS44OTQgMTEzLjA5Nyw5MC4yMyIgaWQ9IkZpbGwtMjAiIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTA4LjcyNCw5MS42MTQgTDEwOC43MjQsOTEuNjE0IEMxMDcuNTgyLDkxLjYxNCAxMDYuNTY2LDkxLjQwMSAxMDUuNzA1LDkwLjc5NyBDMTA1LjY4NCw5MC43ODMgMTA1LjY2NSw5MC44MTEgMTA1LjY1LDkwLjc5IEMxMDQuNzU2LDg5LjU0NiAxMDQuMjgzLDg3Ljg0MiAxMDQuMjgzLDg1LjgxNyBDMTA0LjI4Myw3OS41NzUgMTA4LjcwOSw3MS45NTMgMTE0LjE0OCw2OC44MTIgQzExNS43MjIsNjcuOTA0IDExNy4yMzIsNjcuNDQ5IDExOC42MzgsNjcuNDQ5IEMxMTkuNzgsNjcuNDQ5IDEyMC43OTYsNjcuNzU4IDEyMS42NTYsNjguMzYyIEMxMjEuNjc4LDY4LjM3NyAxMjEuNjk3LDY4LjM5NyAxMjEuNzEyLDY4LjQxOCBDMTIyLjYwNiw2OS42NjIgMTIzLjA3OSw3MS4zOSAxMjMuMDc5LDczLjQxNSBDMTIzLjA3OSw3OS42NTggMTE4LjY1Myw4Ny4xOTggMTEzLjIxNCw5MC4zMzggQzExMS42NCw5MS4yNDcgMTEwLjEzLDkxLjYxNCAxMDguNzI0LDkxLjYxNCBMMTA4LjcyNCw5MS42MTQgWiBNMTA2LjAwNiw5MC41MDUgQzEwNi43OCw5MS4wMzcgMTA3LjY5NCw5MS4yODEgMTA4LjcyNCw5MS4yODEgQzExMC4wNDcsOTEuMjgxIDExMS40NzgsOTAuODY4IDExMi45OCw5MC4wMDEgQzExOC4yOTEsODYuOTM1IDEyMi42MTEsNzkuNDk2IDEyMi42MTEsNzMuNDAzIEMxMjIuNjExLDcxLjQ5NCAxMjIuMTc3LDY5Ljg4IDEyMS4zNTYsNjguNzE4IEMxMjAuNTgyLDY4LjE4NSAxMTkuNjY4LDY3LjkxOSAxMTguNjM4LDY3LjkxOSBDMTE3LjMxNSw2Ny45MTkgMTE1Ljg4Myw2OC4zNiAxMTQuMzgyLDY5LjIyNyBDMTA5LjA3MSw3Mi4yOTMgMTA0Ljc1MSw3OS43MzMgMTA0Ljc1MSw4NS44MjYgQzEwNC43NTEsODcuNzM1IDEwNS4xODUsODkuMzQzIDEwNi4wMDYsOTAuNTA1IEwxMDYuMDA2LDkwLjUwNSBaIiBpZD0iRmlsbC0yMSIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNDkuMzE4LDcuMjYyIEwxMzkuMzM0LDE2LjE0IEwxNTUuMjI3LDI3LjE3MSBMMTYwLjgxNiwyMS4wNTkgTDE0OS4zMTgsNy4yNjIiIGlkPSJGaWxsLTIyIiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE2OS42NzYsMTMuODQgTDE1OS45MjgsMTkuNDY3IEMxNTYuMjg2LDIxLjU3IDE1MC40LDIxLjU4IDE0Ni43ODEsMTkuNDkxIEMxNDMuMTYxLDE3LjQwMiAxNDMuMTgsMTQuMDAzIDE0Ni44MjIsMTEuOSBMMTU2LjMxNyw2LjI5MiBMMTQ5LjU4OCwyLjQwNyBMNjcuNzUyLDQ5LjQ3OCBMMTEzLjY3NSw3NS45OTIgTDExNi43NTYsNzQuMjEzIEMxMTcuMzg3LDczLjg0OCAxMTcuNjI1LDczLjMxNSAxMTcuMzc0LDcyLjgyMyBDMTE1LjAxNyw2OC4xOTEgMTE0Ljc4MSw2My4yNzcgMTE2LjY5MSw1OC41NjEgQzEyMi4zMjksNDQuNjQxIDE0MS4yLDMzLjc0NiAxNjUuMzA5LDMwLjQ5MSBDMTczLjQ3OCwyOS4zODggMTgxLjk4OSwyOS41MjQgMTkwLjAxMywzMC44ODUgQzE5MC44NjUsMzEuMDMgMTkxLjc4OSwzMC44OTMgMTkyLjQyLDMwLjUyOCBMMTk1LjUwMSwyOC43NSBMMTY5LjY3NiwxMy44NCIgaWQ9IkZpbGwtMjMiIGZpbGw9IiNGQUZBRkEiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjY3NSw3Ni40NTkgQzExMy41OTQsNzYuNDU5IDExMy41MTQsNzYuNDM4IDExMy40NDIsNzYuMzk3IEw2Ny41MTgsNDkuODgyIEM2Ny4zNzQsNDkuNzk5IDY3LjI4NCw0OS42NDUgNjcuMjg1LDQ5LjQ3OCBDNjcuMjg1LDQ5LjMxMSA2Ny4zNzQsNDkuMTU3IDY3LjUxOSw0OS4wNzMgTDE0OS4zNTUsMi4wMDIgQzE0OS40OTksMS45MTkgMTQ5LjY3NywxLjkxOSAxNDkuODIxLDIuMDAyIEwxNTYuNTUsNS44ODcgQzE1Ni43NzQsNi4wMTcgMTU2Ljg1LDYuMzAyIDE1Ni43MjIsNi41MjYgQzE1Ni41OTIsNi43NDkgMTU2LjMwNyw2LjgyNiAxNTYuMDgzLDYuNjk2IEwxNDkuNTg3LDIuOTQ2IEw2OC42ODcsNDkuNDc5IEwxMTMuNjc1LDc1LjQ1MiBMMTE2LjUyMyw3My44MDggQzExNi43MTUsNzMuNjk3IDExNy4xNDMsNzMuMzk5IDExNi45NTgsNzMuMDM1IEMxMTQuNTQyLDY4LjI4NyAxMTQuMyw2My4yMjEgMTE2LjI1OCw1OC4zODUgQzExOS4wNjQsNTEuNDU4IDEyNS4xNDMsNDUuMTQzIDEzMy44NCw0MC4xMjIgQzE0Mi40OTcsMzUuMTI0IDE1My4zNTgsMzEuNjMzIDE2NS4yNDcsMzAuMDI4IEMxNzMuNDQ1LDI4LjkyMSAxODIuMDM3LDI5LjA1OCAxOTAuMDkxLDMwLjQyNSBDMTkwLjgzLDMwLjU1IDE5MS42NTIsMzAuNDMyIDE5Mi4xODYsMzAuMTI0IEwxOTQuNTY3LDI4Ljc1IEwxNjkuNDQyLDE0LjI0NCBDMTY5LjIxOSwxNC4xMTUgMTY5LjE0MiwxMy44MjkgMTY5LjI3MSwxMy42MDYgQzE2OS40LDEzLjM4MiAxNjkuNjg1LDEzLjMwNiAxNjkuOTA5LDEzLjQzNSBMMTk1LjczNCwyOC4zNDUgQzE5NS44NzksMjguNDI4IDE5NS45NjgsMjguNTgzIDE5NS45NjgsMjguNzUgQzE5NS45NjgsMjguOTE2IDE5NS44NzksMjkuMDcxIDE5NS43MzQsMjkuMTU0IEwxOTIuNjUzLDMwLjkzMyBDMTkxLjkzMiwzMS4zNSAxOTAuODksMzEuNTA4IDE4OS45MzUsMzEuMzQ2IEMxODEuOTcyLDI5Ljk5NSAxNzMuNDc4LDI5Ljg2IDE2NS4zNzIsMzAuOTU0IEMxNTMuNjAyLDMyLjU0MyAxNDIuODYsMzUuOTkzIDEzNC4zMDcsNDAuOTMxIEMxMjUuNzkzLDQ1Ljg0NyAxMTkuODUxLDUyLjAwNCAxMTcuMTI0LDU4LjczNiBDMTE1LjI3LDYzLjMxNCAxMTUuNTAxLDY4LjExMiAxMTcuNzksNzIuNjExIEMxMTguMTYsNzMuMzM2IDExNy44NDUsNzQuMTI0IDExNi45OSw3NC42MTcgTDExMy45MDksNzYuMzk3IEMxMTMuODM2LDc2LjQzOCAxMTMuNzU2LDc2LjQ1OSAxMTMuNjc1LDc2LjQ1OSIgaWQ9IkZpbGwtMjQiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUzLjMxNiwyMS4yNzkgQzE1MC45MDMsMjEuMjc5IDE0OC40OTUsMjAuNzUxIDE0Ni42NjQsMTkuNjkzIEMxNDQuODQ2LDE4LjY0NCAxNDMuODQ0LDE3LjIzMiAxNDMuODQ0LDE1LjcxOCBDMTQzLjg0NCwxNC4xOTEgMTQ0Ljg2LDEyLjc2MyAxNDYuNzA1LDExLjY5OCBMMTU2LjE5OCw2LjA5MSBDMTU2LjMwOSw2LjAyNSAxNTYuNDUyLDYuMDYyIDE1Ni41MTgsNi4xNzMgQzE1Ni41ODMsNi4yODQgMTU2LjU0Nyw2LjQyNyAxNTYuNDM2LDYuNDkzIEwxNDYuOTQsMTIuMTAyIEMxNDUuMjQ0LDEzLjA4MSAxNDQuMzEyLDE0LjM2NSAxNDQuMzEyLDE1LjcxOCBDMTQ0LjMxMiwxNy4wNTggMTQ1LjIzLDE4LjMyNiAxNDYuODk3LDE5LjI4OSBDMTUwLjQ0NiwyMS4zMzggMTU2LjI0LDIxLjMyNyAxNTkuODExLDE5LjI2NSBMMTY5LjU1OSwxMy42MzcgQzE2OS42NywxMy41NzMgMTY5LjgxMywxMy42MTEgMTY5Ljg3OCwxMy43MjMgQzE2OS45NDMsMTMuODM0IDE2OS45MDQsMTMuOTc3IDE2OS43OTMsMTQuMDQyIEwxNjAuMDQ1LDE5LjY3IEMxNTguMTg3LDIwLjc0MiAxNTUuNzQ5LDIxLjI3OSAxNTMuMzE2LDIxLjI3OSIgaWQ9IkZpbGwtMjUiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEzLjY3NSw3NS45OTIgTDY3Ljc2Miw0OS40ODQiIGlkPSJGaWxsLTI2IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTExMy42NzUsNzYuMzQyIEMxMTMuNjE1LDc2LjM0MiAxMTMuNTU1LDc2LjMyNyAxMTMuNSw3Ni4yOTUgTDY3LjU4Nyw0OS43ODcgQzY3LjQxOSw0OS42OSA2Ny4zNjIsNDkuNDc2IDY3LjQ1OSw0OS4zMDkgQzY3LjU1Niw0OS4xNDEgNjcuNzcsNDkuMDgzIDY3LjkzNyw0OS4xOCBMMTEzLjg1LDc1LjY4OCBDMTE0LjAxOCw3NS43ODUgMTE0LjA3NSw3NiAxMTMuOTc4LDc2LjE2NyBDMTEzLjkxNCw3Ni4yNzkgMTEzLjc5Niw3Ni4zNDIgMTEzLjY3NSw3Ni4zNDIiIGlkPSJGaWxsLTI3IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTY3Ljc2Miw0OS40ODQgTDY3Ljc2MiwxMDMuNDg1IEM2Ny43NjIsMTA0LjU3NSA2OC41MzIsMTA1LjkwMyA2OS40ODIsMTA2LjQ1MiBMMTExLjk1NSwxMzAuOTczIEMxMTIuOTA1LDEzMS41MjIgMTEzLjY3NSwxMzEuMDgzIDExMy42NzUsMTI5Ljk5MyBMMTEzLjY3NSw3NS45OTIiIGlkPSJGaWxsLTI4IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTExMi43MjcsMTMxLjU2MSBDMTEyLjQzLDEzMS41NjEgMTEyLjEwNywxMzEuNDY2IDExMS43OCwxMzEuMjc2IEw2OS4zMDcsMTA2Ljc1NSBDNjguMjQ0LDEwNi4xNDIgNjcuNDEyLDEwNC43MDUgNjcuNDEyLDEwMy40ODUgTDY3LjQxMiw0OS40ODQgQzY3LjQxMiw0OS4yOSA2Ny41NjksNDkuMTM0IDY3Ljc2Miw0OS4xMzQgQzY3Ljk1Niw0OS4xMzQgNjguMTEzLDQ5LjI5IDY4LjExMyw0OS40ODQgTDY4LjExMywxMDMuNDg1IEM2OC4xMTMsMTA0LjQ0NSA2OC44MiwxMDUuNjY1IDY5LjY1NywxMDYuMTQ4IEwxMTIuMTMsMTMwLjY3IEMxMTIuNDc0LDEzMC44NjggMTEyLjc5MSwxMzAuOTEzIDExMywxMzAuNzkyIEMxMTMuMjA2LDEzMC42NzMgMTEzLjMyNSwxMzAuMzgxIDExMy4zMjUsMTI5Ljk5MyBMMTEzLjMyNSw3NS45OTIgQzExMy4zMjUsNzUuNzk4IDExMy40ODIsNzUuNjQxIDExMy42NzUsNzUuNjQxIEMxMTMuODY5LDc1LjY0MSAxMTQuMDI1LDc1Ljc5OCAxMTQuMDI1LDc1Ljk5MiBMMTE0LjAyNSwxMjkuOTkzIEMxMTQuMDI1LDEzMC42NDggMTEzLjc4NiwxMzEuMTQ3IDExMy4zNSwxMzEuMzk5IEMxMTMuMTYyLDEzMS41MDcgMTEyLjk1MiwxMzEuNTYxIDExMi43MjcsMTMxLjU2MSIgaWQ9IkZpbGwtMjkiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTEyLjg2LDQwLjUxMiBDMTEyLjg2LDQwLjUxMiAxMTIuODYsNDAuNTEyIDExMi44NTksNDAuNTEyIEMxMTAuNTQxLDQwLjUxMiAxMDguMzYsMzkuOTkgMTA2LjcxNywzOS4wNDEgQzEwNS4wMTIsMzguMDU3IDEwNC4wNzQsMzYuNzI2IDEwNC4wNzQsMzUuMjkyIEMxMDQuMDc0LDMzLjg0NyAxMDUuMDI2LDMyLjUwMSAxMDYuNzU0LDMxLjUwNCBMMTE4Ljc5NSwyNC41NTEgQzEyMC40NjMsMjMuNTg5IDEyMi42NjksMjMuMDU4IDEyNS4wMDcsMjMuMDU4IEMxMjcuMzI1LDIzLjA1OCAxMjkuNTA2LDIzLjU4MSAxMzEuMTUsMjQuNTMgQzEzMi44NTQsMjUuNTE0IDEzMy43OTMsMjYuODQ1IDEzMy43OTMsMjguMjc4IEMxMzMuNzkzLDI5LjcyNCAxMzIuODQxLDMxLjA2OSAxMzEuMTEzLDMyLjA2NyBMMTE5LjA3MSwzOS4wMTkgQzExNy40MDMsMzkuOTgyIDExNS4xOTcsNDAuNTEyIDExMi44Niw0MC41MTIgTDExMi44Niw0MC41MTIgWiBNMTI1LjAwNywyMy43NTkgQzEyMi43OSwyMy43NTkgMTIwLjcwOSwyNC4yNTYgMTE5LjE0NiwyNS4xNTggTDEwNy4xMDQsMzIuMTEgQzEwNS42MDIsMzIuOTc4IDEwNC43NzQsMzQuMTA4IDEwNC43NzQsMzUuMjkyIEMxMDQuNzc0LDM2LjQ2NSAxMDUuNTg5LDM3LjU4MSAxMDcuMDY3LDM4LjQzNCBDMTA4LjYwNSwzOS4zMjMgMTEwLjY2MywzOS44MTIgMTEyLjg1OSwzOS44MTIgTDExMi44NiwzOS44MTIgQzExNS4wNzYsMzkuODEyIDExNy4xNTgsMzkuMzE1IDExOC43MjEsMzguNDEzIEwxMzAuNzYyLDMxLjQ2IEMxMzIuMjY0LDMwLjU5MyAxMzMuMDkyLDI5LjQ2MyAxMzMuMDkyLDI4LjI3OCBDMTMzLjA5MiwyNy4xMDYgMTMyLjI3OCwyNS45OSAxMzAuOCwyNS4xMzYgQzEyOS4yNjEsMjQuMjQ4IDEyNy4yMDQsMjMuNzU5IDEyNS4wMDcsMjMuNzU5IEwxMjUuMDA3LDIzLjc1OSBaIiBpZD0iRmlsbC0zMCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNjUuNjMsMTYuMjE5IEwxNTkuODk2LDE5LjUzIEMxNTYuNzI5LDIxLjM1OCAxNTEuNjEsMjEuMzY3IDE0OC40NjMsMTkuNTUgQzE0NS4zMTYsMTcuNzMzIDE0NS4zMzIsMTQuNzc4IDE0OC40OTksMTIuOTQ5IEwxNTQuMjMzLDkuNjM5IEwxNjUuNjMsMTYuMjE5IiBpZD0iRmlsbC0zMSIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xNTQuMjMzLDEwLjQ0OCBMMTY0LjIyOCwxNi4yMTkgTDE1OS41NDYsMTguOTIzIEMxNTguMTEyLDE5Ljc1IDE1Ni4xOTQsMjAuMjA2IDE1NC4xNDcsMjAuMjA2IEMxNTIuMTE4LDIwLjIwNiAxNTAuMjI0LDE5Ljc1NyAxNDguODE0LDE4Ljk0MyBDMTQ3LjUyNCwxOC4xOTkgMTQ2LjgxNCwxNy4yNDkgMTQ2LjgxNCwxNi4yNjkgQzE0Ni44MTQsMTUuMjc4IDE0Ny41MzcsMTQuMzE0IDE0OC44NSwxMy41NTYgTDE1NC4yMzMsMTAuNDQ4IE0xNTQuMjMzLDkuNjM5IEwxNDguNDk5LDEyLjk0OSBDMTQ1LjMzMiwxNC43NzggMTQ1LjMxNiwxNy43MzMgMTQ4LjQ2MywxOS41NSBDMTUwLjAzMSwyMC40NTUgMTUyLjA4NiwyMC45MDcgMTU0LjE0NywyMC45MDcgQzE1Ni4yMjQsMjAuOTA3IDE1OC4zMDYsMjAuNDQ3IDE1OS44OTYsMTkuNTMgTDE2NS42MywxNi4yMTkgTDE1NC4yMzMsOS42MzkiIGlkPSJGaWxsLTMyIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0NS40NDUsNzIuNjY3IEwxNDUuNDQ1LDcyLjY2NyBDMTQzLjY3Miw3Mi42NjcgMTQyLjIwNCw3MS44MTcgMTQxLjIwMiw3MC40MjIgQzE0MS4xMzUsNzAuMzMgMTQxLjE0NSw3MC4xNDcgMTQxLjIyNSw3MC4wNjYgQzE0MS4zMDUsNjkuOTg1IDE0MS40MzIsNjkuOTQ2IDE0MS41MjUsNzAuMDExIEMxNDIuMzA2LDcwLjU1OSAxNDMuMjMxLDcwLjgyMyAxNDQuMjc2LDcwLjgyMiBDMTQ1LjU5OCw3MC44MjIgMTQ3LjAzLDcwLjM3NiAxNDguNTMyLDY5LjUwOSBDMTUzLjg0Miw2Ni40NDMgMTU4LjE2Myw1OC45ODcgMTU4LjE2Myw1Mi44OTQgQzE1OC4xNjMsNTAuOTY3IDE1Ny43MjEsNDkuMzMyIDE1Ni44ODQsNDguMTY4IEMxNTYuODE4LDQ4LjA3NiAxNTYuODI4LDQ3Ljk0OCAxNTYuOTA4LDQ3Ljg2NyBDMTU2Ljk4OCw0Ny43ODYgMTU3LjExNCw0Ny43NzQgMTU3LjIwOCw0Ny44NCBDMTU4Ljg3OCw0OS4wMTIgMTU5Ljc5OCw1MS4yMiAxNTkuNzk4LDU0LjA1OSBDMTU5Ljc5OCw2MC4zMDEgMTU1LjM3Myw2OC4wNDYgMTQ5LjkzMyw3MS4xODYgQzE0OC4zNiw3Mi4wOTQgMTQ2Ljg1LDcyLjY2NyAxNDUuNDQ1LDcyLjY2NyBMMTQ1LjQ0NSw3Mi42NjcgWiBNMTQyLjQ3Niw3MSBDMTQzLjI5LDcxLjY1MSAxNDQuMjk2LDcyLjAwMiAxNDUuNDQ1LDcyLjAwMiBDMTQ2Ljc2Nyw3Mi4wMDIgMTQ4LjE5OCw3MS41NSAxNDkuNyw3MC42ODIgQzE1NS4wMSw2Ny42MTcgMTU5LjMzMSw2MC4xNTkgMTU5LjMzMSw1NC4wNjUgQzE1OS4zMzEsNTIuMDg1IDE1OC44NjgsNTAuNDM1IDE1OC4wMDYsNDkuMjcyIEMxNTguNDE3LDUwLjMwNyAxNTguNjMsNTEuNTMyIDE1OC42Myw1Mi44OTIgQzE1OC42Myw1OS4xMzQgMTU0LjIwNSw2Ni43NjcgMTQ4Ljc2NSw2OS45MDcgQzE0Ny4xOTIsNzAuODE2IDE0NS42ODEsNzEuMjgzIDE0NC4yNzYsNzEuMjgzIEMxNDMuNjM0LDcxLjI4MyAxNDMuMDMzLDcxLjE5MiAxNDIuNDc2LDcxIEwxNDIuNDc2LDcxIFoiIGlkPSJGaWxsLTMzIiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0OC42NDgsNjkuNzA0IEMxNTQuMDMyLDY2LjU5NiAxNTguMzk2LDU5LjA2OCAxNTguMzk2LDUyLjg5MSBDMTU4LjM5Niw1MC44MzkgMTU3LjkxMyw0OS4xOTggMTU3LjA3NCw0OC4wMyBDMTU1LjI4OSw0Ni43NzggMTUyLjY5OSw0Ni44MzYgMTQ5LjgxNiw0OC41MDEgQzE0NC40MzMsNTEuNjA5IDE0MC4wNjgsNTkuMTM3IDE0MC4wNjgsNjUuMzE0IEMxNDAuMDY4LDY3LjM2NSAxNDAuNTUyLDY5LjAwNiAxNDEuMzkxLDcwLjE3NCBDMTQzLjE3Niw3MS40MjcgMTQ1Ljc2NSw3MS4zNjkgMTQ4LjY0OCw2OS43MDQiIGlkPSJGaWxsLTM0IiBmaWxsPSIjRkFGQUZBIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTE0NC4yNzYsNzEuMjc2IEwxNDQuMjc2LDcxLjI3NiBDMTQzLjEzMyw3MS4yNzYgMTQyLjExOCw3MC45NjkgMTQxLjI1Nyw3MC4zNjUgQzE0MS4yMzYsNzAuMzUxIDE0MS4yMTcsNzAuMzMyIDE0MS4yMDIsNzAuMzExIEMxNDAuMzA3LDY5LjA2NyAxMzkuODM1LDY3LjMzOSAxMzkuODM1LDY1LjMxNCBDMTM5LjgzNSw1OS4wNzMgMTQ0LjI2LDUxLjQzOSAxNDkuNyw0OC4yOTggQzE1MS4yNzMsNDcuMzkgMTUyLjc4NCw0Ni45MjkgMTU0LjE4OSw0Ni45MjkgQzE1NS4zMzIsNDYuOTI5IDE1Ni4zNDcsNDcuMjM2IDE1Ny4yMDgsNDcuODM5IEMxNTcuMjI5LDQ3Ljg1NCAxNTcuMjQ4LDQ3Ljg3MyAxNTcuMjYzLDQ3Ljg5NCBDMTU4LjE1Nyw0OS4xMzggMTU4LjYzLDUwLjg2NSAxNTguNjMsNTIuODkxIEMxNTguNjMsNTkuMTMyIDE1NC4yMDUsNjYuNzY2IDE0OC43NjUsNjkuOTA3IEMxNDcuMTkyLDcwLjgxNSAxNDUuNjgxLDcxLjI3NiAxNDQuMjc2LDcxLjI3NiBMMTQ0LjI3Niw3MS4yNzYgWiBNMTQxLjU1OCw3MC4xMDQgQzE0Mi4zMzEsNzAuNjM3IDE0My4yNDUsNzEuMDA1IDE0NC4yNzYsNzEuMDA1IEMxNDUuNTk4LDcxLjAwNSAxNDcuMDMsNzAuNDY3IDE0OC41MzIsNjkuNiBDMTUzLjg0Miw2Ni41MzQgMTU4LjE2Myw1OS4wMzMgMTU4LjE2Myw1Mi45MzkgQzE1OC4xNjMsNTEuMDMxIDE1Ny43MjksNDkuMzg1IDE1Ni45MDcsNDguMjIzIEMxNTYuMTMzLDQ3LjY5MSAxNTUuMjE5LDQ3LjQwOSAxNTQuMTg5LDQ3LjQwOSBDMTUyLjg2Nyw0Ny40MDkgMTUxLjQzNSw0Ny44NDIgMTQ5LjkzMyw0OC43MDkgQzE0NC42MjMsNTEuNzc1IDE0MC4zMDIsNTkuMjczIDE0MC4zMDIsNjUuMzY2IEMxNDAuMzAyLDY3LjI3NiAxNDAuNzM2LDY4Ljk0MiAxNDEuNTU4LDcwLjEwNCBMMTQxLjU1OCw3MC4xMDQgWiIgaWQ9IkZpbGwtMzUiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUwLjcyLDY1LjM2MSBMMTUwLjM1Nyw2NS4wNjYgQzE1MS4xNDcsNjQuMDkyIDE1MS44NjksNjMuMDQgMTUyLjUwNSw2MS45MzggQzE1My4zMTMsNjAuNTM5IDE1My45NzgsNTkuMDY3IDE1NC40ODIsNTcuNTYzIEwxNTQuOTI1LDU3LjcxMiBDMTU0LjQxMiw1OS4yNDUgMTUzLjczMyw2MC43NDUgMTUyLjkxLDYyLjE3MiBDMTUyLjI2Miw2My4yOTUgMTUxLjUyNSw2NC4zNjggMTUwLjcyLDY1LjM2MSIgaWQ9IkZpbGwtMzYiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTE1LjkxNyw4NC41MTQgTDExNS41NTQsODQuMjIgQzExNi4zNDQsODMuMjQ1IDExNy4wNjYsODIuMTk0IDExNy43MDIsODEuMDkyIEMxMTguNTEsNzkuNjkyIDExOS4xNzUsNzguMjIgMTE5LjY3OCw3Ni43MTcgTDEyMC4xMjEsNzYuODY1IEMxMTkuNjA4LDc4LjM5OCAxMTguOTMsNzkuODk5IDExOC4xMDYsODEuMzI2IEMxMTcuNDU4LDgyLjQ0OCAxMTYuNzIyLDgzLjUyMSAxMTUuOTE3LDg0LjUxNCIgaWQ9IkZpbGwtMzciIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTE0LDEzMC40NzYgTDExNCwxMzAuMDA4IEwxMTQsNzYuMDUyIEwxMTQsNzUuNTg0IEwxMTQsNzYuMDUyIEwxMTQsMTMwLjAwOCBMMTE0LDEzMC40NzYiIGlkPSJGaWxsLTM4IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgICAgICA8ZyBpZD0iSW1wb3J0ZWQtTGF5ZXJzLUNvcHkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDYyLjAwMDAwMCwgMC4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTkuODIyLDM3LjQ3NCBDMTkuODM5LDM3LjMzOSAxOS43NDcsMzcuMTk0IDE5LjU1NSwzNy4wODIgQzE5LjIyOCwzNi44OTQgMTguNzI5LDM2Ljg3MiAxOC40NDYsMzcuMDM3IEwxMi40MzQsNDAuNTA4IEMxMi4zMDMsNDAuNTg0IDEyLjI0LDQwLjY4NiAxMi4yNDMsNDAuNzkzIEMxMi4yNDUsNDAuOTI1IDEyLjI0NSw0MS4yNTQgMTIuMjQ1LDQxLjM3MSBMMTIuMjQ1LDQxLjQxNCBMMTIuMjM4LDQxLjU0MiBDOC4xNDgsNDMuODg3IDUuNjQ3LDQ1LjMyMSA1LjY0Nyw0NS4zMjEgQzUuNjQ2LDQ1LjMyMSAzLjU3LDQ2LjM2NyAyLjg2LDUwLjUxMyBDMi44Niw1MC41MTMgMS45NDgsNTcuNDc0IDEuOTYyLDcwLjI1OCBDMS45NzcsODIuODI4IDIuNTY4LDg3LjMyOCAzLjEyOSw5MS42MDkgQzMuMzQ5LDkzLjI5MyA2LjEzLDkzLjczNCA2LjEzLDkzLjczNCBDNi40NjEsOTMuNzc0IDYuODI4LDkzLjcwNyA3LjIxLDkzLjQ4NiBMODIuNDgzLDQ5LjkzNSBDODQuMjkxLDQ4Ljg2NiA4NS4xNSw0Ni4yMTYgODUuNTM5LDQzLjY1MSBDODYuNzUyLDM1LjY2MSA4Ny4yMTQsMTAuNjczIDg1LjI2NCwzLjc3MyBDODUuMDY4LDMuMDggODQuNzU0LDIuNjkgODQuMzk2LDIuNDkxIEw4Mi4zMSwxLjcwMSBDODEuNTgzLDEuNzI5IDgwLjg5NCwyLjE2OCA4MC43NzYsMi4yMzYgQzgwLjYzNiwyLjMxNyA0MS44MDcsMjQuNTg1IDIwLjAzMiwzNy4wNzIgTDE5LjgyMiwzNy40NzQiIGlkPSJGaWxsLTEiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNODIuMzExLDEuNzAxIEw4NC4zOTYsMi40OTEgQzg0Ljc1NCwyLjY5IDg1LjA2OCwzLjA4IDg1LjI2NCwzLjc3MyBDODcuMjEzLDEwLjY3MyA4Ni43NTEsMzUuNjYgODUuNTM5LDQzLjY1MSBDODUuMTQ5LDQ2LjIxNiA4NC4yOSw0OC44NjYgODIuNDgzLDQ5LjkzNSBMNy4yMSw5My40ODYgQzYuODk3LDkzLjY2NyA2LjU5NSw5My43NDQgNi4zMTQsOTMuNzQ0IEw2LjEzMSw5My43MzMgQzYuMTMxLDkzLjczNCAzLjM0OSw5My4yOTMgMy4xMjgsOTEuNjA5IEMyLjU2OCw4Ny4zMjcgMS45NzcsODIuODI4IDEuOTYzLDcwLjI1OCBDMS45NDgsNTcuNDc0IDIuODYsNTAuNTEzIDIuODYsNTAuNTEzIEMzLjU3LDQ2LjM2NyA1LjY0Nyw0NS4zMjEgNS42NDcsNDUuMzIxIEM1LjY0Nyw0NS4zMjEgOC4xNDgsNDMuODg3IDEyLjIzOCw0MS41NDIgTDEyLjI0NSw0MS40MTQgTDEyLjI0NSw0MS4zNzEgQzEyLjI0NSw0MS4yNTQgMTIuMjQ1LDQwLjkyNSAxMi4yNDMsNDAuNzkzIEMxMi4yNCw0MC42ODYgMTIuMzAyLDQwLjU4MyAxMi40MzQsNDAuNTA4IEwxOC40NDYsMzcuMDM2IEMxOC41NzQsMzYuOTYyIDE4Ljc0NiwzNi45MjYgMTguOTI3LDM2LjkyNiBDMTkuMTQ1LDM2LjkyNiAxOS4zNzYsMzYuOTc5IDE5LjU1NCwzNy4wODIgQzE5Ljc0NywzNy4xOTQgMTkuODM5LDM3LjM0IDE5LjgyMiwzNy40NzQgTDIwLjAzMywzNy4wNzIgQzQxLjgwNiwyNC41ODUgODAuNjM2LDIuMzE4IDgwLjc3NywyLjIzNiBDODAuODk0LDIuMTY4IDgxLjU4MywxLjcyOSA4Mi4zMTEsMS43MDEgTTgyLjMxMSwwLjcwNCBMODIuMjcyLDAuNzA1IEM4MS42NTQsMC43MjggODAuOTg5LDAuOTQ5IDgwLjI5OCwxLjM2MSBMODAuMjc3LDEuMzczIEM4MC4xMjksMS40NTggNTkuNzY4LDEzLjEzNSAxOS43NTgsMzYuMDc5IEMxOS41LDM1Ljk4MSAxOS4yMTQsMzUuOTI5IDE4LjkyNywzNS45MjkgQzE4LjU2MiwzNS45MjkgMTguMjIzLDM2LjAxMyAxNy45NDcsMzYuMTczIEwxMS45MzUsMzkuNjQ0IEMxMS40OTMsMzkuODk5IDExLjIzNiw0MC4zMzQgMTEuMjQ2LDQwLjgxIEwxMS4yNDcsNDAuOTYgTDUuMTY3LDQ0LjQ0NyBDNC43OTQsNDQuNjQ2IDIuNjI1LDQ1Ljk3OCAxLjg3Nyw1MC4zNDUgTDEuODcxLDUwLjM4NCBDMS44NjIsNTAuNDU0IDAuOTUxLDU3LjU1NyAwLjk2NSw3MC4yNTkgQzAuOTc5LDgyLjg3OSAxLjU2OCw4Ny4zNzUgMi4xMzcsOTEuNzI0IEwyLjEzOSw5MS43MzkgQzIuNDQ3LDk0LjA5NCA1LjYxNCw5NC42NjIgNS45NzUsOTQuNzE5IEw2LjAwOSw5NC43MjMgQzYuMTEsOTQuNzM2IDYuMjEzLDk0Ljc0MiA2LjMxNCw5NC43NDIgQzYuNzksOTQuNzQyIDcuMjYsOTQuNjEgNy43MSw5NC4zNSBMODIuOTgzLDUwLjc5OCBDODQuNzk0LDQ5LjcyNyA4NS45ODIsNDcuMzc1IDg2LjUyNSw0My44MDEgQzg3LjcxMSwzNS45ODcgODguMjU5LDEwLjcwNSA4Ni4yMjQsMy41MDIgQzg1Ljk3MSwyLjYwOSA4NS41MiwxLjk3NSA4NC44ODEsMS42MiBMODQuNzQ5LDEuNTU4IEw4Mi42NjQsMC43NjkgQzgyLjU1MSwwLjcyNSA4Mi40MzEsMC43MDQgODIuMzExLDAuNzA0IiBpZD0iRmlsbC0yIiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTY2LjI2NywxMS41NjUgTDY3Ljc2MiwxMS45OTkgTDExLjQyMyw0NC4zMjUiIGlkPSJGaWxsLTMiIGZpbGw9IiNGRkZGRkYiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMjAyLDkwLjU0NSBDMTIuMDI5LDkwLjU0NSAxMS44NjIsOTAuNDU1IDExLjc2OSw5MC4yOTUgQzExLjYzMiw5MC4wNTcgMTEuNzEzLDg5Ljc1MiAxMS45NTIsODkuNjE0IEwzMC4zODksNzguOTY5IEMzMC42MjgsNzguODMxIDMwLjkzMyw3OC45MTMgMzEuMDcxLDc5LjE1MiBDMzEuMjA4LDc5LjM5IDMxLjEyNyw3OS42OTYgMzAuODg4LDc5LjgzMyBMMTIuNDUxLDkwLjQ3OCBMMTIuMjAyLDkwLjU0NSIgaWQ9IkZpbGwtNCIgZmlsbD0iIzYwN0Q4QiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMy43NjQsNDIuNjU0IEwxMy42NTYsNDIuNTkyIEwxMy43MDIsNDIuNDIxIEwxOC44MzcsMzkuNDU3IEwxOS4wMDcsMzkuNTAyIEwxOC45NjIsMzkuNjczIEwxMy44MjcsNDIuNjM3IEwxMy43NjQsNDIuNjU0IiBpZD0iRmlsbC01IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTguNTIsOTAuMzc1IEw4LjUyLDQ2LjQyMSBMOC41ODMsNDYuMzg1IEw3NS44NCw3LjU1NCBMNzUuODQsNTEuNTA4IEw3NS43NzgsNTEuNTQ0IEw4LjUyLDkwLjM3NSBMOC41Miw5MC4zNzUgWiBNOC43Nyw0Ni41NjQgTDguNzcsODkuOTQ0IEw3NS41OTEsNTEuMzY1IEw3NS41OTEsNy45ODUgTDguNzcsNDYuNTY0IEw4Ljc3LDQ2LjU2NCBaIiBpZD0iRmlsbC02IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTI0Ljk4Niw4My4xODIgQzI0Ljc1Niw4My4zMzEgMjQuMzc0LDgzLjU2NiAyNC4xMzcsODMuNzA1IEwxMi42MzIsOTAuNDA2IEMxMi4zOTUsOTAuNTQ1IDEyLjQyNiw5MC42NTggMTIuNyw5MC42NTggTDEzLjI2NSw5MC42NTggQzEzLjU0LDkwLjY1OCAxMy45NTgsOTAuNTQ1IDE0LjE5NSw5MC40MDYgTDI1LjcsODMuNzA1IEMyNS45MzcsODMuNTY2IDI2LjEyOCw4My40NTIgMjYuMTI1LDgzLjQ0OSBDMjYuMTIyLDgzLjQ0NyAyNi4xMTksODMuMjIgMjYuMTE5LDgyLjk0NiBDMjYuMTE5LDgyLjY3MiAyNS45MzEsODIuNTY5IDI1LjcwMSw4Mi43MTkgTDI0Ljk4Niw4My4xODIiIGlkPSJGaWxsLTciIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTMuMjY2LDkwLjc4MiBMMTIuNyw5MC43ODIgQzEyLjUsOTAuNzgyIDEyLjM4NCw5MC43MjYgMTIuMzU0LDkwLjYxNiBDMTIuMzI0LDkwLjUwNiAxMi4zOTcsOTAuMzk5IDEyLjU2OSw5MC4yOTkgTDI0LjA3NCw4My41OTcgQzI0LjMxLDgzLjQ1OSAyNC42ODksODMuMjI2IDI0LjkxOCw4My4wNzggTDI1LjYzMyw4Mi42MTQgQzI1LjcyMyw4Mi41NTUgMjUuODEzLDgyLjUyNSAyNS44OTksODIuNTI1IEMyNi4wNzEsODIuNTI1IDI2LjI0NCw4Mi42NTUgMjYuMjQ0LDgyLjk0NiBDMjYuMjQ0LDgzLjE2IDI2LjI0NSw4My4zMDkgMjYuMjQ3LDgzLjM4MyBMMjYuMjUzLDgzLjM4NyBMMjYuMjQ5LDgzLjQ1NiBDMjYuMjQ2LDgzLjUzMSAyNi4yNDYsODMuNTMxIDI1Ljc2Myw4My44MTIgTDE0LjI1OCw5MC41MTQgQzE0LDkwLjY2NSAxMy41NjQsOTAuNzgyIDEzLjI2Niw5MC43ODIgTDEzLjI2Niw5MC43ODIgWiBNMTIuNjY2LDkwLjUzMiBMMTIuNyw5MC41MzMgTDEzLjI2Niw5MC41MzMgQzEzLjUxOCw5MC41MzMgMTMuOTE1LDkwLjQyNSAxNC4xMzIsOTAuMjk5IEwyNS42MzcsODMuNTk3IEMyNS44MDUsODMuNDk5IDI1LjkzMSw4My40MjQgMjUuOTk4LDgzLjM4MyBDMjUuOTk0LDgzLjI5OSAyNS45OTQsODMuMTY1IDI1Ljk5NCw4Mi45NDYgTDI1Ljg5OSw4Mi43NzUgTDI1Ljc2OCw4Mi44MjQgTDI1LjA1NCw4My4yODcgQzI0LjgyMiw4My40MzcgMjQuNDM4LDgzLjY3MyAyNC4yLDgzLjgxMiBMMTIuNjk1LDkwLjUxNCBMMTIuNjY2LDkwLjUzMiBMMTIuNjY2LDkwLjUzMiBaIiBpZD0iRmlsbC04IiBmaWxsPSIjNjA3RDhCIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTEzLjI2Niw4OS44NzEgTDEyLjcsODkuODcxIEMxMi41LDg5Ljg3MSAxMi4zODQsODkuODE1IDEyLjM1NCw4OS43MDUgQzEyLjMyNCw4OS41OTUgMTIuMzk3LDg5LjQ4OCAxMi41NjksODkuMzg4IEwyNC4wNzQsODIuNjg2IEMyNC4zMzIsODIuNTM1IDI0Ljc2OCw4Mi40MTggMjUuMDY3LDgyLjQxOCBMMjUuNjMyLDgyLjQxOCBDMjUuODMyLDgyLjQxOCAyNS45NDgsODIuNDc0IDI1Ljk3OCw4Mi41ODQgQzI2LjAwOCw4Mi42OTQgMjUuOTM1LDgyLjgwMSAyNS43NjMsODIuOTAxIEwxNC4yNTgsODkuNjAzIEMxNCw4OS43NTQgMTMuNTY0LDg5Ljg3MSAxMy4yNjYsODkuODcxIEwxMy4yNjYsODkuODcxIFogTTEyLjY2Niw4OS42MjEgTDEyLjcsODkuNjIyIEwxMy4yNjYsODkuNjIyIEMxMy41MTgsODkuNjIyIDEzLjkxNSw4OS41MTUgMTQuMTMyLDg5LjM4OCBMMjUuNjM3LDgyLjY4NiBMMjUuNjY3LDgyLjY2OCBMMjUuNjMyLDgyLjY2NyBMMjUuMDY3LDgyLjY2NyBDMjQuODE1LDgyLjY2NyAyNC40MTgsODIuNzc1IDI0LjIsODIuOTAxIEwxMi42OTUsODkuNjAzIEwxMi42NjYsODkuNjIxIEwxMi42NjYsODkuNjIxIFoiIGlkPSJGaWxsLTkiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMzcsOTAuODAxIEwxMi4zNyw4OS41NTQgTDEyLjM3LDkwLjgwMSIgaWQ9IkZpbGwtMTAiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNi4xMyw5My45MDEgQzUuMzc5LDkzLjgwOCA0LjgxNiw5My4xNjQgNC42OTEsOTIuNTI1IEMzLjg2LDg4LjI4NyAzLjU0LDgzLjc0MyAzLjUyNiw3MS4xNzMgQzMuNTExLDU4LjM4OSA0LjQyMyw1MS40MjggNC40MjMsNTEuNDI4IEM1LjEzNCw0Ny4yODIgNy4yMSw0Ni4yMzYgNy4yMSw0Ni4yMzYgQzcuMjEsNDYuMjM2IDgxLjY2NywzLjI1IDgyLjA2OSwzLjAxNyBDODIuMjkyLDIuODg4IDg0LjU1NiwxLjQzMyA4NS4yNjQsMy45NCBDODcuMjE0LDEwLjg0IDg2Ljc1MiwzNS44MjcgODUuNTM5LDQzLjgxOCBDODUuMTUsNDYuMzgzIDg0LjI5MSw0OS4wMzMgODIuNDgzLDUwLjEwMSBMNy4yMSw5My42NTMgQzYuODI4LDkzLjg3NCA2LjQ2MSw5My45NDEgNi4xMyw5My45MDEgQzYuMTMsOTMuOTAxIDMuMzQ5LDkzLjQ2IDMuMTI5LDkxLjc3NiBDMi41NjgsODcuNDk1IDEuOTc3LDgyLjk5NSAxLjk2Miw3MC40MjUgQzEuOTQ4LDU3LjY0MSAyLjg2LDUwLjY4IDIuODYsNTAuNjggQzMuNTcsNDYuNTM0IDUuNjQ3LDQ1LjQ4OSA1LjY0Nyw0NS40ODkgQzUuNjQ2LDQ1LjQ4OSA4LjA2NSw0NC4wOTIgMTIuMjQ1LDQxLjY3OSBMMTMuMTE2LDQxLjU2IEwxOS43MTUsMzcuNzMgTDE5Ljc2MSwzNy4yNjkgTDYuMTMsOTMuOTAxIiBpZD0iRmlsbC0xMSIgZmlsbD0iI0ZBRkFGQSI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02LjMxNyw5NC4xNjEgTDYuMTAyLDk0LjE0OCBMNi4xMDEsOTQuMTQ4IEw1Ljg1Nyw5NC4xMDEgQzUuMTM4LDkzLjk0NSAzLjA4NSw5My4zNjUgMi44ODEsOTEuODA5IEMyLjMxMyw4Ny40NjkgMS43MjcsODIuOTk2IDEuNzEzLDcwLjQyNSBDMS42OTksNTcuNzcxIDIuNjA0LDUwLjcxOCAyLjYxMyw1MC42NDggQzMuMzM4LDQ2LjQxNyA1LjQ0NSw0NS4zMSA1LjUzNSw0NS4yNjYgTDEyLjE2Myw0MS40MzkgTDEzLjAzMyw0MS4zMiBMMTkuNDc5LDM3LjU3OCBMMTkuNTEzLDM3LjI0NCBDMTkuNTI2LDM3LjEwNyAxOS42NDcsMzcuMDA4IDE5Ljc4NiwzNy4wMjEgQzE5LjkyMiwzNy4wMzQgMjAuMDIzLDM3LjE1NiAyMC4wMDksMzcuMjkzIEwxOS45NSwzNy44ODIgTDEzLjE5OCw0MS44MDEgTDEyLjMyOCw0MS45MTkgTDUuNzcyLDQ1LjcwNCBDNS43NDEsNDUuNzIgMy43ODIsNDYuNzcyIDMuMTA2LDUwLjcyMiBDMy4wOTksNTAuNzgyIDIuMTk4LDU3LjgwOCAyLjIxMiw3MC40MjQgQzIuMjI2LDgyLjk2MyAyLjgwOSw4Ny40MiAzLjM3Myw5MS43MjkgQzMuNDY0LDkyLjQyIDQuMDYyLDkyLjg4MyA0LjY4Miw5My4xODEgQzQuNTY2LDkyLjk4NCA0LjQ4Niw5Mi43NzYgNC40NDYsOTIuNTcyIEMzLjY2NSw4OC41ODggMy4yOTEsODQuMzcgMy4yNzYsNzEuMTczIEMzLjI2Miw1OC41MiA0LjE2Nyw1MS40NjYgNC4xNzYsNTEuMzk2IEM0LjkwMSw0Ny4xNjUgNy4wMDgsNDYuMDU5IDcuMDk4LDQ2LjAxNCBDNy4wOTQsNDYuMDE1IDgxLjU0MiwzLjAzNCA4MS45NDQsMi44MDIgTDgxLjk3MiwyLjc4NSBDODIuODc2LDIuMjQ3IDgzLjY5MiwyLjA5NyA4NC4zMzIsMi4zNTIgQzg0Ljg4NywyLjU3MyA4NS4yODEsMy4wODUgODUuNTA0LDMuODcyIEM4Ny41MTgsMTEgODYuOTY0LDM2LjA5MSA4NS43ODUsNDMuODU1IEM4NS4yNzgsNDcuMTk2IDg0LjIxLDQ5LjM3IDgyLjYxLDUwLjMxNyBMNy4zMzUsOTMuODY5IEM2Ljk5OSw5NC4wNjMgNi42NTgsOTQuMTYxIDYuMzE3LDk0LjE2MSBMNi4zMTcsOTQuMTYxIFogTTYuMTcsOTMuNjU0IEM2LjQ2Myw5My42OSA2Ljc3NCw5My42MTcgNy4wODUsOTMuNDM3IEw4Mi4zNTgsNDkuODg2IEM4NC4xODEsNDguODA4IDg0Ljk2LDQ1Ljk3MSA4NS4yOTIsNDMuNzggQzg2LjQ2NiwzNi4wNDkgODcuMDIzLDExLjA4NSA4NS4wMjQsNC4wMDggQzg0Ljg0NiwzLjM3NyA4NC41NTEsMi45NzYgODQuMTQ4LDIuODE2IEM4My42NjQsMi42MjMgODIuOTgyLDIuNzY0IDgyLjIyNywzLjIxMyBMODIuMTkzLDMuMjM0IEM4MS43OTEsMy40NjYgNy4zMzUsNDYuNDUyIDcuMzM1LDQ2LjQ1MiBDNy4zMDQsNDYuNDY5IDUuMzQ2LDQ3LjUyMSA0LjY2OSw1MS40NzEgQzQuNjYyLDUxLjUzIDMuNzYxLDU4LjU1NiAzLjc3NSw3MS4xNzMgQzMuNzksODQuMzI4IDQuMTYxLDg4LjUyNCA0LjkzNiw5Mi40NzYgQzUuMDI2LDkyLjkzNyA1LjQxMiw5My40NTkgNS45NzMsOTMuNjE1IEM2LjA4Nyw5My42NCA2LjE1OCw5My42NTIgNi4xNjksOTMuNjU0IEw2LjE3LDkzLjY1NCBMNi4xNyw5My42NTQgWiIgaWQ9IkZpbGwtMTIiIGZpbGw9IiM0NTVBNjQiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNy4zMTcsNjguOTgyIEM3LjgwNiw2OC43MDEgOC4yMDIsNjguOTI2IDguMjAyLDY5LjQ4NyBDOC4yMDIsNzAuMDQ3IDcuODA2LDcwLjczIDcuMzE3LDcxLjAxMiBDNi44MjksNzEuMjk0IDYuNDMzLDcxLjA2OSA2LjQzMyw3MC41MDggQzYuNDMzLDY5Ljk0OCA2LjgyOSw2OS4yNjUgNy4zMTcsNjguOTgyIiBpZD0iRmlsbC0xMyIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik02LjkyLDcxLjEzMyBDNi42MzEsNzEuMTMzIDYuNDMzLDcwLjkwNSA2LjQzMyw3MC41MDggQzYuNDMzLDY5Ljk0OCA2LjgyOSw2OS4yNjUgNy4zMTcsNjguOTgyIEM3LjQ2LDY4LjkgNy41OTUsNjguODYxIDcuNzE0LDY4Ljg2MSBDOC4wMDMsNjguODYxIDguMjAyLDY5LjA5IDguMjAyLDY5LjQ4NyBDOC4yMDIsNzAuMDQ3IDcuODA2LDcwLjczIDcuMzE3LDcxLjAxMiBDNy4xNzQsNzEuMDk0IDcuMDM5LDcxLjEzMyA2LjkyLDcxLjEzMyBNNy43MTQsNjguNjc0IEM3LjU1Nyw2OC42NzQgNy4zOTIsNjguNzIzIDcuMjI0LDY4LjgyMSBDNi42NzYsNjkuMTM4IDYuMjQ2LDY5Ljg3OSA2LjI0Niw3MC41MDggQzYuMjQ2LDcwLjk5NCA2LjUxNyw3MS4zMiA2LjkyLDcxLjMyIEM3LjA3OCw3MS4zMiA3LjI0Myw3MS4yNzEgNy40MTEsNzEuMTc0IEM3Ljk1OSw3MC44NTcgOC4zODksNzAuMTE3IDguMzg5LDY5LjQ4NyBDOC4zODksNjkuMDAxIDguMTE3LDY4LjY3NCA3LjcxNCw2OC42NzQiIGlkPSJGaWxsLTE0IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTYuOTIsNzAuOTQ3IEM2LjY0OSw3MC45NDcgNi42MjEsNzAuNjQgNi42MjEsNzAuNTA4IEM2LjYyMSw3MC4wMTcgNi45ODIsNjkuMzkyIDcuNDExLDY5LjE0NSBDNy41MjEsNjkuMDgyIDcuNjI1LDY5LjA0OSA3LjcxNCw2OS4wNDkgQzcuOTg2LDY5LjA0OSA4LjAxNSw2OS4zNTUgOC4wMTUsNjkuNDg3IEM4LjAxNSw2OS45NzggNy42NTIsNzAuNjAzIDcuMjI0LDcwLjg1MSBDNy4xMTUsNzAuOTE0IDcuMDEsNzAuOTQ3IDYuOTIsNzAuOTQ3IE03LjcxNCw2OC44NjEgQzcuNTk1LDY4Ljg2MSA3LjQ2LDY4LjkgNy4zMTcsNjguOTgyIEM2LjgyOSw2OS4yNjUgNi40MzMsNjkuOTQ4IDYuNDMzLDcwLjUwOCBDNi40MzMsNzAuOTA1IDYuNjMxLDcxLjEzMyA2LjkyLDcxLjEzMyBDNy4wMzksNzEuMTMzIDcuMTc0LDcxLjA5NCA3LjMxNyw3MS4wMTIgQzcuODA2LDcwLjczIDguMjAyLDcwLjA0NyA4LjIwMiw2OS40ODcgQzguMjAyLDY5LjA5IDguMDAzLDY4Ljg2MSA3LjcxNCw2OC44NjEiIGlkPSJGaWxsLTE1IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTcuNDQ0LDg1LjM1IEM3LjcwOCw4NS4xOTggNy45MjEsODUuMzE5IDcuOTIxLDg1LjYyMiBDNy45MjEsODUuOTI1IDcuNzA4LDg2LjI5MiA3LjQ0NCw4Ni40NDQgQzcuMTgxLDg2LjU5NyA2Ljk2Nyw4Ni40NzUgNi45NjcsODYuMTczIEM2Ljk2Nyw4NS44NzEgNy4xODEsODUuNTAyIDcuNDQ0LDg1LjM1IiBpZD0iRmlsbC0xNiIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik03LjIzLDg2LjUxIEM3LjA3NCw4Ni41MSA2Ljk2Nyw4Ni4zODcgNi45NjcsODYuMTczIEM2Ljk2Nyw4NS44NzEgNy4xODEsODUuNTAyIDcuNDQ0LDg1LjM1IEM3LjUyMSw4NS4zMDUgNy41OTQsODUuMjg0IDcuNjU4LDg1LjI4NCBDNy44MTQsODUuMjg0IDcuOTIxLDg1LjQwOCA3LjkyMSw4NS42MjIgQzcuOTIxLDg1LjkyNSA3LjcwOCw4Ni4yOTIgNy40NDQsODYuNDQ0IEM3LjM2Nyw4Ni40ODkgNy4yOTQsODYuNTEgNy4yMyw4Ni41MSBNNy42NTgsODUuMDk4IEM3LjU1OCw4NS4wOTggNy40NTUsODUuMTI3IDcuMzUxLDg1LjE4OCBDNy4wMzEsODUuMzczIDYuNzgxLDg1LjgwNiA2Ljc4MSw4Ni4xNzMgQzYuNzgxLDg2LjQ4MiA2Ljk2Niw4Ni42OTcgNy4yMyw4Ni42OTcgQzcuMzMsODYuNjk3IDcuNDMzLDg2LjY2NiA3LjUzOCw4Ni42MDcgQzcuODU4LDg2LjQyMiA4LjEwOCw4NS45ODkgOC4xMDgsODUuNjIyIEM4LjEwOCw4NS4zMTMgNy45MjMsODUuMDk4IDcuNjU4LDg1LjA5OCIgaWQ9IkZpbGwtMTciIGZpbGw9IiM4MDk3QTIiPjwvcGF0aD4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNy4yMyw4Ni4zMjIgTDcuMTU0LDg2LjE3MyBDNy4xNTQsODUuOTM4IDcuMzMzLDg1LjYyOSA3LjUzOCw4NS41MTIgTDcuNjU4LDg1LjQ3MSBMNy43MzQsODUuNjIyIEM3LjczNCw4NS44NTYgNy41NTUsODYuMTY0IDcuMzUxLDg2LjI4MiBMNy4yMyw4Ni4zMjIgTTcuNjU4LDg1LjI4NCBDNy41OTQsODUuMjg0IDcuNTIxLDg1LjMwNSA3LjQ0NCw4NS4zNSBDNy4xODEsODUuNTAyIDYuOTY3LDg1Ljg3MSA2Ljk2Nyw4Ni4xNzMgQzYuOTY3LDg2LjM4NyA3LjA3NCw4Ni41MSA3LjIzLDg2LjUxIEM3LjI5NCw4Ni41MSA3LjM2Nyw4Ni40ODkgNy40NDQsODYuNDQ0IEM3LjcwOCw4Ni4yOTIgNy45MjEsODUuOTI1IDcuOTIxLDg1LjYyMiBDNy45MjEsODUuNDA4IDcuODE0LDg1LjI4NCA3LjY1OCw4NS4yODQiIGlkPSJGaWxsLTE4IiBmaWxsPSIjODA5N0EyIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTc3LjI3OCw3Ljc2OSBMNzcuMjc4LDUxLjQzNiBMMTAuMjA4LDkwLjE2IEwxMC4yMDgsNDYuNDkzIEw3Ny4yNzgsNy43NjkiIGlkPSJGaWxsLTE5IiBmaWxsPSIjNDU1QTY0Ij48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPHBhdGggZD0iTTEwLjA4Myw5MC4zNzUgTDEwLjA4Myw0Ni40MjEgTDEwLjE0Niw0Ni4zODUgTDc3LjQwMyw3LjU1NCBMNzcuNDAzLDUxLjUwOCBMNzcuMzQxLDUxLjU0NCBMMTAuMDgzLDkwLjM3NSBMMTAuMDgzLDkwLjM3NSBaIE0xMC4zMzMsNDYuNTY0IEwxMC4zMzMsODkuOTQ0IEw3Ny4xNTQsNTEuMzY1IEw3Ny4xNTQsNy45ODUgTDEwLjMzMyw0Ni41NjQgTDEwLjMzMyw0Ni41NjQgWiIgaWQ9IkZpbGwtMjAiIGZpbGw9IiM2MDdEOEIiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0xMjUuNzM3LDg4LjY0NyBMMTE4LjA5OCw5MS45ODEgTDExOC4wOTgsODQgTDEwNi42MzksODguNzEzIEwxMDYuNjM5LDk2Ljk4MiBMOTksMTAwLjMxNSBMMTEyLjM2OSwxMDMuOTYxIEwxMjUuNzM3LDg4LjY0NyIgaWQ9IkltcG9ydGVkLUxheWVycy1Db3B5LTIiIGZpbGw9IiM0NTVBNjQiIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPjwvcGF0aD4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+');
  41057. };
  41058. module.exports = RotateInstructions;
  41059. },{"./util.js":68}],63:[function(_dereq_,module,exports){
  41060. /*
  41061. * Copyright 2015 Google Inc. All Rights Reserved.
  41062. * Licensed under the Apache License, Version 2.0 (the "License");
  41063. * you may not use this file except in compliance with the License.
  41064. * You may obtain a copy of the License at
  41065. *
  41066. * http://www.apache.org/licenses/LICENSE-2.0
  41067. *
  41068. * Unless required by applicable law or agreed to in writing, software
  41069. * distributed under the License is distributed on an "AS IS" BASIS,
  41070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41071. * See the License for the specific language governing permissions and
  41072. * limitations under the License.
  41073. */
  41074. var SensorSample = _dereq_('./sensor-sample.js');
  41075. var MathUtil = _dereq_('../math-util.js');
  41076. var Util = _dereq_('../util.js');
  41077. /**
  41078. * An implementation of a simple complementary filter, which fuses gyroscope and
  41079. * accelerometer data from the 'devicemotion' event.
  41080. *
  41081. * Accelerometer data is very noisy, but stable over the long term.
  41082. * Gyroscope data is smooth, but tends to drift over the long term.
  41083. *
  41084. * This fusion is relatively simple:
  41085. * 1. Get orientation estimates from accelerometer by applying a low-pass filter
  41086. * on that data.
  41087. * 2. Get orientation estimates from gyroscope by integrating over time.
  41088. * 3. Combine the two estimates, weighing (1) in the long term, but (2) for the
  41089. * short term.
  41090. */
  41091. function ComplementaryFilter(kFilter) {
  41092. this.kFilter = kFilter;
  41093. // Raw sensor measurements.
  41094. this.currentAccelMeasurement = new SensorSample();
  41095. this.currentGyroMeasurement = new SensorSample();
  41096. this.previousGyroMeasurement = new SensorSample();
  41097. // Set default look direction to be in the correct direction.
  41098. if (Util.isIOS()) {
  41099. this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1);
  41100. } else {
  41101. this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1);
  41102. }
  41103. this.previousFilterQ = new MathUtil.Quaternion();
  41104. this.previousFilterQ.copy(this.filterQ);
  41105. // Orientation based on the accelerometer.
  41106. this.accelQ = new MathUtil.Quaternion();
  41107. // Whether or not the orientation has been initialized.
  41108. this.isOrientationInitialized = false;
  41109. // Running estimate of gravity based on the current orientation.
  41110. this.estimatedGravity = new MathUtil.Vector3();
  41111. // Measured gravity based on accelerometer.
  41112. this.measuredGravity = new MathUtil.Vector3();
  41113. // Debug only quaternion of gyro-based orientation.
  41114. this.gyroIntegralQ = new MathUtil.Quaternion();
  41115. }
  41116. ComplementaryFilter.prototype.addAccelMeasurement = function(vector, timestampS) {
  41117. this.currentAccelMeasurement.set(vector, timestampS);
  41118. };
  41119. ComplementaryFilter.prototype.addGyroMeasurement = function(vector, timestampS) {
  41120. this.currentGyroMeasurement.set(vector, timestampS);
  41121. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  41122. if (Util.isTimestampDeltaValid(deltaT)) {
  41123. this.run_();
  41124. }
  41125. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  41126. };
  41127. ComplementaryFilter.prototype.run_ = function() {
  41128. if (!this.isOrientationInitialized) {
  41129. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  41130. this.previousFilterQ.copy(this.accelQ);
  41131. this.isOrientationInitialized = true;
  41132. return;
  41133. }
  41134. var deltaT = this.currentGyroMeasurement.timestampS -
  41135. this.previousGyroMeasurement.timestampS;
  41136. // Convert gyro rotation vector to a quaternion delta.
  41137. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  41138. this.gyroIntegralQ.multiply(gyroDeltaQ);
  41139. // filter_1 = K * (filter_0 + gyro * dT) + (1 - K) * accel.
  41140. this.filterQ.copy(this.previousFilterQ);
  41141. this.filterQ.multiply(gyroDeltaQ);
  41142. // Calculate the delta between the current estimated gravity and the real
  41143. // gravity vector from accelerometer.
  41144. var invFilterQ = new MathUtil.Quaternion();
  41145. invFilterQ.copy(this.filterQ);
  41146. invFilterQ.inverse();
  41147. this.estimatedGravity.set(0, 0, -1);
  41148. this.estimatedGravity.applyQuaternion(invFilterQ);
  41149. this.estimatedGravity.normalize();
  41150. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  41151. this.measuredGravity.normalize();
  41152. // Compare estimated gravity with measured gravity, get the delta quaternion
  41153. // between the two.
  41154. var deltaQ = new MathUtil.Quaternion();
  41155. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  41156. deltaQ.inverse();
  41157. if (Util.isDebug()) {
  41158. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)',
  41159. MathUtil.radToDeg * Util.getQuaternionAngle(deltaQ),
  41160. (this.estimatedGravity.x).toFixed(1),
  41161. (this.estimatedGravity.y).toFixed(1),
  41162. (this.estimatedGravity.z).toFixed(1),
  41163. (this.measuredGravity.x).toFixed(1),
  41164. (this.measuredGravity.y).toFixed(1),
  41165. (this.measuredGravity.z).toFixed(1));
  41166. }
  41167. // Calculate the SLERP target: current orientation plus the measured-estimated
  41168. // quaternion delta.
  41169. var targetQ = new MathUtil.Quaternion();
  41170. targetQ.copy(this.filterQ);
  41171. targetQ.multiply(deltaQ);
  41172. // SLERP factor: 0 is pure gyro, 1 is pure accel.
  41173. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  41174. this.previousFilterQ.copy(this.filterQ);
  41175. };
  41176. ComplementaryFilter.prototype.getOrientation = function() {
  41177. return this.filterQ;
  41178. };
  41179. ComplementaryFilter.prototype.accelToQuaternion_ = function(accel) {
  41180. var normAccel = new MathUtil.Vector3();
  41181. normAccel.copy(accel);
  41182. normAccel.normalize();
  41183. var quat = new MathUtil.Quaternion();
  41184. quat.setFromUnitVectors(new MathUtil.Vector3(0, 0, -1), normAccel);
  41185. quat.inverse();
  41186. return quat;
  41187. };
  41188. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function(gyro, dt) {
  41189. // Extract axis and angle from the gyroscope data.
  41190. var quat = new MathUtil.Quaternion();
  41191. var axis = new MathUtil.Vector3();
  41192. axis.copy(gyro);
  41193. axis.normalize();
  41194. quat.setFromAxisAngle(axis, gyro.length() * dt);
  41195. return quat;
  41196. };
  41197. module.exports = ComplementaryFilter;
  41198. },{"../math-util.js":59,"../util.js":68,"./sensor-sample.js":66}],64:[function(_dereq_,module,exports){
  41199. /*
  41200. * Copyright 2015 Google Inc. All Rights Reserved.
  41201. * Licensed under the Apache License, Version 2.0 (the "License");
  41202. * you may not use this file except in compliance with the License.
  41203. * You may obtain a copy of the License at
  41204. *
  41205. * http://www.apache.org/licenses/LICENSE-2.0
  41206. *
  41207. * Unless required by applicable law or agreed to in writing, software
  41208. * distributed under the License is distributed on an "AS IS" BASIS,
  41209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41210. * See the License for the specific language governing permissions and
  41211. * limitations under the License.
  41212. */
  41213. var ComplementaryFilter = _dereq_('./complementary-filter.js');
  41214. var PosePredictor = _dereq_('./pose-predictor.js');
  41215. var TouchPanner = _dereq_('../touch-panner.js');
  41216. var MathUtil = _dereq_('../math-util.js');
  41217. var Util = _dereq_('../util.js');
  41218. /**
  41219. * The pose sensor, implemented using DeviceMotion APIs.
  41220. */
  41221. function FusionPoseSensor() {
  41222. this.deviceId = 'webvr-polyfill:fused';
  41223. this.deviceName = 'VR Position Device (webvr-polyfill:fused)';
  41224. this.accelerometer = new MathUtil.Vector3();
  41225. this.gyroscope = new MathUtil.Vector3();
  41226. this.start();
  41227. this.filter = new ComplementaryFilter(window.WebVRConfig.K_FILTER);
  41228. this.posePredictor = new PosePredictor(window.WebVRConfig.PREDICTION_TIME_S);
  41229. this.touchPanner = new TouchPanner();
  41230. this.filterToWorldQ = new MathUtil.Quaternion();
  41231. // Set the filter to world transform, depending on OS.
  41232. if (Util.isIOS()) {
  41233. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2);
  41234. } else {
  41235. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2);
  41236. }
  41237. this.inverseWorldToScreenQ = new MathUtil.Quaternion();
  41238. this.worldToScreenQ = new MathUtil.Quaternion();
  41239. this.originalPoseAdjustQ = new MathUtil.Quaternion();
  41240. this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1),
  41241. -window.orientation * Math.PI / 180);
  41242. this.setScreenTransform_();
  41243. // Adjust this filter for being in landscape mode.
  41244. if (Util.isLandscapeMode()) {
  41245. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  41246. }
  41247. // Keep track of a reset transform for resetSensor.
  41248. this.resetQ = new MathUtil.Quaternion();
  41249. this.isFirefoxAndroid = Util.isFirefoxAndroid();
  41250. this.isIOS = Util.isIOS();
  41251. this.orientationOut_ = new Float32Array(4);
  41252. }
  41253. FusionPoseSensor.prototype.getPosition = function() {
  41254. // This PoseSensor doesn't support position
  41255. return null;
  41256. };
  41257. FusionPoseSensor.prototype.getOrientation = function() {
  41258. // Convert from filter space to the the same system used by the
  41259. // deviceorientation event.
  41260. var orientation = this.filter.getOrientation();
  41261. // Predict orientation.
  41262. this.predictedQ = this.posePredictor.getPrediction(orientation, this.gyroscope, this.previousTimestampS);
  41263. // Convert to THREE coordinate system: -Z forward, Y up, X right.
  41264. var out = new MathUtil.Quaternion();
  41265. out.copy(this.filterToWorldQ);
  41266. out.multiply(this.resetQ);
  41267. if (!window.WebVRConfig.TOUCH_PANNER_DISABLED) {
  41268. out.multiply(this.touchPanner.getOrientation());
  41269. }
  41270. out.multiply(this.predictedQ);
  41271. out.multiply(this.worldToScreenQ);
  41272. // Handle the yaw-only case.
  41273. if (window.WebVRConfig.YAW_ONLY) {
  41274. // Make a quaternion that only turns around the Y-axis.
  41275. out.x = 0;
  41276. out.z = 0;
  41277. out.normalize();
  41278. }
  41279. this.orientationOut_[0] = out.x;
  41280. this.orientationOut_[1] = out.y;
  41281. this.orientationOut_[2] = out.z;
  41282. this.orientationOut_[3] = out.w;
  41283. return this.orientationOut_;
  41284. };
  41285. FusionPoseSensor.prototype.resetPose = function() {
  41286. // Reduce to inverted yaw-only.
  41287. this.resetQ.copy(this.filter.getOrientation());
  41288. this.resetQ.x = 0;
  41289. this.resetQ.y = 0;
  41290. this.resetQ.z *= -1;
  41291. this.resetQ.normalize();
  41292. // Take into account extra transformations in landscape mode.
  41293. if (Util.isLandscapeMode()) {
  41294. this.resetQ.multiply(this.inverseWorldToScreenQ);
  41295. }
  41296. // Take into account original pose.
  41297. this.resetQ.multiply(this.originalPoseAdjustQ);
  41298. if (!window.WebVRConfig.TOUCH_PANNER_DISABLED) {
  41299. this.touchPanner.resetSensor();
  41300. }
  41301. };
  41302. FusionPoseSensor.prototype.onDeviceMotion_ = function(deviceMotion) {
  41303. this.updateDeviceMotion_(deviceMotion);
  41304. };
  41305. FusionPoseSensor.prototype.updateDeviceMotion_ = function(deviceMotion) {
  41306. var accGravity = deviceMotion.accelerationIncludingGravity;
  41307. var rotRate = deviceMotion.rotationRate;
  41308. var timestampS = deviceMotion.timeStamp / 1000;
  41309. var deltaS = timestampS - this.previousTimestampS;
  41310. if (deltaS <= Util.MIN_TIMESTEP || deltaS > Util.MAX_TIMESTEP) {
  41311. console.warn('Invalid timestamps detected. Time step between successive ' +
  41312. 'gyroscope sensor samples is very small or not monotonic');
  41313. this.previousTimestampS = timestampS;
  41314. return;
  41315. }
  41316. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  41317. if (Util.isR7()) {
  41318. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  41319. } else {
  41320. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  41321. }
  41322. // With iOS and Firefox Android, rotationRate is reported in degrees,
  41323. // so we first convert to radians.
  41324. if (this.isIOS || this.isFirefoxAndroid) {
  41325. this.gyroscope.multiplyScalar(Math.PI / 180);
  41326. }
  41327. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  41328. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  41329. this.previousTimestampS = timestampS;
  41330. };
  41331. FusionPoseSensor.prototype.onOrientationChange_ = function(screenOrientation) {
  41332. this.setScreenTransform_();
  41333. };
  41334. /**
  41335. * This is only needed if we are in an cross origin iframe on iOS to work around
  41336. * this issue: https://bugs.webkit.org/show_bug.cgi?id=152299.
  41337. */
  41338. FusionPoseSensor.prototype.onMessage_ = function(event) {
  41339. var message = event.data;
  41340. // If there's no message type, ignore it.
  41341. if (!message || !message.type) {
  41342. return;
  41343. }
  41344. // Ignore all messages that aren't devicemotion.
  41345. var type = message.type.toLowerCase();
  41346. if (type !== 'devicemotion') {
  41347. return;
  41348. }
  41349. // Update device motion.
  41350. this.updateDeviceMotion_(message.deviceMotionEvent);
  41351. };
  41352. FusionPoseSensor.prototype.setScreenTransform_ = function() {
  41353. this.worldToScreenQ.set(0, 0, 0, 1);
  41354. switch (window.orientation) {
  41355. case 0:
  41356. break;
  41357. case 90:
  41358. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -Math.PI / 2);
  41359. break;
  41360. case -90:
  41361. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), Math.PI / 2);
  41362. break;
  41363. case 180:
  41364. // TODO.
  41365. break;
  41366. }
  41367. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  41368. this.inverseWorldToScreenQ.inverse();
  41369. };
  41370. FusionPoseSensor.prototype.start = function() {
  41371. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  41372. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  41373. this.onMessageCallback_ = this.onMessage_.bind(this);
  41374. // Only listen for postMessages if we're in an iOS and embedded inside a cross
  41375. // domain IFrame. In this case, the polyfill can still work if the containing
  41376. // page sends synthetic devicemotion events. For an example of this, see
  41377. // iframe-message-sender.js in VR View: https://goo.gl/XDtvFZ
  41378. if (Util.isIOS() && Util.isInsideCrossDomainIFrame()) {
  41379. window.addEventListener('message', this.onMessageCallback_);
  41380. }
  41381. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  41382. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  41383. };
  41384. FusionPoseSensor.prototype.stop = function() {
  41385. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  41386. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  41387. window.removeEventListener('message', this.onMessageCallback_);
  41388. };
  41389. module.exports = FusionPoseSensor;
  41390. },{"../math-util.js":59,"../touch-panner.js":67,"../util.js":68,"./complementary-filter.js":63,"./pose-predictor.js":65}],65:[function(_dereq_,module,exports){
  41391. /*
  41392. * Copyright 2015 Google Inc. All Rights Reserved.
  41393. * Licensed under the Apache License, Version 2.0 (the "License");
  41394. * you may not use this file except in compliance with the License.
  41395. * You may obtain a copy of the License at
  41396. *
  41397. * http://www.apache.org/licenses/LICENSE-2.0
  41398. *
  41399. * Unless required by applicable law or agreed to in writing, software
  41400. * distributed under the License is distributed on an "AS IS" BASIS,
  41401. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41402. * See the License for the specific language governing permissions and
  41403. * limitations under the License.
  41404. */
  41405. var MathUtil = _dereq_('../math-util');
  41406. var Util = _dereq_('../util');
  41407. /**
  41408. * Given an orientation and the gyroscope data, predicts the future orientation
  41409. * of the head. This makes rendering appear faster.
  41410. *
  41411. * Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf
  41412. *
  41413. * @param {Number} predictionTimeS time from head movement to the appearance of
  41414. * the corresponding image.
  41415. */
  41416. function PosePredictor(predictionTimeS) {
  41417. this.predictionTimeS = predictionTimeS;
  41418. // The quaternion corresponding to the previous state.
  41419. this.previousQ = new MathUtil.Quaternion();
  41420. // Previous time a prediction occurred.
  41421. this.previousTimestampS = null;
  41422. // The delta quaternion that adjusts the current pose.
  41423. this.deltaQ = new MathUtil.Quaternion();
  41424. // The output quaternion.
  41425. this.outQ = new MathUtil.Quaternion();
  41426. }
  41427. PosePredictor.prototype.getPrediction = function(currentQ, gyro, timestampS) {
  41428. if (!this.previousTimestampS) {
  41429. this.previousQ.copy(currentQ);
  41430. this.previousTimestampS = timestampS;
  41431. return currentQ;
  41432. }
  41433. // Calculate axis and angle based on gyroscope rotation rate data.
  41434. var axis = new MathUtil.Vector3();
  41435. axis.copy(gyro);
  41436. axis.normalize();
  41437. var angularSpeed = gyro.length();
  41438. // If we're rotating slowly, don't do prediction.
  41439. if (angularSpeed < MathUtil.degToRad * 20) {
  41440. if (Util.isDebug()) {
  41441. console.log('Moving slowly, at %s deg/s: no prediction',
  41442. (MathUtil.radToDeg * angularSpeed).toFixed(1));
  41443. }
  41444. this.outQ.copy(currentQ);
  41445. this.previousQ.copy(currentQ);
  41446. return this.outQ;
  41447. }
  41448. // Get the predicted angle based on the time delta and latency.
  41449. var deltaT = timestampS - this.previousTimestampS;
  41450. var predictAngle = angularSpeed * this.predictionTimeS;
  41451. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  41452. this.outQ.copy(this.previousQ);
  41453. this.outQ.multiply(this.deltaQ);
  41454. this.previousQ.copy(currentQ);
  41455. this.previousTimestampS = timestampS;
  41456. return this.outQ;
  41457. };
  41458. module.exports = PosePredictor;
  41459. },{"../math-util":59,"../util":68}],66:[function(_dereq_,module,exports){
  41460. function SensorSample(sample, timestampS) {
  41461. this.set(sample, timestampS);
  41462. };
  41463. SensorSample.prototype.set = function(sample, timestampS) {
  41464. this.sample = sample;
  41465. this.timestampS = timestampS;
  41466. };
  41467. SensorSample.prototype.copy = function(sensorSample) {
  41468. this.set(sensorSample.sample, sensorSample.timestampS);
  41469. };
  41470. module.exports = SensorSample;
  41471. },{}],67:[function(_dereq_,module,exports){
  41472. /*
  41473. * Copyright 2015 Google Inc. All Rights Reserved.
  41474. * Licensed under the Apache License, Version 2.0 (the "License");
  41475. * you may not use this file except in compliance with the License.
  41476. * You may obtain a copy of the License at
  41477. *
  41478. * http://www.apache.org/licenses/LICENSE-2.0
  41479. *
  41480. * Unless required by applicable law or agreed to in writing, software
  41481. * distributed under the License is distributed on an "AS IS" BASIS,
  41482. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41483. * See the License for the specific language governing permissions and
  41484. * limitations under the License.
  41485. */
  41486. var MathUtil = _dereq_('./math-util.js');
  41487. var Util = _dereq_('./util.js');
  41488. var ROTATE_SPEED = 0.5;
  41489. /**
  41490. * Provides a quaternion responsible for pre-panning the scene before further
  41491. * transformations due to device sensors.
  41492. */
  41493. function TouchPanner() {
  41494. window.addEventListener('touchstart', this.onTouchStart_.bind(this));
  41495. window.addEventListener('touchmove', this.onTouchMove_.bind(this));
  41496. window.addEventListener('touchend', this.onTouchEnd_.bind(this));
  41497. this.isTouching = false;
  41498. this.rotateStart = new MathUtil.Vector2();
  41499. this.rotateEnd = new MathUtil.Vector2();
  41500. this.rotateDelta = new MathUtil.Vector2();
  41501. this.theta = 0;
  41502. this.orientation = new MathUtil.Quaternion();
  41503. }
  41504. TouchPanner.prototype.getOrientation = function() {
  41505. this.orientation.setFromEulerXYZ(0, 0, this.theta);
  41506. return this.orientation;
  41507. };
  41508. TouchPanner.prototype.resetSensor = function() {
  41509. this.theta = 0;
  41510. };
  41511. TouchPanner.prototype.onTouchStart_ = function(e) {
  41512. // Only respond if there is exactly one touch.
  41513. // Note that the Daydream controller passes in a `touchstart` event with
  41514. // no `touches` property, so we must check for that case too.
  41515. if (!e.touches || e.touches.length != 1) {
  41516. return;
  41517. }
  41518. this.rotateStart.set(e.touches[0].pageX, e.touches[0].pageY);
  41519. this.isTouching = true;
  41520. };
  41521. TouchPanner.prototype.onTouchMove_ = function(e) {
  41522. if (!this.isTouching) {
  41523. return;
  41524. }
  41525. this.rotateEnd.set(e.touches[0].pageX, e.touches[0].pageY);
  41526. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  41527. this.rotateStart.copy(this.rotateEnd);
  41528. // On iOS, direction is inverted.
  41529. if (Util.isIOS()) {
  41530. this.rotateDelta.x *= -1;
  41531. }
  41532. var element = document.body;
  41533. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * ROTATE_SPEED;
  41534. };
  41535. TouchPanner.prototype.onTouchEnd_ = function(e) {
  41536. this.isTouching = false;
  41537. };
  41538. module.exports = TouchPanner;
  41539. },{"./math-util.js":59,"./util.js":68}],68:[function(_dereq_,module,exports){
  41540. /*
  41541. * Copyright 2015 Google Inc. All Rights Reserved.
  41542. * Licensed under the Apache License, Version 2.0 (the "License");
  41543. * you may not use this file except in compliance with the License.
  41544. * You may obtain a copy of the License at
  41545. *
  41546. * http://www.apache.org/licenses/LICENSE-2.0
  41547. *
  41548. * Unless required by applicable law or agreed to in writing, software
  41549. * distributed under the License is distributed on an "AS IS" BASIS,
  41550. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41551. * See the License for the specific language governing permissions and
  41552. * limitations under the License.
  41553. */
  41554. var Util = window.Util || {};
  41555. Util.MIN_TIMESTEP = 0.001;
  41556. Util.MAX_TIMESTEP = 1;
  41557. Util.base64 = function(mimeType, base64) {
  41558. return 'data:' + mimeType + ';base64,' + base64;
  41559. };
  41560. Util.clamp = function(value, min, max) {
  41561. return Math.min(Math.max(min, value), max);
  41562. };
  41563. Util.lerp = function(a, b, t) {
  41564. return a + ((b - a) * t);
  41565. };
  41566. /**
  41567. * Light polyfill for `Promise.race`. Returns
  41568. * a promise that resolves when the first promise
  41569. * provided resolves.
  41570. *
  41571. * @param {Array<Promise>} promises
  41572. */
  41573. Util.race = function(promises) {
  41574. if (Promise.race) {
  41575. return Promise.race(promises);
  41576. }
  41577. return new Promise(function (resolve, reject) {
  41578. for (var i = 0; i < promises.length; i++) {
  41579. promises[i].then(resolve, reject);
  41580. }
  41581. });
  41582. };
  41583. Util.isIOS = (function() {
  41584. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  41585. return function() {
  41586. return isIOS;
  41587. };
  41588. })();
  41589. Util.isWebViewAndroid = (function() {
  41590. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 &&
  41591. navigator.userAgent.indexOf('Android') !== -1 &&
  41592. navigator.userAgent.indexOf('Chrome') !== -1;
  41593. return function() {
  41594. return isWebViewAndroid;
  41595. };
  41596. })();
  41597. Util.isSafari = (function() {
  41598. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  41599. return function() {
  41600. return isSafari;
  41601. };
  41602. })();
  41603. Util.isFirefoxAndroid = (function() {
  41604. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 &&
  41605. navigator.userAgent.indexOf('Android') !== -1;
  41606. return function() {
  41607. return isFirefoxAndroid;
  41608. };
  41609. })();
  41610. Util.isR7 = (function() {
  41611. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  41612. return function() {
  41613. return isR7;
  41614. };
  41615. })();
  41616. Util.isLandscapeMode = function() {
  41617. var rtn = (window.orientation == 90 || window.orientation == -90);
  41618. return Util.isR7() ? !rtn : rtn;
  41619. };
  41620. // Helper method to validate the time steps of sensor timestamps.
  41621. Util.isTimestampDeltaValid = function(timestampDeltaS) {
  41622. if (isNaN(timestampDeltaS)) {
  41623. return false;
  41624. }
  41625. if (timestampDeltaS <= Util.MIN_TIMESTEP) {
  41626. return false;
  41627. }
  41628. if (timestampDeltaS > Util.MAX_TIMESTEP) {
  41629. return false;
  41630. }
  41631. return true;
  41632. };
  41633. Util.getScreenWidth = function() {
  41634. return Math.max(window.screen.width, window.screen.height) *
  41635. window.devicePixelRatio;
  41636. };
  41637. Util.getScreenHeight = function() {
  41638. return Math.min(window.screen.width, window.screen.height) *
  41639. window.devicePixelRatio;
  41640. };
  41641. Util.requestFullscreen = function(element) {
  41642. if (Util.isWebViewAndroid()) {
  41643. return false;
  41644. }
  41645. if (element.requestFullscreen) {
  41646. element.requestFullscreen();
  41647. } else if (element.webkitRequestFullscreen) {
  41648. element.webkitRequestFullscreen();
  41649. } else if (element.mozRequestFullScreen) {
  41650. element.mozRequestFullScreen();
  41651. } else if (element.msRequestFullscreen) {
  41652. element.msRequestFullscreen();
  41653. } else {
  41654. return false;
  41655. }
  41656. return true;
  41657. };
  41658. Util.exitFullscreen = function() {
  41659. if (document.exitFullscreen) {
  41660. document.exitFullscreen();
  41661. } else if (document.webkitExitFullscreen) {
  41662. document.webkitExitFullscreen();
  41663. } else if (document.mozCancelFullScreen) {
  41664. document.mozCancelFullScreen();
  41665. } else if (document.msExitFullscreen) {
  41666. document.msExitFullscreen();
  41667. } else {
  41668. return false;
  41669. }
  41670. return true;
  41671. };
  41672. Util.getFullscreenElement = function() {
  41673. return document.fullscreenElement ||
  41674. document.webkitFullscreenElement ||
  41675. document.mozFullScreenElement ||
  41676. document.msFullscreenElement;
  41677. };
  41678. Util.linkProgram = function(gl, vertexSource, fragmentSource, attribLocationMap) {
  41679. // No error checking for brevity.
  41680. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  41681. gl.shaderSource(vertexShader, vertexSource);
  41682. gl.compileShader(vertexShader);
  41683. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  41684. gl.shaderSource(fragmentShader, fragmentSource);
  41685. gl.compileShader(fragmentShader);
  41686. var program = gl.createProgram();
  41687. gl.attachShader(program, vertexShader);
  41688. gl.attachShader(program, fragmentShader);
  41689. for (var attribName in attribLocationMap)
  41690. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  41691. gl.linkProgram(program);
  41692. gl.deleteShader(vertexShader);
  41693. gl.deleteShader(fragmentShader);
  41694. return program;
  41695. };
  41696. Util.getProgramUniforms = function(gl, program) {
  41697. var uniforms = {};
  41698. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  41699. var uniformName = '';
  41700. for (var i = 0; i < uniformCount; i++) {
  41701. var uniformInfo = gl.getActiveUniform(program, i);
  41702. uniformName = uniformInfo.name.replace('[0]', '');
  41703. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  41704. }
  41705. return uniforms;
  41706. };
  41707. Util.orthoMatrix = function (out, left, right, bottom, top, near, far) {
  41708. var lr = 1 / (left - right),
  41709. bt = 1 / (bottom - top),
  41710. nf = 1 / (near - far);
  41711. out[0] = -2 * lr;
  41712. out[1] = 0;
  41713. out[2] = 0;
  41714. out[3] = 0;
  41715. out[4] = 0;
  41716. out[5] = -2 * bt;
  41717. out[6] = 0;
  41718. out[7] = 0;
  41719. out[8] = 0;
  41720. out[9] = 0;
  41721. out[10] = 2 * nf;
  41722. out[11] = 0;
  41723. out[12] = (left + right) * lr;
  41724. out[13] = (top + bottom) * bt;
  41725. out[14] = (far + near) * nf;
  41726. out[15] = 1;
  41727. return out;
  41728. };
  41729. Util.copyArray = function (source, dest) {
  41730. for (var i = 0, n = source.length; i < n; i++) {
  41731. dest[i] = source[i];
  41732. }
  41733. };
  41734. Util.isMobile = function() {
  41735. var check = false;
  41736. (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);
  41737. return check;
  41738. };
  41739. Util.extend = function(dest, src) {
  41740. for (var key in src) {
  41741. if (src.hasOwnProperty(key)) {
  41742. dest[key] = src[key];
  41743. }
  41744. }
  41745. return dest;
  41746. }
  41747. Util.safariCssSizeWorkaround = function(canvas) {
  41748. // TODO(smus): Remove this workaround when Safari for iOS is fixed.
  41749. // iOS only workaround (for https://bugs.webkit.org/show_bug.cgi?id=152556).
  41750. //
  41751. // "To the last I grapple with thee;
  41752. // from hell's heart I stab at thee;
  41753. // for hate's sake I spit my last breath at thee."
  41754. // -- Moby Dick, by Herman Melville
  41755. if (Util.isIOS()) {
  41756. var width = canvas.style.width;
  41757. var height = canvas.style.height;
  41758. canvas.style.width = (parseInt(width) + 1) + 'px';
  41759. canvas.style.height = (parseInt(height)) + 'px';
  41760. setTimeout(function() {
  41761. canvas.style.width = width;
  41762. canvas.style.height = height;
  41763. }, 100);
  41764. }
  41765. // Debug only.
  41766. window.Util = Util;
  41767. window.canvas = canvas;
  41768. };
  41769. Util.isDebug = function() {
  41770. return Util.getQueryParameter('debug');
  41771. };
  41772. Util.getQueryParameter = function(name) {
  41773. var name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  41774. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  41775. results = regex.exec(location.search);
  41776. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  41777. };
  41778. Util.frameDataFromPose = (function() {
  41779. var piOver180 = Math.PI / 180.0;
  41780. var rad45 = Math.PI * 0.25;
  41781. // Borrowed from glMatrix.
  41782. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  41783. var upTan = Math.tan(fov ? (fov.upDegrees * piOver180) : rad45),
  41784. downTan = Math.tan(fov ? (fov.downDegrees * piOver180) : rad45),
  41785. leftTan = Math.tan(fov ? (fov.leftDegrees * piOver180) : rad45),
  41786. rightTan = Math.tan(fov ? (fov.rightDegrees * piOver180) : rad45),
  41787. xScale = 2.0 / (leftTan + rightTan),
  41788. yScale = 2.0 / (upTan + downTan);
  41789. out[0] = xScale;
  41790. out[1] = 0.0;
  41791. out[2] = 0.0;
  41792. out[3] = 0.0;
  41793. out[4] = 0.0;
  41794. out[5] = yScale;
  41795. out[6] = 0.0;
  41796. out[7] = 0.0;
  41797. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  41798. out[9] = ((upTan - downTan) * yScale * 0.5);
  41799. out[10] = far / (near - far);
  41800. out[11] = -1.0;
  41801. out[12] = 0.0;
  41802. out[13] = 0.0;
  41803. out[14] = (far * near) / (near - far);
  41804. out[15] = 0.0;
  41805. return out;
  41806. }
  41807. function mat4_fromRotationTranslation(out, q, v) {
  41808. // Quaternion math
  41809. var x = q[0], y = q[1], z = q[2], w = q[3],
  41810. x2 = x + x,
  41811. y2 = y + y,
  41812. z2 = z + z,
  41813. xx = x * x2,
  41814. xy = x * y2,
  41815. xz = x * z2,
  41816. yy = y * y2,
  41817. yz = y * z2,
  41818. zz = z * z2,
  41819. wx = w * x2,
  41820. wy = w * y2,
  41821. wz = w * z2;
  41822. out[0] = 1 - (yy + zz);
  41823. out[1] = xy + wz;
  41824. out[2] = xz - wy;
  41825. out[3] = 0;
  41826. out[4] = xy - wz;
  41827. out[5] = 1 - (xx + zz);
  41828. out[6] = yz + wx;
  41829. out[7] = 0;
  41830. out[8] = xz + wy;
  41831. out[9] = yz - wx;
  41832. out[10] = 1 - (xx + yy);
  41833. out[11] = 0;
  41834. out[12] = v[0];
  41835. out[13] = v[1];
  41836. out[14] = v[2];
  41837. out[15] = 1;
  41838. return out;
  41839. };
  41840. function mat4_translate(out, a, v) {
  41841. var x = v[0], y = v[1], z = v[2],
  41842. a00, a01, a02, a03,
  41843. a10, a11, a12, a13,
  41844. a20, a21, a22, a23;
  41845. if (a === out) {
  41846. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  41847. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  41848. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  41849. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  41850. } else {
  41851. a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
  41852. a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
  41853. a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
  41854. out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
  41855. out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
  41856. out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
  41857. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  41858. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  41859. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  41860. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  41861. }
  41862. return out;
  41863. };
  41864. function mat4_invert(out, a) {
  41865. var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
  41866. a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
  41867. a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
  41868. a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
  41869. b00 = a00 * a11 - a01 * a10,
  41870. b01 = a00 * a12 - a02 * a10,
  41871. b02 = a00 * a13 - a03 * a10,
  41872. b03 = a01 * a12 - a02 * a11,
  41873. b04 = a01 * a13 - a03 * a11,
  41874. b05 = a02 * a13 - a03 * a12,
  41875. b06 = a20 * a31 - a21 * a30,
  41876. b07 = a20 * a32 - a22 * a30,
  41877. b08 = a20 * a33 - a23 * a30,
  41878. b09 = a21 * a32 - a22 * a31,
  41879. b10 = a21 * a33 - a23 * a31,
  41880. b11 = a22 * a33 - a23 * a32,
  41881. // Calculate the determinant
  41882. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  41883. if (!det) {
  41884. return null;
  41885. }
  41886. det = 1.0 / det;
  41887. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  41888. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  41889. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  41890. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  41891. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  41892. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  41893. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  41894. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  41895. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  41896. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  41897. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  41898. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  41899. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  41900. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  41901. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  41902. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  41903. return out;
  41904. };
  41905. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  41906. var defaultPosition = new Float32Array([0, 0, 0]);
  41907. function updateEyeMatrices(projection, view, pose, parameters, vrDisplay) {
  41908. mat4_perspectiveFromFieldOfView(projection, parameters ? parameters.fieldOfView : null, vrDisplay.depthNear, vrDisplay.depthFar);
  41909. var orientation = pose.orientation || defaultOrientation;
  41910. var position = pose.position || defaultPosition;
  41911. mat4_fromRotationTranslation(view, orientation, position);
  41912. if (parameters)
  41913. mat4_translate(view, view, parameters.offset);
  41914. mat4_invert(view, view);
  41915. }
  41916. return function(frameData, pose, vrDisplay) {
  41917. if (!frameData || !pose)
  41918. return false;
  41919. frameData.pose = pose;
  41920. frameData.timestamp = pose.timestamp;
  41921. updateEyeMatrices(
  41922. frameData.leftProjectionMatrix, frameData.leftViewMatrix,
  41923. pose, vrDisplay.getEyeParameters("left"), vrDisplay);
  41924. updateEyeMatrices(
  41925. frameData.rightProjectionMatrix, frameData.rightViewMatrix,
  41926. pose, vrDisplay.getEyeParameters("right"), vrDisplay);
  41927. return true;
  41928. };
  41929. })();
  41930. Util.isInsideCrossDomainIFrame = function() {
  41931. var isFramed = (window.self !== window.top);
  41932. var refDomain = Util.getDomainFromUrl(document.referrer);
  41933. var thisDomain = Util.getDomainFromUrl(window.location.href);
  41934. return isFramed && (refDomain !== thisDomain);
  41935. };
  41936. // From http://stackoverflow.com/a/23945027.
  41937. Util.getDomainFromUrl = function(url) {
  41938. var domain;
  41939. // Find & remove protocol (http, ftp, etc.) and get domain.
  41940. if (url.indexOf("://") > -1) {
  41941. domain = url.split('/')[2];
  41942. }
  41943. else {
  41944. domain = url.split('/')[0];
  41945. }
  41946. //find & remove port number
  41947. domain = domain.split(':')[0];
  41948. return domain;
  41949. }
  41950. module.exports = Util;
  41951. },{}],69:[function(_dereq_,module,exports){
  41952. /*
  41953. * Copyright 2015 Google Inc. All Rights Reserved.
  41954. * Licensed under the Apache License, Version 2.0 (the "License");
  41955. * you may not use this file except in compliance with the License.
  41956. * You may obtain a copy of the License at
  41957. *
  41958. * http://www.apache.org/licenses/LICENSE-2.0
  41959. *
  41960. * Unless required by applicable law or agreed to in writing, software
  41961. * distributed under the License is distributed on an "AS IS" BASIS,
  41962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41963. * See the License for the specific language governing permissions and
  41964. * limitations under the License.
  41965. */
  41966. var DeviceInfo = _dereq_('./device-info.js');
  41967. var Util = _dereq_('./util.js');
  41968. var DEFAULT_VIEWER = 'CardboardV1';
  41969. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  41970. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  41971. /**
  41972. * Creates a viewer selector with the options specified. Supports being shown
  41973. * and hidden. Generates events when viewer parameters change. Also supports
  41974. * saving the currently selected index in localStorage.
  41975. */
  41976. function ViewerSelector() {
  41977. // Try to load the selected key from local storage.
  41978. try {
  41979. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  41980. } catch (error) {
  41981. console.error('Failed to load viewer profile: %s', error);
  41982. }
  41983. //If none exists, or if localstorage is unavailable, use the default key.
  41984. if (!this.selectedKey) {
  41985. this.selectedKey = DEFAULT_VIEWER;
  41986. }
  41987. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  41988. this.root = null;
  41989. this.onChangeCallbacks_ = [];
  41990. }
  41991. ViewerSelector.prototype.show = function(root) {
  41992. this.root = root;
  41993. root.appendChild(this.dialog);
  41994. // Ensure the currently selected item is checked.
  41995. var selected = this.dialog.querySelector('#' + this.selectedKey);
  41996. selected.checked = true;
  41997. // Show the UI.
  41998. this.dialog.style.display = 'block';
  41999. };
  42000. ViewerSelector.prototype.hide = function() {
  42001. if (this.root && this.root.contains(this.dialog)) {
  42002. this.root.removeChild(this.dialog);
  42003. }
  42004. this.dialog.style.display = 'none';
  42005. };
  42006. ViewerSelector.prototype.getCurrentViewer = function() {
  42007. return DeviceInfo.Viewers[this.selectedKey];
  42008. };
  42009. ViewerSelector.prototype.getSelectedKey_ = function() {
  42010. var input = this.dialog.querySelector('input[name=field]:checked');
  42011. if (input) {
  42012. return input.id;
  42013. }
  42014. return null;
  42015. };
  42016. ViewerSelector.prototype.onChange = function(cb) {
  42017. this.onChangeCallbacks_.push(cb);
  42018. };
  42019. ViewerSelector.prototype.fireOnChange_ = function(viewer) {
  42020. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  42021. this.onChangeCallbacks_[i](viewer);
  42022. }
  42023. };
  42024. ViewerSelector.prototype.onSave_ = function() {
  42025. this.selectedKey = this.getSelectedKey_();
  42026. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  42027. console.error('ViewerSelector.onSave_: this should never happen!');
  42028. return;
  42029. }
  42030. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  42031. // Attempt to save the viewer profile, but fails in private mode.
  42032. try {
  42033. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  42034. } catch(error) {
  42035. console.error('Failed to save viewer profile: %s', error);
  42036. }
  42037. this.hide();
  42038. };
  42039. /**
  42040. * Creates the dialog.
  42041. */
  42042. ViewerSelector.prototype.createDialog_ = function(options) {
  42043. var container = document.createElement('div');
  42044. container.classList.add(CLASS_NAME);
  42045. container.style.display = 'none';
  42046. // Create an overlay that dims the background, and which goes away when you
  42047. // tap it.
  42048. var overlay = document.createElement('div');
  42049. var s = overlay.style;
  42050. s.position = 'fixed';
  42051. s.left = 0;
  42052. s.top = 0;
  42053. s.width = '100%';
  42054. s.height = '100%';
  42055. s.background = 'rgba(0, 0, 0, 0.3)';
  42056. overlay.addEventListener('click', this.hide.bind(this));
  42057. var width = 280;
  42058. var dialog = document.createElement('div');
  42059. var s = dialog.style;
  42060. s.boxSizing = 'border-box';
  42061. s.position = 'fixed';
  42062. s.top = '24px';
  42063. s.left = '50%';
  42064. s.marginLeft = (-width/2) + 'px';
  42065. s.width = width + 'px';
  42066. s.padding = '24px';
  42067. s.overflow = 'hidden';
  42068. s.background = '#fafafa';
  42069. s.fontFamily = "'Roboto', sans-serif";
  42070. s.boxShadow = '0px 5px 20px #666';
  42071. dialog.appendChild(this.createH1_('Select your viewer'));
  42072. for (var id in options) {
  42073. dialog.appendChild(this.createChoice_(id, options[id].label));
  42074. }
  42075. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  42076. container.appendChild(overlay);
  42077. container.appendChild(dialog);
  42078. return container;
  42079. };
  42080. ViewerSelector.prototype.createH1_ = function(name) {
  42081. var h1 = document.createElement('h1');
  42082. var s = h1.style;
  42083. s.color = 'black';
  42084. s.fontSize = '20px';
  42085. s.fontWeight = 'bold';
  42086. s.marginTop = 0;
  42087. s.marginBottom = '24px';
  42088. h1.innerHTML = name;
  42089. return h1;
  42090. };
  42091. ViewerSelector.prototype.createChoice_ = function(id, name) {
  42092. /*
  42093. <div class="choice">
  42094. <input id="v1" type="radio" name="field" value="v1">
  42095. <label for="v1">Cardboard V1</label>
  42096. </div>
  42097. */
  42098. var div = document.createElement('div');
  42099. div.style.marginTop = '8px';
  42100. div.style.color = 'black';
  42101. var input = document.createElement('input');
  42102. input.style.fontSize = '30px';
  42103. input.setAttribute('id', id);
  42104. input.setAttribute('type', 'radio');
  42105. input.setAttribute('value', id);
  42106. input.setAttribute('name', 'field');
  42107. var label = document.createElement('label');
  42108. label.style.marginLeft = '4px';
  42109. label.setAttribute('for', id);
  42110. label.innerHTML = name;
  42111. div.appendChild(input);
  42112. div.appendChild(label);
  42113. return div;
  42114. };
  42115. ViewerSelector.prototype.createButton_ = function(label, onclick) {
  42116. var button = document.createElement('button');
  42117. button.innerHTML = label;
  42118. var s = button.style;
  42119. s.float = 'right';
  42120. s.textTransform = 'uppercase';
  42121. s.color = '#1094f7';
  42122. s.fontSize = '14px';
  42123. s.letterSpacing = 0;
  42124. s.border = 0;
  42125. s.background = 'none';
  42126. s.marginTop = '16px';
  42127. button.addEventListener('click', onclick);
  42128. return button;
  42129. };
  42130. module.exports = ViewerSelector;
  42131. },{"./device-info.js":53,"./util.js":68}],70:[function(_dereq_,module,exports){
  42132. /*
  42133. * Copyright 2015 Google Inc. All Rights Reserved.
  42134. * Licensed under the Apache License, Version 2.0 (the "License");
  42135. * you may not use this file except in compliance with the License.
  42136. * You may obtain a copy of the License at
  42137. *
  42138. * http://www.apache.org/licenses/LICENSE-2.0
  42139. *
  42140. * Unless required by applicable law or agreed to in writing, software
  42141. * distributed under the License is distributed on an "AS IS" BASIS,
  42142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42143. * See the License for the specific language governing permissions and
  42144. * limitations under the License.
  42145. */
  42146. var Util = _dereq_('./util.js');
  42147. /**
  42148. * Android and iOS compatible wakelock implementation.
  42149. *
  42150. * Refactored thanks to dkovalev@.
  42151. */
  42152. function AndroidWakeLock() {
  42153. var video = document.createElement('video');
  42154. video.setAttribute('loop', '');
  42155. function addSourceToVideo(element, type, dataURI) {
  42156. var source = document.createElement('source');
  42157. source.src = dataURI;
  42158. source.type = 'video/' + type;
  42159. element.appendChild(source);
  42160. }
  42161. addSourceToVideo(video,'webm', Util.base64('video/webm', 'GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='));
  42162. addSourceToVideo(video, 'mp4', Util.base64('video/mp4', 'AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=='));
  42163. this.request = function() {
  42164. if (video.paused) {
  42165. video.play();
  42166. }
  42167. };
  42168. this.release = function() {
  42169. video.pause();
  42170. };
  42171. }
  42172. function iOSWakeLock() {
  42173. var timer = null;
  42174. this.request = function() {
  42175. if (!timer) {
  42176. timer = setInterval(function() {
  42177. window.location = window.location;
  42178. setTimeout(window.stop, 0);
  42179. }, 30000);
  42180. }
  42181. }
  42182. this.release = function() {
  42183. if (timer) {
  42184. clearInterval(timer);
  42185. timer = null;
  42186. }
  42187. }
  42188. }
  42189. function getWakeLock() {
  42190. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  42191. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  42192. return iOSWakeLock;
  42193. } else {
  42194. return AndroidWakeLock;
  42195. }
  42196. }
  42197. module.exports = getWakeLock();
  42198. },{"./util.js":68}],71:[function(_dereq_,module,exports){
  42199. /*
  42200. * Copyright 2015 Google Inc. All Rights Reserved.
  42201. * Licensed under the Apache License, Version 2.0 (the "License");
  42202. * you may not use this file except in compliance with the License.
  42203. * You may obtain a copy of the License at
  42204. *
  42205. * http://www.apache.org/licenses/LICENSE-2.0
  42206. *
  42207. * Unless required by applicable law or agreed to in writing, software
  42208. * distributed under the License is distributed on an "AS IS" BASIS,
  42209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42210. * See the License for the specific language governing permissions and
  42211. * limitations under the License.
  42212. */
  42213. var Util = _dereq_('./util.js');
  42214. var CardboardVRDisplay = _dereq_('./cardboard-vr-display.js');
  42215. var MouseKeyboardVRDisplay = _dereq_('./mouse-keyboard-vr-display.js');
  42216. // Uncomment to add positional tracking via webcam.
  42217. //var WebcamPositionSensorVRDevice = require('./webcam-position-sensor-vr-device.js');
  42218. var VRDisplay = _dereq_('./base.js').VRDisplay;
  42219. var VRFrameData = _dereq_('./base.js').VRFrameData;
  42220. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  42221. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  42222. var VRDisplayHMDDevice = _dereq_('./display-wrappers.js').VRDisplayHMDDevice;
  42223. var VRDisplayPositionSensorDevice = _dereq_('./display-wrappers.js').VRDisplayPositionSensorDevice;
  42224. var version = _dereq_('../package.json').version;
  42225. function WebVRPolyfill() {
  42226. this.displays = [];
  42227. this.devices = []; // For deprecated objects
  42228. this.devicesPopulated = false;
  42229. this.nativeWebVRAvailable = this.isWebVRAvailable();
  42230. this.nativeLegacyWebVRAvailable = this.isDeprecatedWebVRAvailable();
  42231. this.nativeGetVRDisplaysFunc = this.nativeWebVRAvailable ?
  42232. navigator.getVRDisplays :
  42233. null;
  42234. if (!this.nativeLegacyWebVRAvailable && !this.nativeWebVRAvailable) {
  42235. this.enablePolyfill();
  42236. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42237. this.enableDeprecatedPolyfill();
  42238. }
  42239. }
  42240. // Put a shim in place to update the API to 1.1 if needed.
  42241. InstallWebVRSpecShim();
  42242. }
  42243. WebVRPolyfill.prototype.isWebVRAvailable = function() {
  42244. return ('getVRDisplays' in navigator);
  42245. };
  42246. WebVRPolyfill.prototype.isDeprecatedWebVRAvailable = function() {
  42247. return ('getVRDevices' in navigator) || ('mozGetVRDevices' in navigator);
  42248. };
  42249. WebVRPolyfill.prototype.connectDisplay = function(vrDisplay) {
  42250. vrDisplay.fireVRDisplayConnect_();
  42251. this.displays.push(vrDisplay);
  42252. };
  42253. WebVRPolyfill.prototype.populateDevices = function() {
  42254. if (this.devicesPopulated) {
  42255. return;
  42256. }
  42257. // Initialize our virtual VR devices.
  42258. var vrDisplay = null;
  42259. // Add a Cardboard VRDisplay on compatible mobile devices
  42260. if (this.isCardboardCompatible()) {
  42261. vrDisplay = new CardboardVRDisplay();
  42262. this.connectDisplay(vrDisplay);
  42263. // For backwards compatibility
  42264. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42265. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42266. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42267. }
  42268. }
  42269. // Add a Mouse and Keyboard driven VRDisplay for desktops/laptops
  42270. if (!this.isMobile() && !window.WebVRConfig.MOUSE_KEYBOARD_CONTROLS_DISABLED) {
  42271. vrDisplay = new MouseKeyboardVRDisplay();
  42272. this.connectDisplay(vrDisplay);
  42273. // For backwards compatibility
  42274. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42275. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42276. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42277. }
  42278. }
  42279. // Uncomment to add positional tracking via webcam.
  42280. //if (!this.isMobile() && window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42281. // positionDevice = new WebcamPositionSensorVRDevice();
  42282. // this.devices.push(positionDevice);
  42283. //}
  42284. this.devicesPopulated = true;
  42285. };
  42286. WebVRPolyfill.prototype.enablePolyfill = function() {
  42287. // Provide navigator.getVRDisplays.
  42288. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  42289. // Polyfill native VRDisplay.getFrameData
  42290. if (this.nativeWebVRAvailable && window.VRFrameData) {
  42291. var NativeVRFrameData = window.VRFrameData;
  42292. var nativeFrameData = new window.VRFrameData();
  42293. var nativeGetFrameData = window.VRDisplay.prototype.getFrameData;
  42294. window.VRFrameData = VRFrameData;
  42295. window.VRDisplay.prototype.getFrameData = function(frameData) {
  42296. if (frameData instanceof NativeVRFrameData) {
  42297. nativeGetFrameData.call(this, frameData);
  42298. return;
  42299. }
  42300. /*
  42301. Copy frame data from the native object into the polyfilled object.
  42302. */
  42303. nativeGetFrameData.call(this, nativeFrameData);
  42304. frameData.pose = nativeFrameData.pose;
  42305. Util.copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  42306. Util.copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  42307. Util.copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  42308. Util.copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  42309. //todo: copy
  42310. };
  42311. }
  42312. // Provide the `VRDisplay` object.
  42313. window.VRDisplay = VRDisplay;
  42314. // Provide the `navigator.vrEnabled` property.
  42315. if (navigator && typeof navigator.vrEnabled === 'undefined') {
  42316. var self = this;
  42317. Object.defineProperty(navigator, 'vrEnabled', {
  42318. get: function () {
  42319. return self.isCardboardCompatible() &&
  42320. (self.isFullScreenAvailable() || Util.isIOS());
  42321. }
  42322. });
  42323. }
  42324. if (!('VRFrameData' in window)) {
  42325. // Provide the VRFrameData object.
  42326. window.VRFrameData = VRFrameData;
  42327. }
  42328. };
  42329. WebVRPolyfill.prototype.enableDeprecatedPolyfill = function() {
  42330. // Provide navigator.getVRDevices.
  42331. navigator.getVRDevices = this.getVRDevices.bind(this);
  42332. // Provide the CardboardHMDVRDevice and PositionSensorVRDevice objects.
  42333. window.HMDVRDevice = HMDVRDevice;
  42334. window.PositionSensorVRDevice = PositionSensorVRDevice;
  42335. };
  42336. WebVRPolyfill.prototype.getVRDisplays = function() {
  42337. this.populateDevices();
  42338. var polyfillDisplays = this.displays;
  42339. if (!this.nativeWebVRAvailable) {
  42340. return Promise.resolve(polyfillDisplays);
  42341. }
  42342. // Set up a race condition if this browser has a bug where
  42343. // `navigator.getVRDisplays()` never resolves.
  42344. var timeoutId;
  42345. var vrDisplaysNative = this.nativeGetVRDisplaysFunc.call(navigator);
  42346. var timeoutPromise = new Promise(function(resolve) {
  42347. timeoutId = setTimeout(function() {
  42348. console.warn('Native WebVR implementation detected, but `getVRDisplays()` failed to resolve. Falling back to polyfill.');
  42349. resolve([]);
  42350. }, window.WebVRConfig.GET_VR_DISPLAYS_TIMEOUT);
  42351. });
  42352. return Util.race([
  42353. vrDisplaysNative,
  42354. timeoutPromise
  42355. ]).then(function(nativeDisplays) {
  42356. clearTimeout(timeoutId);
  42357. if (window.WebVRConfig.ALWAYS_APPEND_POLYFILL_DISPLAY) {
  42358. return nativeDisplays.concat(polyfillDisplays);
  42359. } else {
  42360. return nativeDisplays.length > 0 ? nativeDisplays : polyfillDisplays;
  42361. }
  42362. });
  42363. };
  42364. WebVRPolyfill.prototype.getVRDevices = function() {
  42365. console.warn('getVRDevices is deprecated. Please update your code to use getVRDisplays instead.');
  42366. var self = this;
  42367. return new Promise(function(resolve, reject) {
  42368. try {
  42369. if (!self.devicesPopulated) {
  42370. if (self.nativeWebVRAvailable) {
  42371. return navigator.getVRDisplays(function(displays) {
  42372. for (var i = 0; i < displays.length; ++i) {
  42373. self.devices.push(new VRDisplayHMDDevice(displays[i]));
  42374. self.devices.push(new VRDisplayPositionSensorDevice(displays[i]));
  42375. }
  42376. self.devicesPopulated = true;
  42377. resolve(self.devices);
  42378. }, reject);
  42379. }
  42380. if (self.nativeLegacyWebVRAvailable) {
  42381. return (navigator.getVRDDevices || navigator.mozGetVRDevices)(function(devices) {
  42382. for (var i = 0; i < devices.length; ++i) {
  42383. if (devices[i] instanceof HMDVRDevice) {
  42384. self.devices.push(devices[i]);
  42385. }
  42386. if (devices[i] instanceof PositionSensorVRDevice) {
  42387. self.devices.push(devices[i]);
  42388. }
  42389. }
  42390. self.devicesPopulated = true;
  42391. resolve(self.devices);
  42392. }, reject);
  42393. }
  42394. }
  42395. self.populateDevices();
  42396. resolve(self.devices);
  42397. } catch (e) {
  42398. reject(e);
  42399. }
  42400. });
  42401. };
  42402. WebVRPolyfill.prototype.NativeVRFrameData = window.VRFrameData;
  42403. /**
  42404. * Determine if a device is mobile.
  42405. */
  42406. WebVRPolyfill.prototype.isMobile = function() {
  42407. return /Android/i.test(navigator.userAgent) ||
  42408. /iPhone|iPad|iPod/i.test(navigator.userAgent);
  42409. };
  42410. WebVRPolyfill.prototype.isCardboardCompatible = function() {
  42411. // For now, support all iOS and Android devices.
  42412. // Also enable the WebVRConfig.FORCE_VR flag for debugging.
  42413. return this.isMobile() || window.WebVRConfig.FORCE_ENABLE_VR;
  42414. };
  42415. WebVRPolyfill.prototype.isFullScreenAvailable = function() {
  42416. return (document.fullscreenEnabled ||
  42417. document.mozFullScreenEnabled ||
  42418. document.webkitFullscreenEnabled ||
  42419. false);
  42420. };
  42421. // Installs a shim that updates a WebVR 1.0 spec implementation to WebVR 1.1
  42422. function InstallWebVRSpecShim() {
  42423. if ('VRDisplay' in window && !('VRFrameData' in window)) {
  42424. // Provide the VRFrameData object.
  42425. window.VRFrameData = VRFrameData;
  42426. // A lot of Chrome builds don't have depthNear and depthFar, even
  42427. // though they're in the WebVR 1.0 spec. Patch them in if they're not present.
  42428. if(!('depthNear' in window.VRDisplay.prototype)) {
  42429. window.VRDisplay.prototype.depthNear = 0.01;
  42430. }
  42431. if(!('depthFar' in window.VRDisplay.prototype)) {
  42432. window.VRDisplay.prototype.depthFar = 10000.0;
  42433. }
  42434. window.VRDisplay.prototype.getFrameData = function(frameData) {
  42435. return Util.frameDataFromPose(frameData, this.getPose(), this);
  42436. }
  42437. }
  42438. };
  42439. WebVRPolyfill.InstallWebVRSpecShim = InstallWebVRSpecShim;
  42440. WebVRPolyfill.version = version;
  42441. module.exports.WebVRPolyfill = WebVRPolyfill;
  42442. },{"../package.json":47,"./base.js":48,"./cardboard-vr-display.js":51,"./display-wrappers.js":54,"./mouse-keyboard-vr-display.js":60,"./util.js":68}],72:[function(_dereq_,module,exports){
  42443. var newline = /\n/
  42444. var newlineChar = '\n'
  42445. var whitespace = /\s/
  42446. module.exports = function(text, opt) {
  42447. var lines = module.exports.lines(text, opt)
  42448. return lines.map(function(line) {
  42449. return text.substring(line.start, line.end)
  42450. }).join('\n')
  42451. }
  42452. module.exports.lines = function wordwrap(text, opt) {
  42453. opt = opt||{}
  42454. //zero width results in nothing visible
  42455. if (opt.width === 0 && opt.mode !== 'nowrap')
  42456. return []
  42457. text = text||''
  42458. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  42459. var start = Math.max(0, opt.start||0)
  42460. var end = typeof opt.end === 'number' ? opt.end : text.length
  42461. var mode = opt.mode
  42462. var measure = opt.measure || monospace
  42463. if (mode === 'pre')
  42464. return pre(measure, text, start, end, width)
  42465. else
  42466. return greedy(measure, text, start, end, width, mode)
  42467. }
  42468. function idxOf(text, chr, start, end) {
  42469. var idx = text.indexOf(chr, start)
  42470. if (idx === -1 || idx > end)
  42471. return end
  42472. return idx
  42473. }
  42474. function isWhitespace(chr) {
  42475. return whitespace.test(chr)
  42476. }
  42477. function pre(measure, text, start, end, width) {
  42478. var lines = []
  42479. var lineStart = start
  42480. for (var i=start; i<end && i<text.length; i++) {
  42481. var chr = text.charAt(i)
  42482. var isNewline = newline.test(chr)
  42483. //If we've reached a newline, then step down a line
  42484. //Or if we've reached the EOF
  42485. if (isNewline || i===end-1) {
  42486. var lineEnd = isNewline ? i : i+1
  42487. var measured = measure(text, lineStart, lineEnd, width)
  42488. lines.push(measured)
  42489. lineStart = i+1
  42490. }
  42491. }
  42492. return lines
  42493. }
  42494. function greedy(measure, text, start, end, width, mode) {
  42495. //A greedy word wrapper based on LibGDX algorithm
  42496. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  42497. var lines = []
  42498. var testWidth = width
  42499. //if 'nowrap' is specified, we only wrap on newline chars
  42500. if (mode === 'nowrap')
  42501. testWidth = Number.MAX_VALUE
  42502. while (start < end && start < text.length) {
  42503. //get next newline position
  42504. var newLine = idxOf(text, newlineChar, start, end)
  42505. //eat whitespace at start of line
  42506. while (start < newLine) {
  42507. if (!isWhitespace( text.charAt(start) ))
  42508. break
  42509. start++
  42510. }
  42511. //determine visible # of glyphs for the available width
  42512. var measured = measure(text, start, newLine, testWidth)
  42513. var lineEnd = start + (measured.end-measured.start)
  42514. var nextStart = lineEnd + newlineChar.length
  42515. //if we had to cut the line before the next newline...
  42516. if (lineEnd < newLine) {
  42517. //find char to break on
  42518. while (lineEnd > start) {
  42519. if (isWhitespace(text.charAt(lineEnd)))
  42520. break
  42521. lineEnd--
  42522. }
  42523. if (lineEnd === start) {
  42524. if (nextStart > start + newlineChar.length) nextStart--
  42525. lineEnd = nextStart // If no characters to break, show all.
  42526. } else {
  42527. nextStart = lineEnd
  42528. //eat whitespace at end of line
  42529. while (lineEnd > start) {
  42530. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  42531. break
  42532. lineEnd--
  42533. }
  42534. }
  42535. }
  42536. if (lineEnd >= start) {
  42537. var result = measure(text, start, lineEnd, testWidth)
  42538. lines.push(result)
  42539. }
  42540. start = nextStart
  42541. }
  42542. return lines
  42543. }
  42544. //determines the visible number of glyphs within a given width
  42545. function monospace(text, start, end, width) {
  42546. var glyphs = Math.min(width, end-start)
  42547. return {
  42548. start: start,
  42549. end: start+glyphs
  42550. }
  42551. }
  42552. },{}],73:[function(_dereq_,module,exports){
  42553. "use strict";
  42554. var window = _dereq_("global/window")
  42555. var isFunction = _dereq_("is-function")
  42556. var parseHeaders = _dereq_("parse-headers")
  42557. var xtend = _dereq_("xtend")
  42558. module.exports = createXHR
  42559. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  42560. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  42561. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  42562. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  42563. options = initParams(uri, options, callback)
  42564. options.method = method.toUpperCase()
  42565. return _createXHR(options)
  42566. }
  42567. })
  42568. function forEachArray(array, iterator) {
  42569. for (var i = 0; i < array.length; i++) {
  42570. iterator(array[i])
  42571. }
  42572. }
  42573. function isEmpty(obj){
  42574. for(var i in obj){
  42575. if(obj.hasOwnProperty(i)) return false
  42576. }
  42577. return true
  42578. }
  42579. function initParams(uri, options, callback) {
  42580. var params = uri
  42581. if (isFunction(options)) {
  42582. callback = options
  42583. if (typeof uri === "string") {
  42584. params = {uri:uri}
  42585. }
  42586. } else {
  42587. params = xtend(options, {uri: uri})
  42588. }
  42589. params.callback = callback
  42590. return params
  42591. }
  42592. function createXHR(uri, options, callback) {
  42593. options = initParams(uri, options, callback)
  42594. return _createXHR(options)
  42595. }
  42596. function _createXHR(options) {
  42597. if(typeof options.callback === "undefined"){
  42598. throw new Error("callback argument missing")
  42599. }
  42600. var called = false
  42601. var callback = function cbOnce(err, response, body){
  42602. if(!called){
  42603. called = true
  42604. options.callback(err, response, body)
  42605. }
  42606. }
  42607. function readystatechange() {
  42608. if (xhr.readyState === 4) {
  42609. loadFunc()
  42610. }
  42611. }
  42612. function getBody() {
  42613. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  42614. var body = undefined
  42615. if (xhr.response) {
  42616. body = xhr.response
  42617. } else {
  42618. body = xhr.responseText || getXml(xhr)
  42619. }
  42620. if (isJson) {
  42621. try {
  42622. body = JSON.parse(body)
  42623. } catch (e) {}
  42624. }
  42625. return body
  42626. }
  42627. function errorFunc(evt) {
  42628. clearTimeout(timeoutTimer)
  42629. if(!(evt instanceof Error)){
  42630. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  42631. }
  42632. evt.statusCode = 0
  42633. return callback(evt, failureResponse)
  42634. }
  42635. // will load the data & process the response in a special response object
  42636. function loadFunc() {
  42637. if (aborted) return
  42638. var status
  42639. clearTimeout(timeoutTimer)
  42640. if(options.useXDR && xhr.status===undefined) {
  42641. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  42642. status = 200
  42643. } else {
  42644. status = (xhr.status === 1223 ? 204 : xhr.status)
  42645. }
  42646. var response = failureResponse
  42647. var err = null
  42648. if (status !== 0){
  42649. response = {
  42650. body: getBody(),
  42651. statusCode: status,
  42652. method: method,
  42653. headers: {},
  42654. url: uri,
  42655. rawRequest: xhr
  42656. }
  42657. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  42658. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  42659. }
  42660. } else {
  42661. err = new Error("Internal XMLHttpRequest Error")
  42662. }
  42663. return callback(err, response, response.body)
  42664. }
  42665. var xhr = options.xhr || null
  42666. if (!xhr) {
  42667. if (options.cors || options.useXDR) {
  42668. xhr = new createXHR.XDomainRequest()
  42669. }else{
  42670. xhr = new createXHR.XMLHttpRequest()
  42671. }
  42672. }
  42673. var key
  42674. var aborted
  42675. var uri = xhr.url = options.uri || options.url
  42676. var method = xhr.method = options.method || "GET"
  42677. var body = options.body || options.data
  42678. var headers = xhr.headers = options.headers || {}
  42679. var sync = !!options.sync
  42680. var isJson = false
  42681. var timeoutTimer
  42682. var failureResponse = {
  42683. body: undefined,
  42684. headers: {},
  42685. statusCode: 0,
  42686. method: method,
  42687. url: uri,
  42688. rawRequest: xhr
  42689. }
  42690. if ("json" in options && options.json !== false) {
  42691. isJson = true
  42692. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  42693. if (method !== "GET" && method !== "HEAD") {
  42694. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  42695. body = JSON.stringify(options.json === true ? body : options.json)
  42696. }
  42697. }
  42698. xhr.onreadystatechange = readystatechange
  42699. xhr.onload = loadFunc
  42700. xhr.onerror = errorFunc
  42701. // IE9 must have onprogress be set to a unique function.
  42702. xhr.onprogress = function () {
  42703. // IE must die
  42704. }
  42705. xhr.onabort = function(){
  42706. aborted = true;
  42707. }
  42708. xhr.ontimeout = errorFunc
  42709. xhr.open(method, uri, !sync, options.username, options.password)
  42710. //has to be after open
  42711. if(!sync) {
  42712. xhr.withCredentials = !!options.withCredentials
  42713. }
  42714. // Cannot set timeout with sync request
  42715. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  42716. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  42717. if (!sync && options.timeout > 0 ) {
  42718. timeoutTimer = setTimeout(function(){
  42719. if (aborted) return
  42720. aborted = true//IE9 may still call readystatechange
  42721. xhr.abort("timeout")
  42722. var e = new Error("XMLHttpRequest timeout")
  42723. e.code = "ETIMEDOUT"
  42724. errorFunc(e)
  42725. }, options.timeout )
  42726. }
  42727. if (xhr.setRequestHeader) {
  42728. for(key in headers){
  42729. if(headers.hasOwnProperty(key)){
  42730. xhr.setRequestHeader(key, headers[key])
  42731. }
  42732. }
  42733. } else if (options.headers && !isEmpty(options.headers)) {
  42734. throw new Error("Headers cannot be set on an XDomainRequest object")
  42735. }
  42736. if ("responseType" in options) {
  42737. xhr.responseType = options.responseType
  42738. }
  42739. if ("beforeSend" in options &&
  42740. typeof options.beforeSend === "function"
  42741. ) {
  42742. options.beforeSend(xhr)
  42743. }
  42744. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  42745. // XMLHttpRequest spec says to pass null as body to indicate no body
  42746. // See https://github.com/naugtur/xhr/issues/100.
  42747. xhr.send(body || null)
  42748. return xhr
  42749. }
  42750. function getXml(xhr) {
  42751. if (xhr.responseType === "document") {
  42752. return xhr.responseXML
  42753. }
  42754. var firefoxBugTakenEffect = xhr.status === 204 && xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  42755. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  42756. return xhr.responseXML
  42757. }
  42758. return null
  42759. }
  42760. function noop() {}
  42761. },{"global/window":15,"is-function":20,"parse-headers":31,"xtend":75}],74:[function(_dereq_,module,exports){
  42762. module.exports = (function xmlparser() {
  42763. //common browsers
  42764. if (typeof window.DOMParser !== 'undefined') {
  42765. return function(str) {
  42766. var parser = new window.DOMParser()
  42767. return parser.parseFromString(str, 'application/xml')
  42768. }
  42769. }
  42770. //IE8 fallback
  42771. if (typeof window.ActiveXObject !== 'undefined'
  42772. && new window.ActiveXObject('Microsoft.XMLDOM')) {
  42773. return function(str) {
  42774. var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM")
  42775. xmlDoc.async = "false"
  42776. xmlDoc.loadXML(str)
  42777. return xmlDoc
  42778. }
  42779. }
  42780. //last resort fallback
  42781. return function(str) {
  42782. var div = document.createElement('div')
  42783. div.innerHTML = str
  42784. return div
  42785. }
  42786. })()
  42787. },{}],75:[function(_dereq_,module,exports){
  42788. module.exports = extend
  42789. var hasOwnProperty = Object.prototype.hasOwnProperty;
  42790. function extend() {
  42791. var target = {}
  42792. for (var i = 0; i < arguments.length; i++) {
  42793. var source = arguments[i]
  42794. for (var key in source) {
  42795. if (hasOwnProperty.call(source, key)) {
  42796. target[key] = source[key]
  42797. }
  42798. }
  42799. }
  42800. return target
  42801. }
  42802. },{}],76:[function(_dereq_,module,exports){
  42803. module.exports={
  42804. "name": "aframe",
  42805. "version": "0.7.0",
  42806. "description": "A web framework for building virtual reality experiences.",
  42807. "homepage": "https://aframe.io/",
  42808. "main": "dist/aframe-master.js",
  42809. "scripts": {
  42810. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  42811. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  42812. "codecov": "codecov",
  42813. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  42814. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  42815. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  42816. "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",
  42817. "docs": "markserv --dir docs --port 9001",
  42818. "preghpages": "node ./scripts/preghpages.js",
  42819. "ghpages": "ghpages -p gh-pages/",
  42820. "lint": "semistandard -v | snazzy",
  42821. "lint:fix": "semistandard --fix",
  42822. "precommit": "npm run lint",
  42823. "prepush": "node scripts/testOnlyCheck.js",
  42824. "prerelease": "node scripts/release.js 0.6.1 0.7.0",
  42825. "start": "npm run dev",
  42826. "test": "karma start ./tests/karma.conf.js",
  42827. "test:docs": "node scripts/docsLint.js",
  42828. "test:firefox": "npm test -- --browsers Firefox",
  42829. "test:chrome": "npm test -- --browsers Chrome",
  42830. "test:node": "mocha --ui tdd tests/node"
  42831. },
  42832. "repository": "aframevr/aframe",
  42833. "license": "MIT",
  42834. "dependencies": {
  42835. "@tweenjs/tween.js": "^16.8.0",
  42836. "browserify-css": "^0.8.2",
  42837. "debug": "ngokevin/debug#noTimestamp",
  42838. "deep-assign": "^2.0.0",
  42839. "document-register-element": "dmarcos/document-register-element#8ccc532b7",
  42840. "envify": "^3.4.1",
  42841. "load-bmfont": "^1.2.3",
  42842. "object-assign": "^4.0.1",
  42843. "present": "0.0.6",
  42844. "promise-polyfill": "^3.1.0",
  42845. "style-attr": "^1.0.2",
  42846. "three": "^0.87.0",
  42847. "three-bmfont-text": "^2.1.0",
  42848. "webvr-polyfill": "^0.9.40"
  42849. },
  42850. "devDependencies": {
  42851. "browserify": "^13.1.0",
  42852. "browserify-derequire": "^0.9.4",
  42853. "browserify-istanbul": "^2.0.0",
  42854. "budo": "^9.2.0",
  42855. "chai": "^3.5.0",
  42856. "chai-shallow-deep-equal": "^1.4.0",
  42857. "chalk": "^1.1.3",
  42858. "codecov": "^1.0.1",
  42859. "cross-env": "^5.0.1",
  42860. "exorcist": "^0.4.0",
  42861. "ghpages": "0.0.8",
  42862. "git-rev": "^0.2.1",
  42863. "glob": "^7.1.1",
  42864. "husky": "^0.11.7",
  42865. "istanbul": "^0.4.5",
  42866. "jsdom": "^9.11.0",
  42867. "karma": "1.4.1",
  42868. "karma-browserify": "^5.1.0",
  42869. "karma-chai-shallow-deep-equal": "0.0.4",
  42870. "karma-chrome-launcher": "^2.0.0",
  42871. "karma-coverage": "^1.1.1",
  42872. "karma-env-preprocessor": "^0.1.1",
  42873. "karma-firefox-launcher": "^1.0.0",
  42874. "karma-mocha": "^1.1.1",
  42875. "karma-mocha-reporter": "^2.1.0",
  42876. "karma-sinon-chai": "1.2.4",
  42877. "lolex": "^1.5.1",
  42878. "markserv": "0.0.20",
  42879. "minifyify": "^7.3.3",
  42880. "mocha": "^3.0.2",
  42881. "mozilla-download": "^1.1.1",
  42882. "replace-in-file": "^2.5.3",
  42883. "semistandard": "^9.0.0",
  42884. "shelljs": "^0.7.7",
  42885. "shx": "^0.2.2",
  42886. "sinon": "^1.17.5",
  42887. "sinon-chai": "2.8.0",
  42888. "snazzy": "^5.0.0",
  42889. "too-wordy": "ngokevin/too-wordy",
  42890. "uglifyjs": "^2.4.10",
  42891. "write-good": "^0.9.1"
  42892. },
  42893. "link": true,
  42894. "browserify": {
  42895. "transform": [
  42896. "browserify-css",
  42897. "envify"
  42898. ]
  42899. },
  42900. "semistandard": {
  42901. "ignore": [
  42902. "build/**",
  42903. "dist/**",
  42904. "examples/**/shaders/*.js",
  42905. "**/vendor/**"
  42906. ]
  42907. },
  42908. "keywords": [
  42909. "3d",
  42910. "aframe",
  42911. "cardboard",
  42912. "components",
  42913. "oculus",
  42914. "three",
  42915. "three.js",
  42916. "rift",
  42917. "vive",
  42918. "vr",
  42919. "web-components",
  42920. "webvr"
  42921. ],
  42922. "browserify-css": {
  42923. "minify": true
  42924. },
  42925. "engines": {
  42926. "node": ">= 4.6.0",
  42927. "npm": "^2.15.9"
  42928. }
  42929. }
  42930. },{}],77:[function(_dereq_,module,exports){
  42931. var registerComponent = _dereq_('../core/component').registerComponent;
  42932. var THREE = _dereq_('../lib/three');
  42933. var utils = _dereq_('../utils/');
  42934. var bind = utils.bind;
  42935. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  42936. /**
  42937. * Camera component.
  42938. * Pairs along with camera system to handle tracking the active camera.
  42939. */
  42940. module.exports.Component = registerComponent('camera', {
  42941. schema: {
  42942. active: {default: true},
  42943. far: {default: 10000},
  42944. fov: {default: 80, min: 0},
  42945. near: {default: 0.005, min: 0},
  42946. userHeight: {default: 0, min: 0},
  42947. zoom: {default: 1, min: 0}
  42948. },
  42949. /**
  42950. * Initialize three.js camera and add it to the entity.
  42951. * Add reference from scene to this entity as the camera.
  42952. */
  42953. init: function () {
  42954. var camera;
  42955. var el = this.el;
  42956. var sceneEl = el.sceneEl;
  42957. this.savedPose = null;
  42958. // Create camera.
  42959. camera = this.camera = new THREE.PerspectiveCamera();
  42960. el.setObject3D('camera', camera);
  42961. // Add listeners to save and restore camera pose if headset is present.
  42962. this.onEnterVR = bind(this.onEnterVR, this);
  42963. this.onExitVR = bind(this.onExitVR, this);
  42964. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  42965. sceneEl.addEventListener('exit-vr', this.onExitVR);
  42966. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  42967. if (sceneEl.is('vr-mode')) { this.onEnterVR(); }
  42968. },
  42969. /**
  42970. * Update three.js camera.
  42971. */
  42972. update: function (oldData) {
  42973. var el = this.el;
  42974. var data = this.data;
  42975. var camera = this.camera;
  42976. var system = this.system;
  42977. // Update height offset.
  42978. this.addHeightOffset(oldData.userHeight);
  42979. // Update properties.
  42980. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  42981. camera.far = data.far;
  42982. camera.fov = data.fov;
  42983. camera.near = data.near;
  42984. camera.zoom = data.zoom;
  42985. camera.updateProjectionMatrix();
  42986. // Active property did not change.
  42987. if (oldData && oldData.active === data.active) { return; }
  42988. // If `active` property changes, or first update, handle active camera with system.
  42989. if (data.active && system.activeCameraEl !== el) {
  42990. // Camera enabled. Set camera to this camera.
  42991. system.setActiveCamera(el);
  42992. } else if (!data.active && system.activeCameraEl === el) {
  42993. // Camera disabled. Set camera to another camera.
  42994. system.disableActiveCamera();
  42995. }
  42996. },
  42997. /**
  42998. * Remove camera on remove (callback).
  42999. */
  43000. remove: function () {
  43001. var sceneEl = this.el.sceneEl;
  43002. this.el.removeObject3D('camera');
  43003. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  43004. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  43005. },
  43006. /**
  43007. * Save pose and remove the offset.
  43008. */
  43009. onEnterVR: function () {
  43010. this.saveCameraPose();
  43011. this.removeHeightOffset();
  43012. },
  43013. /**
  43014. * Restore the pose. Do not need to re-add the offset because it was saved on entering VR.
  43015. */
  43016. onExitVR: function () {
  43017. this.restoreCameraPose();
  43018. },
  43019. /**
  43020. * Offsets the position of the camera to set a human scale perspective
  43021. * This offset is not necessary when using a headset because the SDK
  43022. * will return the real user's head height and position.
  43023. */
  43024. addHeightOffset: function (oldOffset) {
  43025. var el = this.el;
  43026. var currentPosition;
  43027. var userHeightOffset = this.data.userHeight;
  43028. oldOffset = oldOffset || 0;
  43029. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  43030. el.setAttribute('position', {
  43031. x: currentPosition.x,
  43032. y: currentPosition.y - oldOffset + userHeightOffset,
  43033. z: currentPosition.z
  43034. });
  43035. },
  43036. /**
  43037. * Remove the height offset (called when entering VR) since WebVR API gives absolute
  43038. * position.
  43039. */
  43040. removeHeightOffset: function () {
  43041. var currentPosition;
  43042. var el = this.el;
  43043. var hasPositionalTracking;
  43044. var userHeightOffset = this.data.userHeight;
  43045. // Remove the offset if there is positional tracking when entering VR.
  43046. // Necessary for fullscreen mode with no headset.
  43047. // Checking this.hasPositionalTracking to make the value injectable for unit tests.
  43048. hasPositionalTracking = this.hasPositionalTracking !== undefined
  43049. ? this.hasPositionalTracking
  43050. : checkHasPositionalTracking();
  43051. if (!userHeightOffset || !hasPositionalTracking) { return; }
  43052. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  43053. el.setAttribute('position', {
  43054. x: currentPosition.x,
  43055. y: currentPosition.y - userHeightOffset,
  43056. z: currentPosition.z
  43057. });
  43058. },
  43059. /**
  43060. * Save camera pose before entering VR to restore later if exiting.
  43061. */
  43062. saveCameraPose: function () {
  43063. var el = this.el;
  43064. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  43065. if (this.savedPose || !hasPositionalTracking) { return; }
  43066. this.savedPose = {
  43067. position: el.getAttribute('position'),
  43068. rotation: el.getAttribute('rotation')
  43069. };
  43070. },
  43071. /**
  43072. * Reset camera pose to before entering VR.
  43073. */
  43074. restoreCameraPose: function () {
  43075. var el = this.el;
  43076. var savedPose = this.savedPose;
  43077. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  43078. if (!savedPose || !hasPositionalTracking) { return; }
  43079. // Reset camera orientation.
  43080. el.setAttribute('position', savedPose.position);
  43081. el.setAttribute('rotation', savedPose.rotation);
  43082. this.savedPose = null;
  43083. }
  43084. });
  43085. },{"../core/component":125,"../lib/three":173,"../utils/":195}],78:[function(_dereq_,module,exports){
  43086. var registerComponent = _dereq_('../core/component').registerComponent;
  43087. var THREE = _dereq_('../lib/three');
  43088. module.exports.Component = registerComponent('collada-model', {
  43089. schema: {type: 'asset'},
  43090. init: function () {
  43091. this.model = null;
  43092. this.loader = new THREE.ColladaLoader();
  43093. this.loader.options.convertUpAxis = true;
  43094. },
  43095. update: function () {
  43096. var self = this;
  43097. var el = this.el;
  43098. var src = this.data;
  43099. if (!src) { return; }
  43100. this.remove();
  43101. this.loader.load(src, function (colladaModel) {
  43102. self.model = colladaModel.scene;
  43103. el.setObject3D('mesh', self.model);
  43104. el.emit('model-loaded', {format: 'collada', model: self.model});
  43105. });
  43106. },
  43107. remove: function () {
  43108. if (!this.model) { return; }
  43109. this.el.removeObject3D('mesh');
  43110. }
  43111. });
  43112. },{"../core/component":125,"../lib/three":173}],79:[function(_dereq_,module,exports){
  43113. /* global THREE */
  43114. var registerComponent = _dereq_('../core/component').registerComponent;
  43115. var utils = _dereq_('../utils/');
  43116. var bind = utils.bind;
  43117. var EVENTS = {
  43118. CLICK: 'click',
  43119. FUSING: 'fusing',
  43120. MOUSEENTER: 'mouseenter',
  43121. MOUSEDOWN: 'mousedown',
  43122. MOUSELEAVE: 'mouseleave',
  43123. MOUSEUP: 'mouseup'
  43124. };
  43125. var STATES = {
  43126. FUSING: 'cursor-fusing',
  43127. HOVERING: 'cursor-hovering',
  43128. HOVERED: 'cursor-hovered'
  43129. };
  43130. var CANVAS_EVENTS = {
  43131. DOWN: ['mousedown', 'touchstart'],
  43132. UP: ['mouseup', 'touchend']
  43133. };
  43134. /**
  43135. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  43136. * from the camera and pointing from camera's facing direction, and then only returning the
  43137. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  43138. *
  43139. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  43140. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  43141. * @member {object} intersection - Attributes of the current intersection event, including
  43142. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  43143. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  43144. * emit events when unintersecting.
  43145. */
  43146. module.exports.Component = registerComponent('cursor', {
  43147. dependencies: ['raycaster'],
  43148. schema: {
  43149. downEvents: {default: []},
  43150. fuse: {default: utils.device.isMobile()},
  43151. fuseTimeout: {default: 1500, min: 0},
  43152. upEvents: {default: []},
  43153. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  43154. },
  43155. init: function () {
  43156. var self = this;
  43157. this.fuseTimeout = undefined;
  43158. this.cursorDownEl = null;
  43159. this.intersection = null;
  43160. this.intersectedEl = null;
  43161. this.canvasBounds = document.body.getBoundingClientRect();
  43162. // Debounce.
  43163. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  43164. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  43165. }, 200);
  43166. // Bind methods.
  43167. this.onCursorDown = bind(this.onCursorDown, this);
  43168. this.onCursorUp = bind(this.onCursorUp, this);
  43169. this.onIntersection = bind(this.onIntersection, this);
  43170. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  43171. this.onMouseMove = bind(this.onMouseMove, this);
  43172. },
  43173. update: function (oldData) {
  43174. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  43175. this.updateMouseEventListeners();
  43176. },
  43177. play: function () {
  43178. this.addEventListeners();
  43179. },
  43180. pause: function () {
  43181. this.removeEventListeners();
  43182. },
  43183. remove: function () {
  43184. var el = this.el;
  43185. el.removeState(STATES.HOVERING);
  43186. el.removeState(STATES.FUSING);
  43187. clearTimeout(this.fuseTimeout);
  43188. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  43189. this.removeEventListeners();
  43190. },
  43191. addEventListeners: function () {
  43192. var canvas;
  43193. var data = this.data;
  43194. var el = this.el;
  43195. var self = this;
  43196. function addCanvasListeners () {
  43197. canvas = el.sceneEl.canvas;
  43198. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43199. canvas.addEventListener(downEvent, self.onCursorDown);
  43200. });
  43201. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43202. canvas.addEventListener(upEvent, self.onCursorUp);
  43203. });
  43204. }
  43205. canvas = el.sceneEl.canvas;
  43206. if (canvas) {
  43207. addCanvasListeners();
  43208. } else {
  43209. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  43210. }
  43211. data.downEvents.forEach(function (downEvent) {
  43212. el.addEventListener(downEvent, self.onCursorDown);
  43213. });
  43214. data.upEvents.forEach(function (upEvent) {
  43215. el.addEventListener(upEvent, self.onCursorUp);
  43216. });
  43217. el.addEventListener('raycaster-intersection', this.onIntersection);
  43218. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43219. window.addEventListener('resize', this.updateCanvasBounds);
  43220. },
  43221. removeEventListeners: function () {
  43222. var canvas;
  43223. var data = this.data;
  43224. var el = this.el;
  43225. var self = this;
  43226. canvas = el.sceneEl.canvas;
  43227. if (canvas) {
  43228. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43229. canvas.removeEventListener(downEvent, self.onCursorDown);
  43230. });
  43231. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43232. canvas.removeEventListener(upEvent, self.onCursorUp);
  43233. });
  43234. }
  43235. data.downEvents.forEach(function (downEvent) {
  43236. el.removeEventListener(downEvent, self.onCursorDown);
  43237. });
  43238. data.upEvents.forEach(function (upEvent) {
  43239. el.removeEventListener(upEvent, self.onCursorUp);
  43240. });
  43241. el.removeEventListener('raycaster-intersection', this.onIntersection);
  43242. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43243. window.removeEventListener('mousemove', this.onMouseMove);
  43244. window.removeEventListener('touchstart', this.onMouseMove);
  43245. window.removeEventListener('touchmove', this.onMouseMove);
  43246. window.removeEventListener('resize', this.updateCanvasBounds);
  43247. },
  43248. updateMouseEventListeners: function () {
  43249. var el = this.el;
  43250. window.removeEventListener('mousemove', this.onMouseMove);
  43251. window.removeEventListener('touchstart', this.onMouseMove);
  43252. window.removeEventListener('touchmove', this.onMouseMove);
  43253. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  43254. if (this.data.rayOrigin !== 'mouse') { return; }
  43255. window.addEventListener('mousemove', this.onMouseMove, false);
  43256. window.addEventListener('touchstart', this.onMouseMove, false);
  43257. window.addEventListener('touchmove', this.onMouseMove, false);
  43258. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  43259. this.updateCanvasBounds();
  43260. },
  43261. onMouseMove: (function () {
  43262. var direction = new THREE.Vector3();
  43263. var mouse = new THREE.Vector2();
  43264. var origin = new THREE.Vector3();
  43265. var rayCasterConfig = {origin: origin, direction: direction};
  43266. return function (evt) {
  43267. var bounds = this.canvasBounds;
  43268. var camera = this.el.sceneEl.camera;
  43269. var left;
  43270. var point;
  43271. var top;
  43272. camera.parent.updateMatrixWorld();
  43273. camera.updateMatrixWorld();
  43274. // Calculate mouse position based on the canvas element
  43275. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  43276. // Track the first touch for simplicity.
  43277. point = evt.touches.item(0);
  43278. } else {
  43279. point = evt;
  43280. }
  43281. left = point.clientX - bounds.left;
  43282. top = point.clientY - bounds.top;
  43283. mouse.x = (left / bounds.width) * 2 - 1;
  43284. mouse.y = -(top / bounds.height) * 2 + 1;
  43285. origin.setFromMatrixPosition(camera.matrixWorld);
  43286. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  43287. this.el.setAttribute('raycaster', rayCasterConfig);
  43288. if (evt.type === 'touchstart' || evt.type === 'touchmove') { evt.preventDefault(); }
  43289. };
  43290. })(),
  43291. /**
  43292. * Trigger mousedown and keep track of the mousedowned entity.
  43293. */
  43294. onCursorDown: function (evt) {
  43295. this.twoWayEmit(EVENTS.MOUSEDOWN);
  43296. this.cursorDownEl = this.intersectedEl;
  43297. if (evt.type === 'touchstart') { evt.preventDefault(); }
  43298. },
  43299. /**
  43300. * Trigger mouseup if:
  43301. * - Not fusing (mobile has no mouse).
  43302. * - Currently intersecting an entity.
  43303. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  43304. * in case user mousedowned one entity, dragged to another, and mouseupped.
  43305. */
  43306. onCursorUp: function (evt) {
  43307. this.twoWayEmit(EVENTS.MOUSEUP);
  43308. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  43309. // previously cursorUp entity.
  43310. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  43311. this.cursorDownEl.emit(EVENTS.MOUSEUP, {cursorEl: this.el, intersection: null});
  43312. }
  43313. if (!this.data.fuse && this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  43314. this.twoWayEmit(EVENTS.CLICK);
  43315. }
  43316. this.cursorDownEl = null;
  43317. if (evt.type === 'touchend') { evt.preventDefault(); }
  43318. },
  43319. /**
  43320. * Handle intersection.
  43321. */
  43322. onIntersection: function (evt) {
  43323. var self = this;
  43324. var cursorEl = this.el;
  43325. var data = this.data;
  43326. var index;
  43327. var intersectedEl;
  43328. var intersection;
  43329. // Select closest object, excluding the cursor.
  43330. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  43331. intersection = evt.detail.intersections[index];
  43332. intersectedEl = evt.detail.els[index];
  43333. // If cursor is the only intersected object, ignore the event.
  43334. if (!intersectedEl) { return; }
  43335. // Already intersecting this entity.
  43336. if (this.intersectedEl === intersectedEl) {
  43337. this.intersection = intersection;
  43338. return;
  43339. }
  43340. // Unset current intersection.
  43341. if (this.intersectedEl) { this.clearCurrentIntersection(); }
  43342. // Set new intersection.
  43343. this.intersection = intersection;
  43344. this.intersectedEl = intersectedEl;
  43345. // Hovering.
  43346. cursorEl.addState(STATES.HOVERING);
  43347. intersectedEl.addState(STATES.HOVERED);
  43348. self.twoWayEmit(EVENTS.MOUSEENTER);
  43349. // Begin fuse if necessary.
  43350. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  43351. cursorEl.addState(STATES.FUSING);
  43352. this.twoWayEmit(EVENTS.FUSING);
  43353. this.fuseTimeout = setTimeout(function fuse () {
  43354. cursorEl.removeState(STATES.FUSING);
  43355. self.twoWayEmit(EVENTS.CLICK);
  43356. }, data.fuseTimeout);
  43357. },
  43358. /**
  43359. * Handle intersection cleared.
  43360. */
  43361. onIntersectionCleared: function (evt) {
  43362. var clearedEls = evt.detail.clearedEls;
  43363. // Check if the current intersection has ended
  43364. if (clearedEls.indexOf(this.intersectedEl) !== -1) {
  43365. this.clearCurrentIntersection();
  43366. }
  43367. },
  43368. clearCurrentIntersection: function () {
  43369. var cursorEl = this.el;
  43370. // No longer hovering (or fusing).
  43371. this.intersectedEl.removeState(STATES.HOVERED);
  43372. cursorEl.removeState(STATES.HOVERING);
  43373. cursorEl.removeState(STATES.FUSING);
  43374. this.twoWayEmit(EVENTS.MOUSELEAVE);
  43375. // Unset intersected entity (after emitting the event).
  43376. this.intersection = null;
  43377. this.intersectedEl = null;
  43378. // Clear fuseTimeout.
  43379. clearTimeout(this.fuseTimeout);
  43380. },
  43381. /**
  43382. * Helper to emit on both the cursor and the intersected entity (if exists).
  43383. */
  43384. twoWayEmit: function (evtName) {
  43385. var el = this.el;
  43386. var intersectedEl = this.intersectedEl;
  43387. var intersection = this.intersection;
  43388. el.emit(evtName, {intersectedEl: intersectedEl, intersection: intersection});
  43389. if (!intersectedEl) { return; }
  43390. intersectedEl.emit(evtName, {cursorEl: el, intersection: intersection});
  43391. }
  43392. });
  43393. },{"../core/component":125,"../utils/":195}],80:[function(_dereq_,module,exports){
  43394. var registerComponent = _dereq_('../core/component').registerComponent;
  43395. var bind = _dereq_('../utils/bind');
  43396. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  43397. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  43398. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  43399. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  43400. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  43401. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  43402. /**
  43403. * Daydream controls.
  43404. * Interface with Daydream controller and map Gamepad events to
  43405. * controller buttons: trackpad, menu, system
  43406. * Load a controller model and highlight the pressed buttons.
  43407. */
  43408. module.exports.Component = registerComponent('daydream-controls', {
  43409. schema: {
  43410. hand: {default: ''}, // This informs the degenerate arm model.
  43411. buttonColor: {type: 'color', default: '#000000'},
  43412. buttonTouchedColor: {type: 'color', default: '#777777'},
  43413. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43414. model: {default: true},
  43415. rotationOffset: {default: 0},
  43416. armModel: {default: true}
  43417. },
  43418. /**
  43419. * Button IDs:
  43420. * 0 - trackpad
  43421. * 1 - menu (never dispatched on this layer)
  43422. * 2 - system (never dispatched on this layer)
  43423. */
  43424. mapping: {
  43425. axes: {trackpad: [0, 1]},
  43426. buttons: ['trackpad', 'menu', 'system']
  43427. },
  43428. bindMethods: function () {
  43429. this.onModelLoaded = bind(this.onModelLoaded, this);
  43430. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43431. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43432. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43433. this.onAxisMoved = bind(this.onAxisMoved, this);
  43434. this.onGamepadConnectionEvent = bind(this.onGamepadConnectionEvent, this);
  43435. },
  43436. init: function () {
  43437. var self = this;
  43438. this.animationActive = 'pointing';
  43439. this.onButtonChanged = bind(this.onButtonChanged, this);
  43440. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  43441. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  43442. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  43443. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  43444. this.onAxisMoved = bind(this.onAxisMoved, this);
  43445. this.controllerPresent = false;
  43446. this.everGotGamepadEvent = false;
  43447. this.lastControllerCheck = 0;
  43448. this.bindMethods();
  43449. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43450. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43451. },
  43452. addEventListeners: function () {
  43453. var el = this.el;
  43454. el.addEventListener('buttonchanged', this.onButtonChanged);
  43455. el.addEventListener('buttondown', this.onButtonDown);
  43456. el.addEventListener('buttonup', this.onButtonUp);
  43457. el.addEventListener('touchstart', this.onButtonTouchStart);
  43458. el.addEventListener('touchend', this.onButtonTouchEnd);
  43459. el.addEventListener('model-loaded', this.onModelLoaded);
  43460. el.addEventListener('axismove', this.onAxisMoved);
  43461. this.controllerEventsActive = true;
  43462. },
  43463. removeEventListeners: function () {
  43464. var el = this.el;
  43465. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43466. el.removeEventListener('buttondown', this.onButtonDown);
  43467. el.removeEventListener('buttonup', this.onButtonUp);
  43468. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43469. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43470. el.removeEventListener('model-loaded', this.onModelLoaded);
  43471. el.removeEventListener('axismove', this.onAxisMoved);
  43472. this.controllerEventsActive = false;
  43473. },
  43474. checkIfControllerPresent: function () {
  43475. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  43476. },
  43477. onGamepadConnectionEvent: function (evt) {
  43478. this.everGotGamepadEvent = true;
  43479. // Due to an apparent bug in FF Nightly
  43480. // where only one gamepadconnected / disconnected event is fired,
  43481. // which makes it difficult to handle in individual controller entities,
  43482. // we no longer remove the controllersupdate listener as a result.
  43483. this.checkIfControllerPresent();
  43484. },
  43485. play: function () {
  43486. this.checkIfControllerPresent();
  43487. this.addControllersUpdateListener();
  43488. window.addEventListener('gamepadconnected', this.onGamepadConnectionEvent, false);
  43489. window.addEventListener('gamepaddisconnected', this.onGamepadConnectionEvent, false);
  43490. },
  43491. pause: function () {
  43492. this.removeEventListeners();
  43493. this.removeControllersUpdateListener();
  43494. window.removeEventListener('gamepadconnected', this.onGamepadConnectionEvent, false);
  43495. window.removeEventListener('gamepaddisconnected', this.onGamepadConnectionEvent, false);
  43496. },
  43497. injectTrackedControls: function () {
  43498. var el = this.el;
  43499. var data = this.data;
  43500. el.setAttribute('tracked-controls', {
  43501. armModel: data.armModel,
  43502. hand: data.hand,
  43503. idPrefix: GAMEPAD_ID_PREFIX,
  43504. rotationOffset: data.rotationOffset
  43505. });
  43506. if (!this.data.model) { return; }
  43507. this.el.setAttribute('obj-model', {
  43508. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  43509. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  43510. });
  43511. },
  43512. addControllersUpdateListener: function () {
  43513. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43514. },
  43515. removeControllersUpdateListener: function () {
  43516. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43517. },
  43518. onControllersUpdate: function () {
  43519. if (!this.everGotGamepadEvent) { this.checkIfControllerPresent(); }
  43520. },
  43521. onModelLoaded: function (evt) {
  43522. var controllerObject3D = evt.detail.model;
  43523. var buttonMeshes;
  43524. if (!this.data.model) { return; }
  43525. buttonMeshes = this.buttonMeshes = {};
  43526. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  43527. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  43528. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  43529. // Offset pivot point.
  43530. controllerObject3D.position.set(0, 0, -0.04);
  43531. },
  43532. onAxisMoved: function (evt) {
  43533. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43534. },
  43535. onButtonChanged: function (evt) {
  43536. var button = this.mapping.buttons[evt.detail.id];
  43537. if (!button) return;
  43538. // Pass along changed event with button state, using button mapping for convenience.
  43539. this.el.emit(button + 'changed', evt.detail.state);
  43540. },
  43541. onButtonEvent: function (id, evtName) {
  43542. var buttonName = this.mapping.buttons[id];
  43543. var i;
  43544. if (Array.isArray(buttonName)) {
  43545. for (i = 0; i < buttonName.length; i++) {
  43546. this.el.emit(buttonName[i] + evtName);
  43547. }
  43548. } else {
  43549. this.el.emit(buttonName + evtName);
  43550. }
  43551. this.updateModel(buttonName, evtName);
  43552. },
  43553. updateModel: function (buttonName, evtName) {
  43554. var i;
  43555. if (!this.data.model) { return; }
  43556. if (Array.isArray(buttonName)) {
  43557. for (i = 0; i < buttonName.length; i++) {
  43558. this.updateButtonModel(buttonName[i], evtName);
  43559. }
  43560. } else {
  43561. this.updateButtonModel(buttonName, evtName);
  43562. }
  43563. },
  43564. updateButtonModel: function (buttonName, state) {
  43565. var buttonMeshes = this.buttonMeshes;
  43566. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43567. var color;
  43568. switch (state) {
  43569. case 'down':
  43570. color = this.data.buttonHighlightColor;
  43571. break;
  43572. case 'touchstart':
  43573. color = this.data.buttonTouchedColor;
  43574. break;
  43575. default:
  43576. color = this.data.buttonColor;
  43577. }
  43578. buttonMeshes[buttonName].material.color.set(color);
  43579. }
  43580. });
  43581. },{"../core/component":125,"../utils/bind":189,"../utils/tracked-controls":200}],81:[function(_dereq_,module,exports){
  43582. var registerComponent = _dereq_('../core/component').registerComponent;
  43583. var bind = _dereq_('../utils/bind');
  43584. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  43585. var emitIfAxesChanged = _dereq_('../utils/tracked-controls').emitIfAxesChanged;
  43586. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  43587. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  43588. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  43589. var GAMEPAD_ID_PREFIX = 'Gear VR';
  43590. /**
  43591. * Gear VR controls.
  43592. * Interface with Gear VR controller and map Gamepad events to
  43593. * controller buttons: trackpad, trigger
  43594. * Load a controller model and highlight the pressed buttons.
  43595. */
  43596. module.exports.Component = registerComponent('gearvr-controls', {
  43597. schema: {
  43598. hand: {default: ''}, // This informs the degenerate arm model.
  43599. buttonColor: {type: 'color', default: '#000000'},
  43600. buttonTouchedColor: {type: 'color', default: '#777777'},
  43601. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43602. model: {default: true},
  43603. rotationOffset: {default: 0},
  43604. armModel: {default: true}
  43605. },
  43606. /**
  43607. * Button IDs:
  43608. * 0 - trackpad
  43609. * 1 - trigger
  43610. */
  43611. mapping: {
  43612. axes: {trackpad: [0, 1]},
  43613. buttons: ['trackpad', 'trigger']
  43614. },
  43615. bindMethods: function () {
  43616. this.onModelLoaded = bind(this.onModelLoaded, this);
  43617. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43618. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43619. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43620. this.onAxisMoved = bind(this.onAxisMoved, this);
  43621. },
  43622. init: function () {
  43623. var self = this;
  43624. this.animationActive = 'pointing';
  43625. this.onButtonChanged = bind(this.onButtonChanged, this);
  43626. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  43627. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  43628. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  43629. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  43630. this.onAxisMoved = bind(this.onAxisMoved, this);
  43631. this.controllerPresent = false;
  43632. this.everGotGamepadEvent = false;
  43633. this.lastControllerCheck = 0;
  43634. this.bindMethods();
  43635. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43636. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43637. },
  43638. addEventListeners: function () {
  43639. var el = this.el;
  43640. el.addEventListener('buttonchanged', this.onButtonChanged);
  43641. el.addEventListener('buttondown', this.onButtonDown);
  43642. el.addEventListener('buttonup', this.onButtonUp);
  43643. el.addEventListener('touchstart', this.onButtonTouchStart);
  43644. el.addEventListener('touchend', this.onButtonTouchEnd);
  43645. el.addEventListener('model-loaded', this.onModelLoaded);
  43646. el.addEventListener('axismove', this.onAxisMoved);
  43647. this.controllerEventsActive = true;
  43648. this.addControllersUpdateListener();
  43649. },
  43650. removeEventListeners: function () {
  43651. var el = this.el;
  43652. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43653. el.removeEventListener('buttondown', this.onButtonDown);
  43654. el.removeEventListener('buttonup', this.onButtonUp);
  43655. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43656. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43657. el.removeEventListener('model-loaded', this.onModelLoaded);
  43658. el.removeEventListener('axismove', this.onAxisMoved);
  43659. this.controllerEventsActive = false;
  43660. this.removeControllersUpdateListener();
  43661. },
  43662. checkIfControllerPresent: function () {
  43663. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  43664. this.data.hand ? {hand: this.data.hand} : {});
  43665. },
  43666. play: function () {
  43667. this.checkIfControllerPresent();
  43668. this.addControllersUpdateListener();
  43669. },
  43670. pause: function () {
  43671. this.removeEventListeners();
  43672. this.removeControllersUpdateListener();
  43673. },
  43674. injectTrackedControls: function () {
  43675. var el = this.el;
  43676. var data = this.data;
  43677. el.setAttribute('tracked-controls', {
  43678. armModel: data.armModel,
  43679. idPrefix: GAMEPAD_ID_PREFIX,
  43680. rotationOffset: data.rotationOffset
  43681. });
  43682. if (!this.data.model) { return; }
  43683. this.el.setAttribute('obj-model', {
  43684. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  43685. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  43686. });
  43687. },
  43688. addControllersUpdateListener: function () {
  43689. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43690. },
  43691. removeControllersUpdateListener: function () {
  43692. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43693. },
  43694. onControllersUpdate: function () {
  43695. this.checkIfControllerPresent();
  43696. },
  43697. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  43698. onModelLoaded: function (evt) {
  43699. var controllerObject3D = evt.detail.model;
  43700. var buttonMeshes;
  43701. if (!this.data.model) { return; }
  43702. buttonMeshes = this.buttonMeshes = {};
  43703. buttonMeshes.trigger = controllerObject3D.children[2];
  43704. buttonMeshes.trackpad = controllerObject3D.children[1];
  43705. },
  43706. onButtonChanged: function (evt) {
  43707. var button = this.mapping.buttons[evt.detail.id];
  43708. if (!button) return;
  43709. // Pass along changed event with button state, using button mapping for convenience.
  43710. this.el.emit(button + 'changed', evt.detail.state);
  43711. },
  43712. onButtonEvent: function (id, evtName) {
  43713. var buttonName = this.mapping.buttons[id];
  43714. var i;
  43715. if (Array.isArray(buttonName)) {
  43716. for (i = 0; i < buttonName.length; i++) {
  43717. this.el.emit(buttonName[i] + evtName);
  43718. }
  43719. } else {
  43720. this.el.emit(buttonName + evtName);
  43721. }
  43722. this.updateModel(buttonName, evtName);
  43723. },
  43724. onAxisMoved: function (evt) {
  43725. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43726. },
  43727. updateModel: function (buttonName, evtName) {
  43728. var i;
  43729. if (!this.data.model) { return; }
  43730. if (Array.isArray(buttonName)) {
  43731. for (i = 0; i < buttonName.length; i++) {
  43732. this.updateButtonModel(buttonName[i], evtName);
  43733. }
  43734. } else {
  43735. this.updateButtonModel(buttonName, evtName);
  43736. }
  43737. },
  43738. updateButtonModel: function (buttonName, state) {
  43739. var buttonMeshes = this.buttonMeshes;
  43740. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43741. var color;
  43742. switch (state) {
  43743. case 'down':
  43744. color = this.data.buttonHighlightColor;
  43745. break;
  43746. case 'touchstart':
  43747. color = this.data.buttonTouchedColor;
  43748. break;
  43749. default:
  43750. color = this.data.buttonColor;
  43751. }
  43752. buttonMeshes[buttonName].material.color.set(color);
  43753. }
  43754. });
  43755. },{"../core/component":125,"../utils/bind":189,"../utils/tracked-controls":200}],82:[function(_dereq_,module,exports){
  43756. var debug = _dereq_('../utils/debug');
  43757. var geometries = _dereq_('../core/geometry').geometries;
  43758. var geometryNames = _dereq_('../core/geometry').geometryNames;
  43759. var registerComponent = _dereq_('../core/component').registerComponent;
  43760. var THREE = _dereq_('../lib/three');
  43761. var dummyGeometry = new THREE.Geometry();
  43762. var warn = debug('components:geometry:warn');
  43763. /**
  43764. * Geometry component. Combined with material component to make a mesh in 3D object.
  43765. * Extended with registered geometries.
  43766. */
  43767. module.exports.Component = registerComponent('geometry', {
  43768. schema: {
  43769. buffer: {default: true},
  43770. mergeTo: {type: 'selector'},
  43771. primitive: {default: 'box', oneOf: geometryNames},
  43772. skipCache: {default: false}
  43773. },
  43774. init: function () {
  43775. this.geometry = null;
  43776. },
  43777. /**
  43778. * Talk to geometry system to get or create geometry.
  43779. */
  43780. update: function (previousData) {
  43781. var data = this.data;
  43782. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  43783. var system = this.system;
  43784. // Dispose old geometry if we created one.
  43785. if (this.geometry) {
  43786. system.unuseGeometry(previousData);
  43787. this.geometry = null;
  43788. }
  43789. // Create new geometry.
  43790. this.geometry = mesh.geometry = system.getOrCreateGeometry(data);
  43791. if (data.mergeTo) {
  43792. this.mergeTo(data.mergeTo);
  43793. }
  43794. },
  43795. /**
  43796. * Merge geometry to another entity's geometry.
  43797. * Remove the entity from the scene. Not a reversible operation.
  43798. *
  43799. * @param {Element} toEl - Entity where the geometry will be merged to.
  43800. */
  43801. mergeTo: function (toEl) {
  43802. var el = this.el;
  43803. var mesh = el.getObject3D('mesh');
  43804. var toMesh;
  43805. if (!toEl || !toEl.isEntity) {
  43806. warn('There is not a valid entity to merge the geometry to');
  43807. return;
  43808. }
  43809. if (toEl === el) {
  43810. warn('Source and target geometries cannot be the same for merge');
  43811. return;
  43812. }
  43813. // Create mesh if entity does not have one.
  43814. toMesh = toEl.getObject3D('mesh');
  43815. if (!toMesh) {
  43816. toMesh = toEl.getOrCreateObject3D('mesh', THREE.Mesh);
  43817. toEl.setAttribute('material', el.getAttribute('material'));
  43818. return;
  43819. }
  43820. if (toMesh.geometry instanceof THREE.Geometry === false ||
  43821. mesh.geometry instanceof THREE.Geometry === false) {
  43822. warn('Geometry merge is only available for `THREE.Geometry` types. ' +
  43823. 'Check that both of the merging geometry and the target geometry have `buffer` ' +
  43824. 'set to false');
  43825. return;
  43826. }
  43827. if (this.data.skipCache === false) {
  43828. warn('Cached geometries are not allowed to merge. Set `skipCache` to true');
  43829. return;
  43830. }
  43831. mesh.parent.updateMatrixWorld();
  43832. toMesh.geometry.merge(mesh.geometry, mesh.matrixWorld);
  43833. el.emit('geometry-merged', {mergeTarget: toEl});
  43834. el.parentNode.removeChild(el);
  43835. },
  43836. /**
  43837. * Tell geometry system that entity is no longer using the geometry.
  43838. * Unset the geometry on the mesh
  43839. */
  43840. remove: function () {
  43841. this.system.unuseGeometry(this.data);
  43842. this.el.getObject3D('mesh').geometry = dummyGeometry;
  43843. this.geometry = null;
  43844. },
  43845. /**
  43846. * Update geometry component schema based on geometry type.
  43847. *
  43848. * @param {object} data - New data passed by Component.
  43849. */
  43850. updateSchema: function (data) {
  43851. var newGeometryType = data.primitive;
  43852. var currentGeometryType = this.data && this.data.primitive;
  43853. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  43854. // Geometry has no schema.
  43855. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  43856. // Nothing has changed.
  43857. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  43858. this.extendSchema(schema);
  43859. }
  43860. });
  43861. },{"../core/component":125,"../core/geometry":126,"../lib/three":173,"../utils/debug":191}],83:[function(_dereq_,module,exports){
  43862. var registerComponent = _dereq_('../core/component').registerComponent;
  43863. var THREE = _dereq_('../lib/three');
  43864. var utils = _dereq_('../utils/');
  43865. var warn = utils.debug('components:gltf-model:warn');
  43866. /**
  43867. * glTF model loader.
  43868. */
  43869. module.exports.Component = registerComponent('gltf-model', {
  43870. schema: {type: 'model'},
  43871. init: function () {
  43872. this.model = null;
  43873. this.loader = new THREE.GLTFLoader();
  43874. },
  43875. update: function () {
  43876. var self = this;
  43877. var el = this.el;
  43878. var src = this.data;
  43879. if (!src) { return; }
  43880. this.remove();
  43881. this.loader.load(src, function gltfLoaded (gltfModel) {
  43882. self.model = gltfModel.scene || gltfModel.scenes[0];
  43883. self.model.animations = gltfModel.animations;
  43884. el.setObject3D('mesh', self.model);
  43885. el.emit('model-loaded', {format: 'gltf', model: self.model});
  43886. }, undefined /* onProgress */, function gltfFailed (error) {
  43887. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  43888. warn(message);
  43889. el.emit('model-error', {format: 'gltf', src: src});
  43890. });
  43891. },
  43892. remove: function () {
  43893. if (!this.model) { return; }
  43894. this.el.removeObject3D('mesh');
  43895. }
  43896. });
  43897. },{"../core/component":125,"../lib/three":173,"../utils/":195}],84:[function(_dereq_,module,exports){
  43898. /* global THREE */
  43899. var registerComponent = _dereq_('../core/component').registerComponent;
  43900. // Found at https://github.com/aframevr/assets.
  43901. var MODEL_URLS = {
  43902. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  43903. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  43904. };
  43905. // Poses.
  43906. var ANIMATIONS = {
  43907. open: 'Open',
  43908. // point: grip active, trackpad surface active, trigger inactive.
  43909. point: 'Point',
  43910. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  43911. pointThumb: 'Point + Thumb',
  43912. // fist: grip active, trigger active, trackpad surface active.
  43913. fist: 'Fist',
  43914. // hold: trigger active, grip inactive.
  43915. hold: 'Hold',
  43916. // thumbUp: grip active, trigger active, trackpad surface inactive.
  43917. thumbUp: 'Thumb Up'
  43918. };
  43919. // Map animation to public events for the API.
  43920. var EVENTS = {};
  43921. EVENTS[ANIMATIONS.fist] = 'grip';
  43922. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  43923. EVENTS[ANIMATIONS.point] = 'pointing';
  43924. EVENTS[ANIMATIONS.thumb] = 'thumb';
  43925. /**
  43926. * Hand controls component that abstracts 6DoF controls:
  43927. * oculus-touch-controls, vive-controls, windows-motion-controls.
  43928. *
  43929. * Originally meant to be a sample implementation of applications-specific controls that
  43930. * abstracts multiple types of controllers.
  43931. *
  43932. * Auto-detect appropriate controller.
  43933. * Handle common events coming from the detected vendor-specific controls.
  43934. * Translate button events to semantic hand-related event names:
  43935. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  43936. * Load hand model with gestures that are applied based on the button pressed.
  43937. *
  43938. * @property {string} Hand mapping (`left`, `right`).
  43939. */
  43940. module.exports.Component = registerComponent('hand-controls', {
  43941. schema: {default: 'left'},
  43942. init: function () {
  43943. var self = this;
  43944. var el = this.el;
  43945. // Current pose.
  43946. this.gesture = ANIMATIONS.open;
  43947. // Active buttons populated by events provided by the attached controls.
  43948. this.pressedButtons = {};
  43949. this.touchedButtons = {};
  43950. this.loader = new THREE.ObjectLoader();
  43951. this.loader.setCrossOrigin('anonymous');
  43952. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  43953. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  43954. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  43955. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  43956. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  43957. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  43958. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  43959. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  43960. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  43961. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  43962. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  43963. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  43964. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  43965. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  43966. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  43967. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  43968. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  43969. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  43970. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  43971. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  43972. this.onControllerConnected = function () { self.setModelVisibility(true); };
  43973. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  43974. el.addEventListener('controllerconnected', this.onControllerConnected);
  43975. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  43976. },
  43977. play: function () {
  43978. this.addEventListeners();
  43979. },
  43980. pause: function () {
  43981. this.removeEventListeners();
  43982. },
  43983. tick: function (time, delta) {
  43984. var mesh = this.el.getObject3D('mesh');
  43985. if (!mesh || !mesh.mixer) { return; }
  43986. mesh.mixer.update(delta / 1000);
  43987. },
  43988. addEventListeners: function () {
  43989. var el = this.el;
  43990. el.addEventListener('gripdown', this.onGripDown);
  43991. el.addEventListener('gripup', this.onGripUp);
  43992. el.addEventListener('trackpaddown', this.onTrackpadDown);
  43993. el.addEventListener('trackpadup', this.onTrackpadUp);
  43994. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  43995. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  43996. el.addEventListener('triggerdown', this.onTriggerDown);
  43997. el.addEventListener('triggerup', this.onTriggerUp);
  43998. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  43999. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  44000. el.addEventListener('griptouchstart', this.onGripTouchStart);
  44001. el.addEventListener('griptouchend', this.onGripTouchEnd);
  44002. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  44003. el.addEventListener('thumbstickup', this.onThumbstickUp);
  44004. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  44005. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  44006. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44007. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44008. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44009. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44010. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44011. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44012. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44013. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44014. },
  44015. removeEventListeners: function () {
  44016. var el = this.el;
  44017. el.removeEventListener('gripdown', this.onGripDown);
  44018. el.removeEventListener('gripup', this.onGripUp);
  44019. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  44020. el.removeEventListener('trackpadup', this.onTrackpadUp);
  44021. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44022. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44023. el.removeEventListener('triggerdown', this.onTriggerDown);
  44024. el.removeEventListener('triggerup', this.onTriggerUp);
  44025. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  44026. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  44027. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  44028. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  44029. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  44030. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  44031. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  44032. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  44033. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  44034. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  44035. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  44036. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  44037. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  44038. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  44039. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44040. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44041. },
  44042. /**
  44043. * Update handler. More like the `init` handler since the only property is the hand, and
  44044. * that won't be changing much.
  44045. */
  44046. update: function (previousHand) {
  44047. var controlConfiguration;
  44048. var el = this.el;
  44049. var hand = this.data;
  44050. // Get common configuration to abstract different vendor controls.
  44051. controlConfiguration = {
  44052. hand: hand,
  44053. model: false,
  44054. rotationOffset: hand === 'left' ? 90 : -90
  44055. };
  44056. // Set model.
  44057. if (hand !== previousHand) {
  44058. this.loader.load(MODEL_URLS[hand], function (scene) {
  44059. var mesh = scene.getObjectByName('Hand');
  44060. mesh.material.skinning = true;
  44061. mesh.mixer = new THREE.AnimationMixer(mesh);
  44062. el.setObject3D('mesh', mesh);
  44063. mesh.position.set(0, 0, 0);
  44064. mesh.rotation.set(0, 0, 0);
  44065. // hidden by default
  44066. mesh.visible = false;
  44067. el.setAttribute('vive-controls', controlConfiguration);
  44068. el.setAttribute('oculus-touch-controls', controlConfiguration);
  44069. el.setAttribute('windows-motion-controls', controlConfiguration);
  44070. });
  44071. }
  44072. },
  44073. remove: function () {
  44074. this.el.removeObject3D('mesh');
  44075. },
  44076. /**
  44077. * Play model animation, based on which button was pressed and which kind of event.
  44078. *
  44079. * 1. Process buttons.
  44080. * 2. Determine gesture (this.determineGesture()).
  44081. * 3. Animation gesture (this.animationGesture()).
  44082. * 4. Emit gesture events (this.emitGestureEvents()).
  44083. *
  44084. * @param {string} button - Name of the button.
  44085. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  44086. */
  44087. handleButton: function (button, evt) {
  44088. var lastGesture;
  44089. var isPressed = evt === 'down';
  44090. var isTouched = evt === 'touchstart';
  44091. // Update objects.
  44092. if (evt.indexOf('touch') === 0) {
  44093. // Update touch object.
  44094. if (isTouched === this.touchedButtons[button]) { return; }
  44095. this.touchedButtons[button] = isTouched;
  44096. } else {
  44097. // Update button object.
  44098. if (isPressed === this.pressedButtons[button]) { return; }
  44099. this.pressedButtons[button] = isPressed;
  44100. }
  44101. // Determine the gesture.
  44102. lastGesture = this.gesture;
  44103. this.gesture = this.determineGesture();
  44104. // Same gesture.
  44105. if (this.gesture === lastGesture) { return; }
  44106. // Animate gesture.
  44107. this.animateGesture(this.gesture, lastGesture);
  44108. // Emit events.
  44109. this.emitGestureEvents(this.gesture, lastGesture);
  44110. },
  44111. /**
  44112. * Determine which pose hand should be in considering active and touched buttons.
  44113. */
  44114. determineGesture: function () {
  44115. var gesture;
  44116. var isGripActive = this.pressedButtons['grip'];
  44117. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  44118. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  44119. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  44120. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  44121. var isVive = isViveController(this.el.components['tracked-controls']);
  44122. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  44123. if (isGripActive) {
  44124. if (isVive) {
  44125. gesture = ANIMATIONS.fist;
  44126. } else
  44127. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  44128. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  44129. } else {
  44130. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  44131. }
  44132. } else {
  44133. if (isTriggerActive) {
  44134. gesture = !isVive ? ANIMATIONS.hold : ANIMATIONS.fist;
  44135. } else if (isVive && isTrackpadActive) {
  44136. gesture = ANIMATIONS.point;
  44137. }
  44138. }
  44139. return gesture;
  44140. },
  44141. /**
  44142. * Play gesture animation.
  44143. *
  44144. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  44145. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  44146. */
  44147. animateGesture: function (gesture, lastGesture) {
  44148. if (gesture) {
  44149. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  44150. return;
  44151. }
  44152. // If no gesture, then reverse the current gesture back to open pose.
  44153. this.playAnimation(lastGesture, lastGesture, true);
  44154. },
  44155. /**
  44156. * Emit `hand-controls`-specific events.
  44157. */
  44158. emitGestureEvents: function (gesture, lastGesture) {
  44159. var el = this.el;
  44160. var eventName;
  44161. if (lastGesture === gesture) { return; }
  44162. // Emit event for lastGesture not inactive.
  44163. eventName = getGestureEventName(lastGesture, false);
  44164. if (eventName) { el.emit(eventName); }
  44165. // Emit event for current gesture now active.
  44166. eventName = getGestureEventName(gesture, true);
  44167. if (eventName) { el.emit(eventName); }
  44168. },
  44169. /**
  44170. * Play hand animation based on button state.
  44171. *
  44172. * @param {string} gesture - Name of the animation as specified by the model.
  44173. * @param {string} lastGesture - Previous pose.
  44174. * @param {boolean} reverse - Whether animation should play in reverse.
  44175. */
  44176. playAnimation: function (gesture, lastGesture, reverse) {
  44177. var fromAction;
  44178. var mesh = this.el.getObject3D('mesh');
  44179. var toAction;
  44180. if (!mesh) { return; }
  44181. // Grab clip action.
  44182. toAction = mesh.mixer.clipAction(gesture);
  44183. toAction.clampWhenFinished = true;
  44184. toAction.loop = THREE.PingPong;
  44185. toAction.repetitions = 0;
  44186. toAction.timeScale = reverse ? -1 : 1;
  44187. toAction.weight = 1;
  44188. // No gesture to gesture or gesture to no gesture.
  44189. if (!lastGesture || gesture === lastGesture) {
  44190. // Stop all current animations.
  44191. mesh.mixer.stopAllAction();
  44192. // Play animation.
  44193. toAction.play();
  44194. return;
  44195. }
  44196. // Animate or crossfade from gesture to gesture.
  44197. fromAction = mesh.mixer.clipAction(lastGesture);
  44198. mesh.mixer.stopAllAction();
  44199. fromAction.weight = 0.15;
  44200. fromAction.play();
  44201. toAction.play();
  44202. fromAction.crossFadeTo(toAction, 0.15, true);
  44203. },
  44204. setModelVisibility: function (visible) {
  44205. var model = this.el.getObject3D('mesh');
  44206. if (!model) { return; }
  44207. model.visible = visible;
  44208. }
  44209. });
  44210. /**
  44211. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  44212. *
  44213. * @param {string} gesture
  44214. * @param {boolean} active
  44215. */
  44216. function getGestureEventName (gesture, active) {
  44217. var eventName;
  44218. if (!gesture) { return; }
  44219. eventName = EVENTS[gesture];
  44220. if (eventName === 'grip') {
  44221. return eventName + (active ? 'close' : 'open');
  44222. }
  44223. if (eventName === 'point' || eventName === 'thumb') {
  44224. return eventName + (active ? 'up' : 'down');
  44225. }
  44226. if (eventName === 'pointing' || eventName === 'pistol') {
  44227. return eventName + (active ? 'start' : 'end');
  44228. }
  44229. return;
  44230. }
  44231. function isViveController (trackedControls) {
  44232. var controllerId = trackedControls && trackedControls.controller &&
  44233. trackedControls.controller.id;
  44234. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  44235. }
  44236. },{"../core/component":125}],85:[function(_dereq_,module,exports){
  44237. _dereq_('./camera');
  44238. _dereq_('./collada-model');
  44239. _dereq_('./cursor');
  44240. _dereq_('./daydream-controls');
  44241. _dereq_('./gearvr-controls');
  44242. _dereq_('./geometry');
  44243. _dereq_('./gltf-model');
  44244. _dereq_('./hand-controls');
  44245. _dereq_('./laser-controls');
  44246. _dereq_('./light');
  44247. _dereq_('./line');
  44248. _dereq_('./link');
  44249. _dereq_('./look-controls');
  44250. _dereq_('./material');
  44251. _dereq_('./obj-model');
  44252. _dereq_('./oculus-touch-controls');
  44253. _dereq_('./position');
  44254. _dereq_('./raycaster');
  44255. _dereq_('./rotation');
  44256. _dereq_('./scale');
  44257. _dereq_('./shadow');
  44258. _dereq_('./sound');
  44259. _dereq_('./text');
  44260. _dereq_('./tracked-controls');
  44261. _dereq_('./visible');
  44262. _dereq_('./vive-controls');
  44263. _dereq_('./wasd-controls');
  44264. _dereq_('./windows-motion-controls');
  44265. _dereq_('./scene/debug');
  44266. _dereq_('./scene/embedded');
  44267. _dereq_('./scene/inspector');
  44268. _dereq_('./scene/fog');
  44269. _dereq_('./scene/keyboard-shortcuts');
  44270. _dereq_('./scene/pool');
  44271. _dereq_('./scene/screenshot');
  44272. _dereq_('./scene/stats');
  44273. _dereq_('./scene/vr-mode-ui');
  44274. },{"./camera":77,"./collada-model":78,"./cursor":79,"./daydream-controls":80,"./gearvr-controls":81,"./geometry":82,"./gltf-model":83,"./hand-controls":84,"./laser-controls":86,"./light":87,"./line":88,"./link":89,"./look-controls":90,"./material":91,"./obj-model":92,"./oculus-touch-controls":93,"./position":94,"./raycaster":95,"./rotation":96,"./scale":97,"./scene/debug":98,"./scene/embedded":99,"./scene/fog":100,"./scene/inspector":101,"./scene/keyboard-shortcuts":102,"./scene/pool":103,"./scene/screenshot":104,"./scene/stats":105,"./scene/vr-mode-ui":106,"./shadow":107,"./sound":108,"./text":109,"./tracked-controls":110,"./visible":111,"./vive-controls":112,"./wasd-controls":113,"./windows-motion-controls":114}],86:[function(_dereq_,module,exports){
  44275. var registerComponent = _dereq_('../core/component').registerComponent;
  44276. var utils = _dereq_('../utils/');
  44277. registerComponent('laser-controls', {
  44278. schema: {
  44279. hand: {default: 'right'}
  44280. },
  44281. init: function () {
  44282. var config = this.config;
  44283. var data = this.data;
  44284. var el = this.el;
  44285. var self = this;
  44286. // Set all controller models.
  44287. el.setAttribute('daydream-controls', {hand: data.hand});
  44288. el.setAttribute('gearvr-controls', {hand: data.hand});
  44289. el.setAttribute('oculus-touch-controls', {hand: data.hand});
  44290. el.setAttribute('vive-controls', {hand: data.hand});
  44291. el.setAttribute('windows-motion-controls', {hand: data.hand});
  44292. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  44293. el.addEventListener('controllerconnected', createRay);
  44294. el.addEventListener('controllerdisconnected', hideRay);
  44295. el.addEventListener('controllermodelready', function (evt) {
  44296. createRay(evt);
  44297. self.modelReady = true;
  44298. });
  44299. function createRay (evt) {
  44300. var controllerConfig = config[evt.detail.name];
  44301. if (!controllerConfig) { return; }
  44302. // Show the line unless a particular config opts to hide it, until a controllermodelready
  44303. // event comes through.
  44304. var raycasterConfig = utils.extend({
  44305. showLine: true
  44306. }, controllerConfig.raycaster || {});
  44307. // The controllermodelready event contains a rayOrigin that takes into account
  44308. // offsets specific to the loaded model.
  44309. if (evt.detail.rayOrigin) {
  44310. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  44311. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  44312. raycasterConfig.showLine = true;
  44313. }
  44314. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  44315. // config applied from a controllermodelready event.
  44316. if (evt.detail.rayOrigin || !self.modelReady) {
  44317. el.setAttribute('raycaster', raycasterConfig);
  44318. } else {
  44319. el.setAttribute('raycaster', 'showLine', true);
  44320. }
  44321. el.setAttribute('cursor', utils.extend({
  44322. fuse: false
  44323. }, controllerConfig.cursor));
  44324. }
  44325. function hideRay () {
  44326. el.setAttribute('raycaster', 'showLine', false);
  44327. }
  44328. },
  44329. config: {
  44330. 'daydream-controls': {
  44331. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']}
  44332. },
  44333. 'gearvr-controls': {
  44334. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']},
  44335. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  44336. },
  44337. 'oculus-touch-controls': {
  44338. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44339. raycaster: {origin: {x: 0.001, y: 0, z: 0.065}, direction: {x: 0, y: -0.8, z: -1}}
  44340. },
  44341. 'vive-controls': {
  44342. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  44343. },
  44344. 'windows-motion-controls': {
  44345. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44346. raycaster: {showLine: false}
  44347. }
  44348. }
  44349. });
  44350. },{"../core/component":125,"../utils/":195}],87:[function(_dereq_,module,exports){
  44351. var bind = _dereq_('../utils/bind');
  44352. var diff = _dereq_('../utils').diff;
  44353. var debug = _dereq_('../utils/debug');
  44354. var registerComponent = _dereq_('../core/component').registerComponent;
  44355. var THREE = _dereq_('../lib/three');
  44356. var degToRad = THREE.Math.degToRad;
  44357. var warn = debug('components:light:warn');
  44358. /**
  44359. * Light component.
  44360. */
  44361. module.exports.Component = registerComponent('light', {
  44362. schema: {
  44363. angle: {default: 60, if: {type: ['spot']}},
  44364. color: {type: 'color'},
  44365. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  44366. decay: {default: 1, if: {type: ['point', 'spot']}},
  44367. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  44368. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  44369. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  44370. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  44371. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  44372. // Shadows.
  44373. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  44374. shadowBias: {default: 0, if: {castShadow: true}},
  44375. shadowCameraFar: {default: 500, if: {castShadow: true}},
  44376. shadowCameraFov: {default: 90, if: {castShadow: true}},
  44377. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  44378. shadowCameraTop: {default: 5, if: {castShadow: true}},
  44379. shadowCameraRight: {default: 5, if: {castShadow: true}},
  44380. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  44381. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  44382. shadowCameraVisible: {default: false, if: {castShadow: true}},
  44383. shadowMapHeight: {default: 512, if: {castShadow: true}},
  44384. shadowMapWidth: {default: 512, if: {castShadow: true}}
  44385. },
  44386. /**
  44387. * Notifies scene a light has been added to remove default lighting.
  44388. */
  44389. init: function () {
  44390. var el = this.el;
  44391. this.light = null;
  44392. this.defaultTarget = null;
  44393. this.system.registerLight(el);
  44394. },
  44395. /**
  44396. * (Re)create or update light.
  44397. */
  44398. update: function (oldData) {
  44399. var data = this.data;
  44400. var diffData = diff(data, oldData);
  44401. var light = this.light;
  44402. var self = this;
  44403. // Existing light.
  44404. if (light && !('type' in diffData)) {
  44405. var shadowsLoaded = false;
  44406. // Light type has not changed. Update light.
  44407. Object.keys(diffData).forEach(function (key) {
  44408. var value = data[key];
  44409. switch (key) {
  44410. case 'color': {
  44411. light.color.set(value);
  44412. break;
  44413. }
  44414. case 'groundColor': {
  44415. light.groundColor.set(value);
  44416. break;
  44417. }
  44418. case 'angle': {
  44419. light.angle = degToRad(value);
  44420. break;
  44421. }
  44422. case 'target': {
  44423. // Reset target if selector is null.
  44424. if (value === null) {
  44425. if (data.type === 'spot' || data.type === 'directional') {
  44426. light.target = self.defaultTarget;
  44427. }
  44428. } else {
  44429. // Target specified, set target to entity's `object3D` when it is loaded.
  44430. if (value.hasLoaded) {
  44431. self.onSetTarget(value, light);
  44432. } else {
  44433. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  44434. }
  44435. }
  44436. break;
  44437. }
  44438. case 'castShadow':
  44439. case 'shadowBias':
  44440. case 'shadowCameraFar':
  44441. case 'shadowCameraFov':
  44442. case 'shadowCameraNear':
  44443. case 'shadowCameraTop':
  44444. case 'shadowCameraRight':
  44445. case 'shadowCameraBottom':
  44446. case 'shadowCameraLeft':
  44447. case 'shadowCameraVisible':
  44448. case 'shadowMapHeight':
  44449. case 'shadowMapWidth':
  44450. if (!shadowsLoaded) {
  44451. self.updateShadow();
  44452. shadowsLoaded = true;
  44453. }
  44454. break;
  44455. default: {
  44456. light[key] = value;
  44457. }
  44458. }
  44459. });
  44460. return;
  44461. }
  44462. // No light yet or light type has changed. Create and add light.
  44463. this.setLight(this.data);
  44464. this.updateShadow();
  44465. },
  44466. setLight: function (data) {
  44467. var el = this.el;
  44468. var newLight = this.getLight(data);
  44469. if (newLight) {
  44470. if (this.light) {
  44471. el.removeObject3D('light');
  44472. }
  44473. this.light = newLight;
  44474. this.light.el = el;
  44475. el.setObject3D('light', this.light);
  44476. // HACK solution for issue #1624
  44477. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  44478. el.getObject3D('light').translateY(-1);
  44479. }
  44480. // set and position default lighttarget as a child to enable spotlight orientation
  44481. if (data.type === 'spot') {
  44482. el.setObject3D('light-target', this.defaultTarget);
  44483. el.getObject3D('light-target').position.set(0, 0, -1);
  44484. }
  44485. }
  44486. },
  44487. /**
  44488. * Updates shadow-related properties on the current light.
  44489. */
  44490. updateShadow: function () {
  44491. var el = this.el;
  44492. var data = this.data;
  44493. var light = this.light;
  44494. light.castShadow = data.castShadow;
  44495. // Shadow camera helper.
  44496. var cameraHelper = el.getObject3D('cameraHelper');
  44497. if (data.shadowCameraVisible && !cameraHelper) {
  44498. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  44499. } else if (!data.shadowCameraVisible && cameraHelper) {
  44500. el.removeObject3D('cameraHelper');
  44501. }
  44502. if (!data.castShadow) { return light; }
  44503. // Shadow appearance.
  44504. light.shadow.bias = data.shadowBias;
  44505. light.shadow.mapSize.height = data.shadowMapHeight;
  44506. light.shadow.mapSize.width = data.shadowMapWidth;
  44507. // Shadow camera.
  44508. light.shadow.camera.near = data.shadowCameraNear;
  44509. light.shadow.camera.far = data.shadowCameraFar;
  44510. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  44511. light.shadow.camera.top = data.shadowCameraTop;
  44512. light.shadow.camera.right = data.shadowCameraRight;
  44513. light.shadow.camera.bottom = data.shadowCameraBottom;
  44514. light.shadow.camera.left = data.shadowCameraLeft;
  44515. } else {
  44516. light.shadow.camera.fov = data.shadowCameraFov;
  44517. }
  44518. light.shadow.camera.updateProjectionMatrix();
  44519. if (cameraHelper) { cameraHelper.update(); }
  44520. },
  44521. /**
  44522. * Creates a new three.js light object given data object defining the light.
  44523. *
  44524. * @param {object} data
  44525. */
  44526. getLight: function (data) {
  44527. var angle = data.angle;
  44528. var color = new THREE.Color(data.color).getHex();
  44529. var decay = data.decay;
  44530. var distance = data.distance;
  44531. var groundColor = new THREE.Color(data.groundColor).getHex();
  44532. var intensity = data.intensity;
  44533. var type = data.type;
  44534. var target = data.target;
  44535. var light = null;
  44536. switch (type.toLowerCase()) {
  44537. case 'ambient': {
  44538. return new THREE.AmbientLight(color, intensity);
  44539. }
  44540. case 'directional': {
  44541. light = new THREE.DirectionalLight(color, intensity);
  44542. this.defaultTarget = light.target;
  44543. if (target) {
  44544. if (target.hasLoaded) {
  44545. this.onSetTarget(target, light);
  44546. } else {
  44547. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44548. }
  44549. }
  44550. return light;
  44551. }
  44552. case 'hemisphere': {
  44553. return new THREE.HemisphereLight(color, groundColor, intensity);
  44554. }
  44555. case 'point': {
  44556. return new THREE.PointLight(color, intensity, distance, decay);
  44557. }
  44558. case 'spot': {
  44559. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  44560. this.defaultTarget = light.target;
  44561. if (target) {
  44562. if (target.hasLoaded) {
  44563. this.onSetTarget(target, light);
  44564. } else {
  44565. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44566. }
  44567. }
  44568. return light;
  44569. }
  44570. default: {
  44571. warn('%s is not a valid light type. ' +
  44572. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  44573. }
  44574. }
  44575. },
  44576. onSetTarget: function (targetEl, light) {
  44577. light.target = targetEl.object3D;
  44578. },
  44579. /**
  44580. * Remove light on remove (callback).
  44581. */
  44582. remove: function () {
  44583. var el = this.el;
  44584. el.removeObject3D('light');
  44585. if (el.getObject3D('cameraHelper')) {
  44586. el.removeObject3D('cameraHelper');
  44587. }
  44588. }
  44589. });
  44590. },{"../core/component":125,"../lib/three":173,"../utils":195,"../utils/bind":189,"../utils/debug":191}],88:[function(_dereq_,module,exports){
  44591. /* global THREE */
  44592. var registerComponent = _dereq_('../core/component').registerComponent;
  44593. module.exports.Component = registerComponent('line', {
  44594. schema: {
  44595. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44596. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44597. color: {type: 'color', default: '#74BEC1'},
  44598. opacity: {type: 'number', default: 1},
  44599. visible: {default: true}
  44600. },
  44601. multiple: true,
  44602. init: function () {
  44603. var data = this.data;
  44604. var geometry;
  44605. var material;
  44606. material = this.material = new THREE.LineBasicMaterial({
  44607. color: data.color,
  44608. opacity: data.opacity,
  44609. transparent: data.opacity < 1,
  44610. visible: data.visible
  44611. });
  44612. geometry = this.geometry = new THREE.BufferGeometry();
  44613. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  44614. this.line = new THREE.Line(geometry, material);
  44615. this.el.setObject3D(this.attrName, this.line);
  44616. },
  44617. update: function (oldData) {
  44618. var data = this.data;
  44619. var geometry = this.geometry;
  44620. var geoNeedsUpdate = false;
  44621. var material = this.material;
  44622. var positionArray = geometry.attributes.position.array;
  44623. // Update geometry.
  44624. if (!isEqualVec3(data.start, oldData.start)) {
  44625. positionArray[0] = data.start.x;
  44626. positionArray[1] = data.start.y;
  44627. positionArray[2] = data.start.z;
  44628. geoNeedsUpdate = true;
  44629. }
  44630. if (!isEqualVec3(data.end, oldData.end)) {
  44631. positionArray[3] = data.end.x;
  44632. positionArray[4] = data.end.y;
  44633. positionArray[5] = data.end.z;
  44634. geoNeedsUpdate = true;
  44635. }
  44636. if (geoNeedsUpdate) {
  44637. geometry.attributes.position.needsUpdate = true;
  44638. geometry.computeBoundingSphere();
  44639. }
  44640. material.color.setStyle(data.color);
  44641. material.opacity = data.opacity;
  44642. material.transparent = data.opacity < 1;
  44643. material.visible = data.visible;
  44644. },
  44645. remove: function () {
  44646. this.el.removeObject3D('line', this.line);
  44647. }
  44648. });
  44649. function isEqualVec3 (a, b) {
  44650. if (!a || !b) { return false; }
  44651. return (a.x === b.x && a.y === b.y && a.z === b.z);
  44652. }
  44653. },{"../core/component":125}],89:[function(_dereq_,module,exports){
  44654. var registerComponent = _dereq_('../core/component').registerComponent;
  44655. var registerShader = _dereq_('../core/shader').registerShader;
  44656. var THREE = _dereq_('../lib/three');
  44657. /**
  44658. * Link component. Connect experiences and traverse between them in VR
  44659. *
  44660. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  44661. */
  44662. module.exports.Component = registerComponent('link', {
  44663. schema: {
  44664. backgroundColor: {default: 'red', type: 'color'},
  44665. borderColor: {default: 'white', type: 'color'},
  44666. highlighted: {default: false},
  44667. highlightedColor: {default: '#24CAFF', type: 'color'},
  44668. href: {default: ''},
  44669. image: {type: 'asset'},
  44670. on: {default: 'click'},
  44671. peekMode: {default: false},
  44672. title: {default: ''},
  44673. titleColor: {default: 'white', type: 'color'},
  44674. visualAspectEnabled: {default: true}
  44675. },
  44676. init: function () {
  44677. this.navigate = this.navigate.bind(this);
  44678. this.previousQuaternion = undefined;
  44679. // Store hidden elements during peek mode so we can show them again later.
  44680. this.hiddenEls = [];
  44681. this.initVisualAspect();
  44682. },
  44683. update: function (oldData) {
  44684. var data = this.data;
  44685. var el = this.el;
  44686. var backgroundColor;
  44687. var strokeColor;
  44688. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  44689. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  44690. el.setAttribute('material', 'backgroundColor', backgroundColor);
  44691. el.setAttribute('material', 'strokeColor', strokeColor);
  44692. if (data.on !== oldData.on) { this.updateEventListener(); }
  44693. if (data.visualAspectEnabled && oldData.peekMode !== undefined &&
  44694. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  44695. if (!data.image || oldData.image === data.image) { return; }
  44696. el.setAttribute('material', 'pano',
  44697. typeof data.image === 'string' ? data.image : data.image.src);
  44698. },
  44699. /*
  44700. * Toggle all elements and full 360 preview of the linked page.
  44701. */
  44702. updatePeekMode: function () {
  44703. var el = this.el;
  44704. var sphereEl = this.sphereEl;
  44705. if (this.data.peekMode) {
  44706. this.hideAll();
  44707. el.getObject3D('mesh').visible = false;
  44708. sphereEl.setAttribute('visible', true);
  44709. } else {
  44710. this.showAll();
  44711. el.getObject3D('mesh').visible = true;
  44712. sphereEl.setAttribute('visible', false);
  44713. }
  44714. },
  44715. play: function () {
  44716. this.updateEventListener();
  44717. },
  44718. pause: function () {
  44719. this.removeEventListener();
  44720. },
  44721. updateEventListener: function () {
  44722. var el = this.el;
  44723. if (!el.isPlaying) { return; }
  44724. this.removeEventListener();
  44725. el.addEventListener(this.data.on, this.navigate);
  44726. },
  44727. removeEventListener: function () {
  44728. var on = this.data.on;
  44729. if (!on) { return; }
  44730. this.el.removeEventListener(on, this.navigate);
  44731. },
  44732. initVisualAspect: function () {
  44733. var el = this.el;
  44734. var semiSphereEl;
  44735. var sphereEl;
  44736. var textEl;
  44737. if (!this.data.visualAspectEnabled) { return; }
  44738. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  44739. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  44740. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  44741. // Set portal.
  44742. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  44743. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  44744. // Set text that displays the link title and URL.
  44745. textEl.setAttribute('text', {
  44746. color: this.data.titleColor,
  44747. align: 'center',
  44748. font: 'kelsonsans',
  44749. value: this.data.title || this.data.href,
  44750. width: 4
  44751. });
  44752. textEl.setAttribute('position', '0 1.5 0');
  44753. el.appendChild(textEl);
  44754. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  44755. semiSphereEl.setAttribute('geometry', {
  44756. primitive: 'sphere',
  44757. radius: 1.0,
  44758. phiStart: 0,
  44759. segmentsWidth: 64,
  44760. segmentsHeight: 64,
  44761. phiLength: 180,
  44762. thetaStart: 0,
  44763. thetaLength: 360
  44764. });
  44765. semiSphereEl.setAttribute('material', {
  44766. shader: 'portal',
  44767. borderEnabled: 0.0,
  44768. pano: this.data.image,
  44769. side: 'back'
  44770. });
  44771. semiSphereEl.setAttribute('rotation', '0 180 0');
  44772. semiSphereEl.setAttribute('position', '0 0 0');
  44773. semiSphereEl.setAttribute('visible', false);
  44774. el.appendChild(semiSphereEl);
  44775. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  44776. sphereEl.setAttribute('geometry', {
  44777. primitive: 'sphere',
  44778. radius: 10,
  44779. segmentsWidth: 64,
  44780. segmentsHeight: 64
  44781. });
  44782. sphereEl.setAttribute('material', {
  44783. shader: 'portal',
  44784. borderEnabled: 0.0,
  44785. pano: this.data.image,
  44786. side: 'back'
  44787. });
  44788. sphereEl.setAttribute('visible', false);
  44789. el.appendChild(sphereEl);
  44790. },
  44791. navigate: function () {
  44792. window.location = this.data.href;
  44793. },
  44794. /**
  44795. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  44796. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  44797. * from where user enters.
  44798. * 2. Place the url/title above or inside portal depending on distance to camera.
  44799. * 3. Face portal to camera when far away from user.
  44800. */
  44801. tick: (function () {
  44802. var cameraWorldPosition = new THREE.Vector3();
  44803. var elWorldPosition = new THREE.Vector3();
  44804. var quaternion = new THREE.Quaternion();
  44805. var scale = new THREE.Vector3();
  44806. return function () {
  44807. var el = this.el;
  44808. var object3D = el.object3D;
  44809. var camera = el.sceneEl.camera;
  44810. var cameraPortalOrientation;
  44811. var distance;
  44812. var textEl = this.textEl;
  44813. if (!this.data.visualAspectEnabled) { return; }
  44814. // Update matrices
  44815. object3D.updateMatrixWorld();
  44816. camera.parent.updateMatrixWorld();
  44817. camera.updateMatrixWorld();
  44818. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  44819. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  44820. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  44821. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  44822. // Store original orientation to be restored when the portal stops facing the camera.
  44823. this.previousQuaternion = this.previousQuaternion || quaternion.clone();
  44824. if (distance > 20) {
  44825. // If the portal is far away from the user, face portal to camera.
  44826. object3D.lookAt(cameraWorldPosition);
  44827. } else {
  44828. // When portal is close to the user/camera.
  44829. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  44830. // If user gets very close to portal, replace with holed sphere they can peek in.
  44831. if (distance < 0.5) {
  44832. // Configure text size and sphere orientation depending side user approaches portal.
  44833. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  44834. textEl.setAttribute('text', 'width', 1.5);
  44835. if (cameraPortalOrientation <= 0.0) {
  44836. textEl.setAttribute('position', '0 0 0.75');
  44837. textEl.setAttribute('rotation', '0 180 0');
  44838. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  44839. } else {
  44840. textEl.setAttribute('position', '0 0 -0.75');
  44841. textEl.setAttribute('rotation', '0 0 0');
  44842. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  44843. }
  44844. el.getObject3D('mesh').visible = false;
  44845. this.semiSphereEl.setAttribute('visible', true);
  44846. this.peekCameraPortalOrientation = cameraPortalOrientation;
  44847. } else {
  44848. // Calculate wich side the camera is approaching the camera (back / front).
  44849. // Adjust text orientation based on camera position.
  44850. if (cameraPortalOrientation <= 0.0) {
  44851. textEl.setAttribute('rotation', '0 180 0');
  44852. } else {
  44853. textEl.setAttribute('rotation', '0 0 0');
  44854. }
  44855. textEl.setAttribute('text', 'width', 5);
  44856. textEl.setAttribute('position', '0 1.5 0');
  44857. el.getObject3D('mesh').visible = true;
  44858. this.semiSphereEl.setAttribute('visible', false);
  44859. this.peekCameraPortalOrientation = undefined;
  44860. }
  44861. if (this.previousQuaternion) {
  44862. object3D.quaternion.copy(this.previousQuaternion);
  44863. this.previousQuaternion = undefined;
  44864. }
  44865. }
  44866. };
  44867. })(),
  44868. hideAll: function () {
  44869. var el = this.el;
  44870. var hiddenEls = this.hiddenEls;
  44871. var self = this;
  44872. if (hiddenEls.length > 0) { return; }
  44873. el.sceneEl.object3D.traverse(function (object) {
  44874. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  44875. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  44876. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  44877. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  44878. object.el === self.semiSphereEl) {
  44879. return;
  44880. }
  44881. object.el.setAttribute('visible', false);
  44882. hiddenEls.push(object.el);
  44883. });
  44884. },
  44885. showAll: function () {
  44886. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  44887. this.hiddenEls = [];
  44888. },
  44889. /**
  44890. * Calculate whether the camera faces the front or back face of the portal.
  44891. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  44892. */
  44893. calculateCameraPortalOrientation: (function () {
  44894. var mat4 = new THREE.Matrix4();
  44895. var cameraPosition = new THREE.Vector3();
  44896. var portalNormal = new THREE.Vector3(0, 0, 1);
  44897. var portalPosition = new THREE.Vector3(0, 0, 0);
  44898. return function () {
  44899. var el = this.el;
  44900. var camera = el.sceneEl.camera;
  44901. // Reset tmp variables.
  44902. cameraPosition.set(0, 0, 0);
  44903. portalNormal.set(0, 0, 1);
  44904. portalPosition.set(0, 0, 0);
  44905. // Apply portal orientation to the normal.
  44906. el.object3D.matrixWorld.extractRotation(mat4);
  44907. portalNormal.applyMatrix4(mat4);
  44908. // Calculate portal world position.
  44909. el.object3D.updateMatrixWorld();
  44910. el.object3D.localToWorld(portalPosition);
  44911. // Calculate camera world position.
  44912. camera.parent.parent.updateMatrixWorld();
  44913. camera.parent.updateMatrixWorld();
  44914. camera.updateMatrixWorld();
  44915. camera.localToWorld(cameraPosition);
  44916. // Calculate vector from portal to camera.
  44917. // (portal) -------> (camera)
  44918. cameraPosition.sub(portalPosition).normalize();
  44919. portalNormal.normalize();
  44920. // Side where camera approaches portal is given by sign of dot product of portal normal
  44921. // and portal to camera vectors.
  44922. return Math.sign(portalNormal.dot(cameraPosition));
  44923. };
  44924. })(),
  44925. remove: function () {
  44926. this.removeEventListener();
  44927. }
  44928. });
  44929. /* eslint-disable */
  44930. registerShader('portal', {
  44931. schema: {
  44932. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  44933. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  44934. pano: {type: 'map', is: 'uniform'},
  44935. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  44936. },
  44937. vertexShader: [
  44938. 'vec3 portalPosition;',
  44939. 'varying vec3 vWorldPosition;',
  44940. 'varying float vDistanceToCenter;',
  44941. 'varying float vDistance;',
  44942. 'void main() {',
  44943. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  44944. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  44945. 'vDistance = length(portalPosition - cameraPosition);',
  44946. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  44947. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  44948. '}'
  44949. ].join('\n'),
  44950. fragmentShader: [
  44951. '#define RECIPROCAL_PI2 0.15915494',
  44952. 'uniform sampler2D pano;',
  44953. 'uniform vec3 strokeColor;',
  44954. 'uniform vec3 backgroundColor;',
  44955. 'uniform float borderEnabled;',
  44956. 'varying float vDistanceToCenter;',
  44957. 'varying float vDistance;',
  44958. 'varying vec3 vWorldPosition;',
  44959. 'void main() {',
  44960. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  44961. 'vec2 sampleUV;',
  44962. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  44963. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  44964. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  44965. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  44966. 'gl_FragColor = vec4(strokeColor, 1.0);',
  44967. '} else {',
  44968. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  44969. '}',
  44970. '}'
  44971. ].join('\n')
  44972. });
  44973. /* eslint-enable */
  44974. },{"../core/component":125,"../core/shader":134,"../lib/three":173}],90:[function(_dereq_,module,exports){
  44975. var registerComponent = _dereq_('../core/component').registerComponent;
  44976. var THREE = _dereq_('../lib/three');
  44977. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  44978. var bind = _dereq_('../utils/bind');
  44979. // To avoid recalculation at every mouse movement tick
  44980. var GRABBING_CLASS = 'a-grabbing';
  44981. var PI_2 = Math.PI / 2;
  44982. var radToDeg = THREE.Math.radToDeg;
  44983. /**
  44984. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  44985. */
  44986. module.exports.Component = registerComponent('look-controls', {
  44987. dependencies: ['position', 'rotation'],
  44988. schema: {
  44989. enabled: {default: true},
  44990. touchEnabled: {default: true},
  44991. hmdEnabled: {default: true},
  44992. reverseMouseDrag: {default: false},
  44993. standing: {default: true}
  44994. },
  44995. init: function () {
  44996. var sceneEl = this.el.sceneEl;
  44997. this.previousHMDPosition = new THREE.Vector3();
  44998. this.hmdQuaternion = new THREE.Quaternion();
  44999. this.hmdEuler = new THREE.Euler();
  45000. this.position = new THREE.Vector3();
  45001. this.rotation = {};
  45002. this.deltaRotation = {};
  45003. this.setupMouseControls();
  45004. this.setupHMDControls();
  45005. this.bindMethods();
  45006. // Reset previous HMD position when we exit VR.
  45007. sceneEl.addEventListener('exit-vr', this.onExitVR);
  45008. },
  45009. update: function (oldData) {
  45010. var data = this.data;
  45011. // Disable grab cursor classes if no longer enabled.
  45012. if (data.enabled !== oldData.enabled) {
  45013. this.updateGrabCursor(data.enabled);
  45014. }
  45015. // Reset pitch and yaw if disabling HMD.
  45016. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  45017. this.pitchObject.rotation.set(0, 0, 0);
  45018. this.yawObject.rotation.set(0, 0, 0);
  45019. }
  45020. },
  45021. tick: function (t) {
  45022. var data = this.data;
  45023. if (!data.enabled) { return; }
  45024. this.controls.standing = data.standing;
  45025. this.controls.userHeight = this.getUserHeight();
  45026. this.controls.update();
  45027. this.updateOrientation();
  45028. this.updatePosition();
  45029. },
  45030. /**
  45031. * Return user height to use for standing poses, where a device doesn't provide an offset.
  45032. */
  45033. getUserHeight: function () {
  45034. var el = this.el;
  45035. return el.hasAttribute('camera')
  45036. ? el.getAttribute('camera').userHeight
  45037. : DEFAULT_CAMERA_HEIGHT;
  45038. },
  45039. play: function () {
  45040. this.addEventListeners();
  45041. },
  45042. pause: function () {
  45043. this.removeEventListeners();
  45044. },
  45045. remove: function () {
  45046. this.removeEventListeners();
  45047. },
  45048. bindMethods: function () {
  45049. this.onMouseDown = bind(this.onMouseDown, this);
  45050. this.onMouseMove = bind(this.onMouseMove, this);
  45051. this.onMouseUp = bind(this.onMouseUp, this);
  45052. this.onTouchStart = bind(this.onTouchStart, this);
  45053. this.onTouchMove = bind(this.onTouchMove, this);
  45054. this.onTouchEnd = bind(this.onTouchEnd, this);
  45055. this.onExitVR = bind(this.onExitVR, this);
  45056. },
  45057. /**
  45058. * Set up states and Object3Ds needed to store rotation data.
  45059. */
  45060. setupMouseControls: function () {
  45061. this.mouseDown = false;
  45062. this.pitchObject = new THREE.Object3D();
  45063. this.yawObject = new THREE.Object3D();
  45064. this.yawObject.position.y = 10;
  45065. this.yawObject.add(this.pitchObject);
  45066. },
  45067. /**
  45068. * Set up VR controls that will copy data to the dolly.
  45069. */
  45070. setupHMDControls: function () {
  45071. this.dolly = new THREE.Object3D();
  45072. this.euler = new THREE.Euler();
  45073. this.controls = new THREE.VRControls(this.dolly);
  45074. this.controls.userHeight = 0.0;
  45075. },
  45076. /**
  45077. * Add mouse and touch event listeners to canvas.
  45078. */
  45079. addEventListeners: function () {
  45080. var sceneEl = this.el.sceneEl;
  45081. var canvasEl = sceneEl.canvas;
  45082. // Wait for canvas to load.
  45083. if (!canvasEl) {
  45084. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  45085. return;
  45086. }
  45087. // Mouse events.
  45088. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  45089. window.addEventListener('mousemove', this.onMouseMove, false);
  45090. window.addEventListener('mouseup', this.onMouseUp, false);
  45091. // Touch events.
  45092. canvasEl.addEventListener('touchstart', this.onTouchStart);
  45093. window.addEventListener('touchmove', this.onTouchMove);
  45094. window.addEventListener('touchend', this.onTouchEnd);
  45095. },
  45096. /**
  45097. * Remove mouse and touch event listeners from canvas.
  45098. */
  45099. removeEventListeners: function () {
  45100. var sceneEl = this.el.sceneEl;
  45101. var canvasEl = sceneEl && sceneEl.canvas;
  45102. if (!canvasEl) { return; }
  45103. // Mouse events.
  45104. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  45105. canvasEl.removeEventListener('mousemove', this.onMouseMove);
  45106. canvasEl.removeEventListener('mouseup', this.onMouseUp);
  45107. canvasEl.removeEventListener('mouseout', this.onMouseUp);
  45108. // Touch events.
  45109. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  45110. canvasEl.removeEventListener('touchmove', this.onTouchMove);
  45111. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  45112. },
  45113. /**
  45114. * Update orientation for mobile, mouse drag, and headset.
  45115. * Mouse-drag only enabled if HMD is not active.
  45116. */
  45117. updateOrientation: function () {
  45118. var currentRotation;
  45119. var deltaRotation = this.deltaRotation;
  45120. var hmdEuler = this.hmdEuler;
  45121. var hmdQuaternion = this.hmdQuaternion;
  45122. var pitchObject = this.pitchObject;
  45123. var yawObject = this.yawObject;
  45124. var sceneEl = this.el.sceneEl;
  45125. var rotation = this.rotation;
  45126. // Calculate HMD quaternion.
  45127. hmdQuaternion = hmdQuaternion.copy(this.dolly.quaternion);
  45128. hmdEuler.setFromQuaternion(hmdQuaternion, 'YXZ');
  45129. if (sceneEl.isMobile) {
  45130. // On mobile, do camera rotation with touch events and sensors.
  45131. rotation.x = radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x);
  45132. rotation.y = radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y);
  45133. rotation.z = radToDeg(hmdEuler.z);
  45134. } else if (!sceneEl.is('vr-mode') || isNullVector(hmdEuler) || !this.data.hmdEnabled) {
  45135. // Mouse drag if WebVR not active (not connected, no incoming sensor data).
  45136. currentRotation = this.el.getAttribute('rotation');
  45137. this.calculateDeltaRotation();
  45138. if (this.data.reverseMouseDrag) {
  45139. rotation.x = currentRotation.x - deltaRotation.x;
  45140. rotation.y = currentRotation.y - deltaRotation.y;
  45141. rotation.z = currentRotation.z;
  45142. } else {
  45143. rotation.x = currentRotation.x + deltaRotation.x;
  45144. rotation.y = currentRotation.y + deltaRotation.y;
  45145. rotation.z = currentRotation.z;
  45146. }
  45147. } else {
  45148. // Mouse rotation ignored with an active headset. Use headset rotation.
  45149. rotation.x = radToDeg(hmdEuler.x);
  45150. rotation.y = radToDeg(hmdEuler.y);
  45151. rotation.z = radToDeg(hmdEuler.z);
  45152. }
  45153. this.el.setAttribute('rotation', rotation);
  45154. },
  45155. /**
  45156. * Calculate delta rotation for mouse-drag and touch-drag.
  45157. */
  45158. calculateDeltaRotation: function () {
  45159. var currentRotationX = radToDeg(this.pitchObject.rotation.x);
  45160. var currentRotationY = radToDeg(this.yawObject.rotation.y);
  45161. this.deltaRotation.x = currentRotationX - (this.previousRotationX || 0);
  45162. this.deltaRotation.y = currentRotationY - (this.previousRotationY || 0);
  45163. // Store current rotation for next tick.
  45164. this.previousRotationX = currentRotationX;
  45165. this.previousRotationY = currentRotationY;
  45166. return this.deltaRotation;
  45167. },
  45168. /**
  45169. * Handle positional tracking.
  45170. */
  45171. updatePosition: function () {
  45172. var el = this.el;
  45173. var currentHMDPosition;
  45174. var currentPosition;
  45175. var position = this.position;
  45176. var previousHMDPosition = this.previousHMDPosition;
  45177. var sceneEl = this.el.sceneEl;
  45178. if (!sceneEl.is('vr-mode')) { return; }
  45179. // Calculate change in position.
  45180. currentHMDPosition = this.calculateHMDPosition();
  45181. currentPosition = el.getAttribute('position');
  45182. position.copy(currentPosition).sub(previousHMDPosition).add(currentHMDPosition);
  45183. el.setAttribute('position', position);
  45184. previousHMDPosition.copy(currentHMDPosition);
  45185. },
  45186. /**
  45187. * Get headset position from VRControls.
  45188. */
  45189. calculateHMDPosition: (function () {
  45190. var position = new THREE.Vector3();
  45191. return function () {
  45192. this.dolly.updateMatrix();
  45193. position.setFromMatrixPosition(this.dolly.matrix);
  45194. return position;
  45195. };
  45196. })(),
  45197. /**
  45198. * Translate mouse drag into rotation.
  45199. *
  45200. * Dragging up and down rotates the camera around the X-axis (yaw).
  45201. * Dragging left and right rotates the camera around the Y-axis (pitch).
  45202. */
  45203. onMouseMove: function (event) {
  45204. var pitchObject = this.pitchObject;
  45205. var yawObject = this.yawObject;
  45206. var previousMouseEvent = this.previousMouseEvent;
  45207. var movementX;
  45208. var movementY;
  45209. // Not dragging or not enabled.
  45210. if (!this.mouseDown || !this.data.enabled) { return; }
  45211. // Calculate delta.
  45212. movementX = event.movementX || event.mozMovementX;
  45213. movementY = event.movementY || event.mozMovementY;
  45214. if (movementX === undefined || movementY === undefined) {
  45215. movementX = event.screenX - previousMouseEvent.screenX;
  45216. movementY = event.screenY - previousMouseEvent.screenY;
  45217. }
  45218. this.previousMouseEvent = event;
  45219. // Calculate rotation.
  45220. yawObject.rotation.y -= movementX * 0.002;
  45221. pitchObject.rotation.x -= movementY * 0.002;
  45222. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  45223. },
  45224. /**
  45225. * Register mouse down to detect mouse drag.
  45226. */
  45227. onMouseDown: function (evt) {
  45228. if (!this.data.enabled) { return; }
  45229. // Handle only primary button.
  45230. if (evt.button !== 0) { return; }
  45231. this.mouseDown = true;
  45232. this.previousMouseEvent = evt;
  45233. document.body.classList.add(GRABBING_CLASS);
  45234. },
  45235. /**
  45236. * Register mouse up to detect release of mouse drag.
  45237. */
  45238. onMouseUp: function () {
  45239. this.mouseDown = false;
  45240. document.body.classList.remove(GRABBING_CLASS);
  45241. },
  45242. /**
  45243. * Register touch down to detect touch drag.
  45244. */
  45245. onTouchStart: function (evt) {
  45246. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  45247. this.touchStart = {
  45248. x: evt.touches[0].pageX,
  45249. y: evt.touches[0].pageY
  45250. };
  45251. this.touchStarted = true;
  45252. },
  45253. /**
  45254. * Translate touch move to Y-axis rotation.
  45255. */
  45256. onTouchMove: function (evt) {
  45257. var canvas = this.el.sceneEl.canvas;
  45258. var deltaY;
  45259. var yawObject = this.yawObject;
  45260. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  45261. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  45262. // Limit touch orientaion to to yaw (y axis).
  45263. yawObject.rotation.y -= deltaY * 0.5;
  45264. this.touchStart = {
  45265. x: evt.touches[0].pageX,
  45266. y: evt.touches[0].pageY
  45267. };
  45268. },
  45269. /**
  45270. * Register touch end to detect release of touch drag.
  45271. */
  45272. onTouchEnd: function () {
  45273. this.touchStarted = false;
  45274. },
  45275. onExitVR: function () {
  45276. this.previousHMDPosition.set(0, 0, 0);
  45277. },
  45278. /**
  45279. * Toggle the feature of showing/hiding the grab cursor.
  45280. */
  45281. updateGrabCursor: function (enabled) {
  45282. var sceneEl = this.el.sceneEl;
  45283. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  45284. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  45285. if (!sceneEl.canvas) {
  45286. if (enabled) {
  45287. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  45288. } else {
  45289. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  45290. }
  45291. return;
  45292. }
  45293. if (enabled) {
  45294. enableGrabCursor();
  45295. return;
  45296. }
  45297. disableGrabCursor();
  45298. }
  45299. });
  45300. function isNullVector (vector) {
  45301. return vector.x === 0 && vector.y === 0 && vector.z === 0;
  45302. }
  45303. },{"../constants":116,"../core/component":125,"../lib/three":173,"../utils/bind":189}],91:[function(_dereq_,module,exports){
  45304. /* global Promise */
  45305. var utils = _dereq_('../utils/');
  45306. var component = _dereq_('../core/component');
  45307. var THREE = _dereq_('../lib/three');
  45308. var shader = _dereq_('../core/shader');
  45309. var error = utils.debug('components:material:error');
  45310. var registerComponent = component.registerComponent;
  45311. var shaders = shader.shaders;
  45312. var shaderNames = shader.shaderNames;
  45313. /**
  45314. * Material component.
  45315. *
  45316. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  45317. * three.js's implementation of PBR. Another standard shading model is `flat` which
  45318. * uses MeshBasicMaterial.
  45319. */
  45320. module.exports.Component = registerComponent('material', {
  45321. schema: {
  45322. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  45323. depthTest: {default: true},
  45324. depthWrite: {default: true},
  45325. flatShading: {default: false},
  45326. npot: {default: false},
  45327. offset: {type: 'vec2', default: {x: 0, y: 0}},
  45328. opacity: {default: 1.0, min: 0.0, max: 1.0},
  45329. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  45330. shader: {default: 'standard', oneOf: shaderNames},
  45331. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  45332. transparent: {default: false},
  45333. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  45334. visible: {default: true}
  45335. },
  45336. init: function () {
  45337. this.material = null;
  45338. },
  45339. /**
  45340. * Update or create material.
  45341. *
  45342. * @param {object|null} oldData
  45343. */
  45344. update: function (oldData) {
  45345. var data = this.data;
  45346. if (!this.shader || data.shader !== oldData.shader) {
  45347. this.updateShader(data.shader);
  45348. }
  45349. this.shader.update(this.data);
  45350. this.updateMaterial(oldData);
  45351. },
  45352. updateSchema: function (data) {
  45353. var newShader = data.shader;
  45354. var currentShader = this.data && this.data.shader;
  45355. var shader = newShader || currentShader;
  45356. var schema = shaders[shader] && shaders[shader].schema;
  45357. if (!schema) { error('Unknown shader schema ' + shader); }
  45358. if (currentShader && newShader === currentShader) { return; }
  45359. this.extendSchema(schema);
  45360. this.updateBehavior();
  45361. },
  45362. updateBehavior: function () {
  45363. var schema = this.schema;
  45364. var self = this;
  45365. var sceneEl = this.el.sceneEl;
  45366. var tickProperties = {};
  45367. var tick = function (time, delta) {
  45368. Object.keys(tickProperties).forEach(function update (key) {
  45369. tickProperties[key] = time;
  45370. });
  45371. self.shader.update(tickProperties);
  45372. };
  45373. this.tick = undefined;
  45374. Object.keys(schema).forEach(function (key) {
  45375. if (schema[key].type === 'time') {
  45376. self.tick = tick;
  45377. tickProperties[key] = true;
  45378. }
  45379. });
  45380. if (!sceneEl) { return; }
  45381. if (!this.tick) {
  45382. sceneEl.removeBehavior(this);
  45383. } else {
  45384. sceneEl.addBehavior(this);
  45385. }
  45386. },
  45387. updateShader: function (shaderName) {
  45388. var data = this.data;
  45389. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  45390. var shaderInstance;
  45391. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  45392. // Get material from A-Frame shader.
  45393. shaderInstance = this.shader = new Shader();
  45394. shaderInstance.el = this.el;
  45395. shaderInstance.init(data);
  45396. this.setMaterial(shaderInstance.material);
  45397. this.updateSchema(data);
  45398. },
  45399. /**
  45400. * Set and update base material properties.
  45401. * Set `needsUpdate` when needed.
  45402. */
  45403. updateMaterial: function (oldData) {
  45404. var data = this.data;
  45405. var material = this.material;
  45406. // Base material properties.
  45407. material.alphaTest = data.alphaTest;
  45408. material.depthTest = data.depthTest !== false;
  45409. material.depthWrite = data.depthWrite !== false;
  45410. material.opacity = data.opacity;
  45411. material.flatShading = data.flatShading;
  45412. material.side = parseSide(data.side);
  45413. material.transparent = data.transparent !== false || data.opacity < 1.0;
  45414. material.vertexColors = parseVertexColors(data.vertexColors);
  45415. material.visible = data.visible;
  45416. // Check if material needs update.
  45417. if (Object.keys(oldData).length &&
  45418. (oldData.alphaTest !== data.alphaTest ||
  45419. oldData.side !== data.side ||
  45420. oldData.vertexColors !== data.vertexColors)) {
  45421. material.needsUpdate = true;
  45422. }
  45423. },
  45424. /**
  45425. * Remove material on remove (callback).
  45426. * Dispose of it from memory and unsubscribe from scene updates.
  45427. */
  45428. remove: function () {
  45429. var defaultMaterial = new THREE.MeshBasicMaterial();
  45430. var material = this.material;
  45431. var object3D = this.el.getObject3D('mesh');
  45432. if (object3D) { object3D.material = defaultMaterial; }
  45433. disposeMaterial(material, this.system);
  45434. },
  45435. /**
  45436. * (Re)create new material. Has side-effects of setting `this.material` and updating
  45437. * material registration in scene.
  45438. *
  45439. * @param {object} data - Material component data.
  45440. * @param {object} type - Material type to create.
  45441. * @returns {object} Material.
  45442. */
  45443. setMaterial: function (material) {
  45444. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  45445. var system = this.system;
  45446. if (this.material) { disposeMaterial(this.material, system); }
  45447. this.material = mesh.material = material;
  45448. system.registerMaterial(material);
  45449. }
  45450. });
  45451. /**
  45452. * Return a three.js constant determining which material face sides to render
  45453. * based on the side parameter (passed as a component property).
  45454. *
  45455. * @param {string} [side=front] - `front`, `back`, or `double`.
  45456. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  45457. */
  45458. function parseSide (side) {
  45459. switch (side) {
  45460. case 'back': {
  45461. return THREE.BackSide;
  45462. }
  45463. case 'double': {
  45464. return THREE.DoubleSide;
  45465. }
  45466. default: {
  45467. // Including case `front`.
  45468. return THREE.FrontSide;
  45469. }
  45470. }
  45471. }
  45472. /**
  45473. * Return a three.js constant determining vertex coloring.
  45474. */
  45475. function parseVertexColors (coloring) {
  45476. switch (coloring) {
  45477. case 'face': {
  45478. return THREE.FaceColors;
  45479. }
  45480. case 'vertex': {
  45481. return THREE.VertexColors;
  45482. }
  45483. default: {
  45484. return THREE.NoColors;
  45485. }
  45486. }
  45487. }
  45488. /**
  45489. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  45490. */
  45491. function disposeMaterial (material, system) {
  45492. material.dispose();
  45493. system.unregisterMaterial(material);
  45494. }
  45495. },{"../core/component":125,"../core/shader":134,"../lib/three":173,"../utils/":195}],92:[function(_dereq_,module,exports){
  45496. var debug = _dereq_('../utils/debug');
  45497. var registerComponent = _dereq_('../core/component').registerComponent;
  45498. var THREE = _dereq_('../lib/three');
  45499. var warn = debug('components:obj-model:warn');
  45500. module.exports.Component = registerComponent('obj-model', {
  45501. schema: {
  45502. mtl: {type: 'model'},
  45503. obj: {type: 'model'}
  45504. },
  45505. init: function () {
  45506. this.model = null;
  45507. this.objLoader = new THREE.OBJLoader();
  45508. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  45509. // Allow cross-origin images to be loaded.
  45510. this.mtlLoader.crossOrigin = '';
  45511. },
  45512. update: function () {
  45513. var data = this.data;
  45514. if (!data.obj) { return; }
  45515. this.remove();
  45516. this.loadObj(data.obj, data.mtl);
  45517. },
  45518. remove: function () {
  45519. if (!this.model) { return; }
  45520. this.el.removeObject3D('mesh');
  45521. },
  45522. loadObj: function (objUrl, mtlUrl) {
  45523. var self = this;
  45524. var el = this.el;
  45525. var mtlLoader = this.mtlLoader;
  45526. var objLoader = this.objLoader;
  45527. if (mtlUrl) {
  45528. // .OBJ with an .MTL.
  45529. if (el.hasAttribute('material')) {
  45530. warn('Material component properties are ignored when a .MTL is provided');
  45531. }
  45532. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  45533. mtlLoader.load(mtlUrl, function (materials) {
  45534. materials.preload();
  45535. objLoader.setMaterials(materials);
  45536. objLoader.load(objUrl, function (objModel) {
  45537. self.model = objModel;
  45538. el.setObject3D('mesh', objModel);
  45539. el.emit('model-loaded', {format: 'obj', model: objModel});
  45540. });
  45541. });
  45542. return;
  45543. }
  45544. // .OBJ only.
  45545. objLoader.load(objUrl, function loadObjOnly (objModel) {
  45546. // Apply material.
  45547. var material = el.components.material;
  45548. if (material) {
  45549. objModel.traverse(function (child) {
  45550. if (child instanceof THREE.Mesh) {
  45551. child.material = material.material;
  45552. }
  45553. });
  45554. }
  45555. self.model = objModel;
  45556. el.setObject3D('mesh', objModel);
  45557. el.emit('model-loaded', {format: 'obj', model: objModel});
  45558. });
  45559. }
  45560. });
  45561. },{"../core/component":125,"../lib/three":173,"../utils/debug":191}],93:[function(_dereq_,module,exports){
  45562. var bind = _dereq_('../utils/bind');
  45563. var registerComponent = _dereq_('../core/component').registerComponent;
  45564. var controllerUtils = _dereq_('../utils/tracked-controls');
  45565. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  45566. var TOUCH_CONTROLLER_MODEL_OBJ_URL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.obj';
  45567. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.mtl';
  45568. var TOUCH_CONTROLLER_MODEL_OBJ_URL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.obj';
  45569. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.mtl';
  45570. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  45571. var PIVOT_OFFSET = {x: 0, y: -0.015, z: 0.04};
  45572. /**
  45573. * Oculus Touch controls.
  45574. * Interface with Oculus Touch controllers and map Gamepad events to
  45575. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  45576. * Load a controller model and highlight the pressed buttons.
  45577. */
  45578. module.exports.Component = registerComponent('oculus-touch-controls', {
  45579. schema: {
  45580. hand: {default: 'left'},
  45581. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  45582. buttonTouchColor: {type: 'color', default: '#8AB'},
  45583. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  45584. model: {default: true},
  45585. rotationOffset: {default: 0}
  45586. },
  45587. /**
  45588. * Button IDs:
  45589. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  45590. * 1 - trigger (with analog value, which goes up to 1)
  45591. * 2 - grip (with analog value, which goes up to 1)
  45592. * 3 - X (left) or A (right)
  45593. * 4 - Y (left) or B (right)
  45594. * 5 - surface (touch only)
  45595. */
  45596. mapping: {
  45597. left: {
  45598. axes: {thumbstick: [0, 1]},
  45599. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  45600. },
  45601. right: {
  45602. axes: {thumbstick: [0, 1]},
  45603. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  45604. }
  45605. },
  45606. bindMethods: function () {
  45607. this.onModelLoaded = bind(this.onModelLoaded, this);
  45608. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45609. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45610. this.onAxisMoved = bind(this.onAxisMoved, this);
  45611. },
  45612. init: function () {
  45613. var self = this;
  45614. this.onButtonChanged = bind(this.onButtonChanged, this);
  45615. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  45616. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  45617. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  45618. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  45619. this.controllerPresent = false;
  45620. this.lastControllerCheck = 0;
  45621. this.previousButtonValues = {};
  45622. this.bindMethods();
  45623. // Allow mock.
  45624. this.emitIfAxesChanged = controllerUtils.emitIfAxesChanged;
  45625. this.checkControllerPresentAndSetup = controllerUtils.checkControllerPresentAndSetup;
  45626. },
  45627. addEventListeners: function () {
  45628. var el = this.el;
  45629. el.addEventListener('buttonchanged', this.onButtonChanged);
  45630. el.addEventListener('buttondown', this.onButtonDown);
  45631. el.addEventListener('buttonup', this.onButtonUp);
  45632. el.addEventListener('touchstart', this.onButtonTouchStart);
  45633. el.addEventListener('touchend', this.onButtonTouchEnd);
  45634. el.addEventListener('axismove', this.onAxisMoved);
  45635. el.addEventListener('model-loaded', this.onModelLoaded);
  45636. this.controllerEventsActive = true;
  45637. },
  45638. removeEventListeners: function () {
  45639. var el = this.el;
  45640. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45641. el.removeEventListener('buttondown', this.onButtonDown);
  45642. el.removeEventListener('buttonup', this.onButtonUp);
  45643. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45644. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45645. el.removeEventListener('axismove', this.onAxisMoved);
  45646. el.removeEventListener('model-loaded', this.onModelLoaded);
  45647. this.controllerEventsActive = false;
  45648. },
  45649. checkIfControllerPresent: function () {
  45650. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  45651. hand: this.data.hand
  45652. });
  45653. },
  45654. play: function () {
  45655. this.checkIfControllerPresent();
  45656. this.addControllersUpdateListener();
  45657. },
  45658. pause: function () {
  45659. this.removeEventListeners();
  45660. this.removeControllersUpdateListener();
  45661. },
  45662. updateControllerModel: function () {
  45663. var objUrl, mtlUrl;
  45664. if (!this.data.model) { return; }
  45665. if (this.data.hand === 'right') {
  45666. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_R + ')';
  45667. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_R + ')';
  45668. } else {
  45669. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_L + ')';
  45670. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_L + ')';
  45671. }
  45672. this.el.setAttribute('obj-model', {obj: objUrl, mtl: mtlUrl});
  45673. },
  45674. injectTrackedControls: function () {
  45675. var data = this.data;
  45676. var offset = data.hand === 'right' ? -90 : 90;
  45677. this.el.setAttribute('tracked-controls', {
  45678. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  45679. controller: 0,
  45680. rotationOffset: data.rotationOffset !== -999 ? data.rotationOffset : offset
  45681. });
  45682. this.updateControllerModel();
  45683. },
  45684. addControllersUpdateListener: function () {
  45685. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45686. },
  45687. removeControllersUpdateListener: function () {
  45688. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45689. },
  45690. onControllersUpdate: function () {
  45691. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45692. this.checkIfControllerPresent();
  45693. },
  45694. onButtonChanged: function (evt) {
  45695. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  45696. var buttonMeshes = this.buttonMeshes;
  45697. var analogValue;
  45698. if (!button) { return; }
  45699. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  45700. // Update trigger and/or grip meshes, if any.
  45701. if (buttonMeshes) {
  45702. if (button === 'trigger' && buttonMeshes.trigger) {
  45703. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  45704. }
  45705. if (button === 'grip' && buttonMeshes.grip) {
  45706. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  45707. }
  45708. }
  45709. // Pass along changed event with button state, using the buttom mapping for convenience.
  45710. this.el.emit(button + 'changed', evt.detail.state);
  45711. },
  45712. onModelLoaded: function (evt) {
  45713. var controllerObject3D = evt.detail.model;
  45714. var buttonMeshes;
  45715. if (!this.data.model) { return; }
  45716. var leftHand = this.data.hand === 'left';
  45717. buttonMeshes = this.buttonMeshes = {};
  45718. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  45719. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  45720. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  45721. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  45722. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  45723. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  45724. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  45725. // Offset pivot point
  45726. controllerObject3D.position = PIVOT_OFFSET;
  45727. },
  45728. onButtonEvent: function (id, evtName) {
  45729. var buttonName = this.mapping[this.data.hand].buttons[id];
  45730. var i;
  45731. if (Array.isArray(buttonName)) {
  45732. for (i = 0; i < buttonName.length; i++) {
  45733. this.el.emit(buttonName[i] + evtName);
  45734. }
  45735. } else {
  45736. this.el.emit(buttonName + evtName);
  45737. }
  45738. this.updateModel(buttonName, evtName);
  45739. },
  45740. onAxisMoved: function (evt) {
  45741. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  45742. },
  45743. updateModel: function (buttonName, evtName) {
  45744. var i;
  45745. if (Array.isArray(buttonName)) {
  45746. for (i = 0; i < buttonName.length; i++) {
  45747. this.updateButtonModel(buttonName[i], evtName);
  45748. }
  45749. } else {
  45750. this.updateButtonModel(buttonName, evtName);
  45751. }
  45752. },
  45753. updateButtonModel: function (buttonName, state) {
  45754. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  45755. var buttonMeshes = this.buttonMeshes;
  45756. if (!this.data.model) { return; }
  45757. if (buttonMeshes && buttonMeshes[buttonName]) {
  45758. buttonMeshes[buttonName].material.color.set(color);
  45759. }
  45760. }
  45761. });
  45762. },{"../core/component":125,"../utils/bind":189,"../utils/tracked-controls":200}],94:[function(_dereq_,module,exports){
  45763. var registerComponent = _dereq_('../core/component').registerComponent;
  45764. module.exports.Component = registerComponent('position', {
  45765. schema: {type: 'vec3'},
  45766. update: function () {
  45767. var object3D = this.el.object3D;
  45768. var data = this.data;
  45769. object3D.position.set(data.x, data.y, data.z);
  45770. }
  45771. });
  45772. },{"../core/component":125}],95:[function(_dereq_,module,exports){
  45773. /* global MutationObserver */
  45774. var registerComponent = _dereq_('../core/component').registerComponent;
  45775. var THREE = _dereq_('../lib/three');
  45776. var utils = _dereq_('../utils/');
  45777. var warn = utils.debug('components:raycaster:warn');
  45778. var dummyVec = new THREE.Vector3();
  45779. // Defines selectors that should be 'safe' for the MutationObserver used to
  45780. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  45781. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  45782. // reliably detected and are therefore disallowed.
  45783. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  45784. // Configuration for the MutationObserver used to refresh the whitelist.
  45785. // Listens for addition/removal of elements and attributes within the scene.
  45786. var OBSERVER_CONFIG = {
  45787. childList: true,
  45788. attributes: true,
  45789. subtree: true
  45790. };
  45791. /**
  45792. * Raycaster component.
  45793. *
  45794. * Pass options to three.js Raycaster including which objects to test.
  45795. * Poll for intersections.
  45796. * Emit event on origin entity and on target entity on intersect.
  45797. *
  45798. * @member {array} intersectedEls - List of currently intersected entities.
  45799. * @member {array} objects - Cached list of meshes to intersect.
  45800. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  45801. * @member {object} raycaster - three.js Raycaster.
  45802. */
  45803. module.exports.Component = registerComponent('raycaster', {
  45804. schema: {
  45805. autoRefresh: {default: true},
  45806. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  45807. enabled: {default: true},
  45808. far: {default: 1000},
  45809. interval: {default: 100},
  45810. near: {default: 0},
  45811. objects: {default: ''},
  45812. origin: {type: 'vec3'},
  45813. recursive: {default: true},
  45814. showLine: {default: false},
  45815. useWorldCoordinates: {default: false}
  45816. },
  45817. init: function () {
  45818. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  45819. // adjust line length.
  45820. this.clearedIntersectedEls = [];
  45821. this.unitLineEndVec3 = new THREE.Vector3();
  45822. this.intersectedEls = [];
  45823. this.objects = [];
  45824. this.prevCheckTime = undefined;
  45825. this.prevIntersectedEls = [];
  45826. this.raycaster = new THREE.Raycaster();
  45827. this.updateOriginDirection();
  45828. this.setDirty = this.setDirty.bind(this);
  45829. this.observer = new MutationObserver(this.setDirty);
  45830. this.dirty = true;
  45831. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  45832. },
  45833. /**
  45834. * Create or update raycaster object.
  45835. */
  45836. update: function (oldData) {
  45837. var data = this.data;
  45838. var el = this.el;
  45839. var raycaster = this.raycaster;
  45840. // Set raycaster properties.
  45841. raycaster.far = data.far;
  45842. raycaster.near = data.near;
  45843. // Draw line.
  45844. if (data.showLine &&
  45845. (data.far !== oldData.far || data.origin !== oldData.origin ||
  45846. data.direction !== oldData.direction || data.showLine !== oldData.showLine)) {
  45847. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  45848. this.drawLine();
  45849. }
  45850. if (!data.showLine && oldData.showLine) {
  45851. el.removeAttribute('line');
  45852. }
  45853. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  45854. warn('Selector "' + data.objects + '" may not update automatically with DOM changes.');
  45855. }
  45856. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  45857. data.autoRefresh
  45858. ? this.addEventListeners()
  45859. : this.removeEventListeners();
  45860. }
  45861. this.setDirty();
  45862. },
  45863. play: function () {
  45864. this.addEventListeners();
  45865. },
  45866. pause: function () {
  45867. this.removeEventListeners();
  45868. },
  45869. remove: function () {
  45870. if (this.data.showLine) {
  45871. this.el.removeAttribute('line');
  45872. }
  45873. },
  45874. addEventListeners: function () {
  45875. if (!this.data.autoRefresh) { return; }
  45876. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  45877. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  45878. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  45879. },
  45880. removeEventListeners: function () {
  45881. this.observer.disconnect();
  45882. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  45883. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  45884. },
  45885. /**
  45886. * Mark the object list as dirty, to be refreshed before next raycast.
  45887. */
  45888. setDirty: function () {
  45889. this.dirty = true;
  45890. },
  45891. /**
  45892. * Update list of objects to test for intersection.
  45893. */
  45894. refreshObjects: function () {
  45895. var data = this.data;
  45896. // If objects not defined, intersect with everything.
  45897. var els = data.objects
  45898. ? this.el.sceneEl.querySelectorAll(data.objects)
  45899. : this.el.sceneEl.children;
  45900. this.objects = flattenChildrenShallow(els);
  45901. this.dirty = false;
  45902. },
  45903. /**
  45904. * Check for intersections and cleared intersections on an interval.
  45905. */
  45906. tick: (function () {
  45907. var intersections = [];
  45908. return function (time) {
  45909. var clearedIntersectedEls = this.clearedIntersectedEls;
  45910. var el = this.el;
  45911. var data = this.data;
  45912. var i;
  45913. var intersectedEls = this.intersectedEls;
  45914. var intersection;
  45915. var lineLength;
  45916. var prevCheckTime = this.prevCheckTime;
  45917. var prevIntersectedEls = this.prevIntersectedEls;
  45918. var rawIntersections;
  45919. if (!this.data.enabled) { return; }
  45920. // Only check for intersection if interval time has passed.
  45921. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45922. // Update check time.
  45923. this.prevCheckTime = time;
  45924. // Refresh the object whitelist if needed.
  45925. if (this.dirty) { this.refreshObjects(); }
  45926. // Store old previously intersected entities.
  45927. copyArray(this.prevIntersectedEls, this.intersectedEls);
  45928. // Raycast.
  45929. this.updateOriginDirection();
  45930. rawIntersections = this.raycaster.intersectObjects(this.objects, data.recursive);
  45931. // Only keep intersections against objects that have a reference to an entity.
  45932. intersections.length = 0;
  45933. for (i = 0; i < rawIntersections.length; i++) {
  45934. intersection = rawIntersections[i];
  45935. // Don't intersect with own line.
  45936. if (data.showLine && intersection.object === el.getObject3D('line')) {
  45937. continue;
  45938. }
  45939. if (intersection.object.el) {
  45940. intersections.push(intersection);
  45941. }
  45942. }
  45943. // Update intersectedEls.
  45944. intersectedEls.length = intersections.length;
  45945. for (i = 0; i < intersections.length; i++) {
  45946. intersectedEls[i] = intersections[i].object.el;
  45947. }
  45948. // Emit intersected on intersected entity per intersected entity.
  45949. for (i = 0; i < intersections.length; i++) {
  45950. intersections[i].object.el.emit('raycaster-intersected', {
  45951. el: el,
  45952. intersection: intersections[i]
  45953. });
  45954. }
  45955. // Emit all intersections at once on raycasting entity.
  45956. if (intersections.length) {
  45957. el.emit('raycaster-intersection', {
  45958. els: intersectedEls,
  45959. intersections: intersections
  45960. });
  45961. }
  45962. // Emit intersection cleared on both entities per formerly intersected entity.
  45963. clearedIntersectedEls.length = 0;
  45964. for (i = 0; i < prevIntersectedEls.length; i++) {
  45965. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  45966. prevIntersectedEls[i].emit('raycaster-intersected-cleared', {el: el});
  45967. clearedIntersectedEls.push(prevIntersectedEls[i]);
  45968. }
  45969. if (clearedIntersectedEls.length) {
  45970. el.emit('raycaster-intersection-cleared', this.intersectionClearedDetail);
  45971. }
  45972. // Update line length.
  45973. if (data.showLine) {
  45974. if (intersections.length) {
  45975. if (intersections[0].object.el === el && intersections[1]) {
  45976. lineLength = intersections[1].distance;
  45977. } else {
  45978. lineLength = intersections[0].distance;
  45979. }
  45980. }
  45981. this.drawLine(lineLength);
  45982. }
  45983. };
  45984. })(),
  45985. /**
  45986. * Update origin and direction of raycaster using entity transforms and supplied origin or
  45987. * direction offsets.
  45988. */
  45989. updateOriginDirection: (function () {
  45990. var direction = new THREE.Vector3();
  45991. var quaternion = new THREE.Quaternion();
  45992. var originVec3 = new THREE.Vector3();
  45993. // Closure to make quaternion/vector3 objects private.
  45994. return function updateOriginDirection () {
  45995. var el = this.el;
  45996. var data = this.data;
  45997. if (data.useWorldCoordinates) {
  45998. this.raycaster.set(data.origin, data.direction);
  45999. return;
  46000. }
  46001. // Grab the position and rotation.
  46002. el.object3D.updateMatrixWorld();
  46003. el.object3D.matrixWorld.decompose(originVec3, quaternion, dummyVec);
  46004. // If non-zero origin, translate the origin into world space.
  46005. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  46006. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  46007. }
  46008. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  46009. // provide. Apply the offset to the direction, then rotation from the object,
  46010. // and normalize.
  46011. direction.copy(data.direction).add(data.origin).applyQuaternion(quaternion).normalize();
  46012. // Apply offset and direction, in world coordinates.
  46013. this.raycaster.set(originVec3, direction);
  46014. };
  46015. })(),
  46016. /**
  46017. * Create or update line to give raycaster visual representation.
  46018. * Customize the line through through line component.
  46019. * We draw the line in the raycaster component to customize the line to the
  46020. * raycaster's origin, direction, and far.
  46021. *
  46022. * Unlike the raycaster, we create the line as a child of the object. The line will
  46023. * be affected by the transforms of the objects, so we don't have to calculate transforms
  46024. * like we do with the raycaster.
  46025. *
  46026. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  46027. * point. If not provided, length will default to the max length, `raycaster.far`.
  46028. */
  46029. drawLine: (function (length) {
  46030. var lineEndVec3 = new THREE.Vector3();
  46031. var otherLineEndVec3 = new THREE.Vector3();
  46032. var lineData = {end: lineEndVec3};
  46033. return function (length) {
  46034. var data = this.data;
  46035. var el = this.el;
  46036. // We switch each time the vector so the line update is triggered
  46037. // and to avoid unnecessary vector clone.
  46038. var endVec3 = lineData.end === lineEndVec3 ? otherLineEndVec3 : lineEndVec3;
  46039. // Treat Infinity as 1000m for the line.
  46040. if (length === undefined) {
  46041. length = data.far === Infinity ? 1000 : data.far;
  46042. }
  46043. // Update the length of the line if given. `unitLineEndVec3` is the direction
  46044. // given by data.direction, then we apply a scalar to give it a length.
  46045. lineData.start = data.origin;
  46046. lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  46047. el.setAttribute('line', lineData);
  46048. };
  46049. })()
  46050. });
  46051. /**
  46052. * Returns children of each element's object3D group. Children are flattened
  46053. * by one level, removing the THREE.Group wrapper, so that non-recursive
  46054. * raycasting remains useful.
  46055. *
  46056. * @param {Array<Element>} els
  46057. * @return {Array<THREE.Object3D>}
  46058. */
  46059. function flattenChildrenShallow (els) {
  46060. var groups = [];
  46061. var objects = [];
  46062. var children;
  46063. var i;
  46064. // Push meshes onto list of objects to intersect.
  46065. for (i = 0; i < els.length; i++) {
  46066. if (els[i].object3D) {
  46067. groups.push(els[i].object3D);
  46068. }
  46069. }
  46070. // Each entity's root is a THREE.Group. Return the group's chilrden.
  46071. for (i = 0; i < groups.length; i++) {
  46072. children = groups[i].children;
  46073. if (children && children.length) {
  46074. objects.push.apply(objects, children);
  46075. }
  46076. }
  46077. return objects;
  46078. }
  46079. /**
  46080. * Copy contents of one array to another without allocating new array.
  46081. */
  46082. function copyArray (a, b) {
  46083. var i;
  46084. a.length = b.length;
  46085. for (i = 0; i < b.length; i++) {
  46086. a[i] = b[i];
  46087. }
  46088. }
  46089. },{"../core/component":125,"../lib/three":173,"../utils/":195}],96:[function(_dereq_,module,exports){
  46090. var degToRad = _dereq_('../lib/three').Math.degToRad;
  46091. var registerComponent = _dereq_('../core/component').registerComponent;
  46092. module.exports.Component = registerComponent('rotation', {
  46093. schema: {type: 'vec3'},
  46094. /**
  46095. * Updates object3D rotation.
  46096. */
  46097. update: function () {
  46098. var data = this.data;
  46099. var object3D = this.el.object3D;
  46100. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  46101. object3D.rotation.order = 'YXZ';
  46102. }
  46103. });
  46104. },{"../core/component":125,"../lib/three":173}],97:[function(_dereq_,module,exports){
  46105. var registerComponent = _dereq_('../core/component').registerComponent;
  46106. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  46107. var zeroScale = 0.00001;
  46108. module.exports.Component = registerComponent('scale', {
  46109. schema: {
  46110. type: 'vec3',
  46111. default: {x: 1, y: 1, z: 1}
  46112. },
  46113. update: function () {
  46114. var data = this.data;
  46115. var object3D = this.el.object3D;
  46116. var x = data.x === 0 ? zeroScale : data.x;
  46117. var y = data.y === 0 ? zeroScale : data.y;
  46118. var z = data.z === 0 ? zeroScale : data.z;
  46119. object3D.scale.set(x, y, z);
  46120. }
  46121. });
  46122. },{"../core/component":125}],98:[function(_dereq_,module,exports){
  46123. var register = _dereq_('../../core/component').registerComponent;
  46124. module.exports.Component = register('debug', {
  46125. schema: {default: true}
  46126. });
  46127. },{"../../core/component":125}],99:[function(_dereq_,module,exports){
  46128. var registerComponent = _dereq_('../../core/component').registerComponent;
  46129. /**
  46130. * Component to embed an a-frame scene within the layout of a 2D page.
  46131. */
  46132. module.exports.Component = registerComponent('embedded', {
  46133. dependencies: ['vr-mode-ui'],
  46134. schema: {default: true},
  46135. update: function () {
  46136. var sceneEl = this.el;
  46137. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  46138. if (this.data === true) {
  46139. if (enterVREl) { enterVREl.classList.add('embedded'); }
  46140. sceneEl.removeFullScreenStyles();
  46141. } else {
  46142. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  46143. sceneEl.addFullScreenStyles();
  46144. }
  46145. }
  46146. });
  46147. },{"../../core/component":125}],100:[function(_dereq_,module,exports){
  46148. var register = _dereq_('../../core/component').registerComponent;
  46149. var THREE = _dereq_('../../lib/three');
  46150. var debug = _dereq_('../../utils/debug');
  46151. var warn = debug('components:fog:warn');
  46152. /**
  46153. * Fog component.
  46154. * Applies only to the scene entity.
  46155. */
  46156. module.exports.Component = register('fog', {
  46157. schema: {
  46158. color: {type: 'color', default: '#000'},
  46159. density: {default: 0.00025},
  46160. far: {default: 1000, min: 0},
  46161. near: {default: 1, min: 0},
  46162. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  46163. },
  46164. update: function () {
  46165. var data = this.data;
  46166. var el = this.el;
  46167. var fog = this.el.object3D.fog;
  46168. if (!el.isScene) {
  46169. warn('Fog component can only be applied to <a-scene>');
  46170. return;
  46171. }
  46172. // (Re)create fog if fog doesn't exist or fog type changed.
  46173. if (!fog || data.type !== fog.name) {
  46174. el.object3D.fog = getFog(data);
  46175. el.systems.material.updateMaterials();
  46176. return;
  46177. }
  46178. // Fog data changed. Update fog.
  46179. Object.keys(this.schema).forEach(function (key) {
  46180. var value = data[key];
  46181. if (key === 'color') { value = new THREE.Color(value); }
  46182. fog[key] = value;
  46183. });
  46184. },
  46185. /**
  46186. * Remove fog on remove (callback).
  46187. */
  46188. remove: function () {
  46189. var fog = this.el.object3D.fog;
  46190. if (!fog) { return; }
  46191. fog.far = 0;
  46192. fog.near = 0.1;
  46193. }
  46194. });
  46195. /**
  46196. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  46197. *
  46198. * @param {object} data - Fog data.
  46199. * @returns {object} fog
  46200. */
  46201. function getFog (data) {
  46202. var fog;
  46203. if (data.type === 'exponential') {
  46204. fog = new THREE.FogExp2(data.color, data.density);
  46205. } else {
  46206. fog = new THREE.Fog(data.color, data.near, data.far);
  46207. }
  46208. fog.name = data.type;
  46209. return fog;
  46210. }
  46211. },{"../../core/component":125,"../../lib/three":173,"../../utils/debug":191}],101:[function(_dereq_,module,exports){
  46212. (function (process){
  46213. /* global AFRAME */
  46214. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  46215. var bind = _dereq_('../../utils/bind');
  46216. var pkg = _dereq_('../../../package');
  46217. var registerComponent = _dereq_('../../core/component').registerComponent;
  46218. /**
  46219. * 0.4.2 to 0.4.x
  46220. * Will need to update this when A-Frame goes to 1.x.x.
  46221. */
  46222. function getFuzzyPatchVersion (version) {
  46223. var split = version.split('.');
  46224. split[2] = 'x';
  46225. return split.join('.');
  46226. }
  46227. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  46228. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  46229. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  46230. var LOADING_MESSAGE = 'Loading Inspector';
  46231. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  46232. module.exports.Component = registerComponent('inspector', {
  46233. schema: {
  46234. url: {default: INSPECTOR_URL}
  46235. },
  46236. init: function () {
  46237. this.onKeydown = bind(this.onKeydown, this);
  46238. this.onMessage = bind(this.onMessage, this);
  46239. this.initOverlay();
  46240. window.addEventListener('keydown', this.onKeydown);
  46241. window.addEventListener('message', this.onMessage);
  46242. },
  46243. initOverlay: function () {
  46244. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  46245. this.loadingMessageEl = document.createElement('div');
  46246. this.loadingMessageEl.classList.add('a-inspector-loader');
  46247. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  46248. },
  46249. remove: function () {
  46250. this.removeEventListeners();
  46251. },
  46252. /**
  46253. * <ctrl> + <alt> + i keyboard shortcut.
  46254. */
  46255. onKeydown: function (evt) {
  46256. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  46257. if (!this.data || !shortcutPressed) { return; }
  46258. this.injectInspector();
  46259. },
  46260. showLoader: function () {
  46261. document.body.appendChild(this.loadingMessageEl);
  46262. },
  46263. hideLoader: function () {
  46264. document.body.removeChild(this.loadingMessageEl);
  46265. },
  46266. /**
  46267. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  46268. */
  46269. onMessage: function (evt) {
  46270. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  46271. },
  46272. injectInspector: function () {
  46273. var self = this;
  46274. var script;
  46275. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  46276. this.showLoader();
  46277. // Inject.
  46278. script = document.createElement('script');
  46279. script.src = this.data.url;
  46280. script.setAttribute('data-name', 'aframe-inspector');
  46281. script.setAttribute(AFRAME_INJECTED, '');
  46282. script.onload = function () {
  46283. AFRAME.INSPECTOR.open();
  46284. self.hideLoader();
  46285. self.removeEventListeners();
  46286. };
  46287. script.onerror = function () {
  46288. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  46289. };
  46290. document.head.appendChild(script);
  46291. AFRAME.inspectorInjected = true;
  46292. },
  46293. removeEventListeners: function () {
  46294. window.removeEventListener('keydown', this.onKeydown);
  46295. window.removeEventListener('message', this.onMessage);
  46296. }
  46297. });
  46298. }).call(this,_dereq_('_process'))
  46299. },{"../../../package":76,"../../constants":116,"../../core/component":125,"../../utils/bind":189,"_process":33}],102:[function(_dereq_,module,exports){
  46300. var registerComponent = _dereq_('../../core/component').registerComponent;
  46301. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  46302. module.exports.Component = registerComponent('keyboard-shortcuts', {
  46303. schema: {
  46304. enterVR: {default: true},
  46305. exitVR: {default: true}
  46306. },
  46307. init: function () {
  46308. var self = this;
  46309. var scene = this.el;
  46310. this.listener = window.addEventListener('keyup', function (event) {
  46311. if (!shouldCaptureKeyEvent(event)) { return; }
  46312. if (self.enterVREnabled && event.keyCode === 70) { // f.
  46313. scene.enterVR();
  46314. }
  46315. if (self.enterVREnabled && event.keyCode === 27) { // escape.
  46316. scene.exitVR();
  46317. }
  46318. }, false);
  46319. },
  46320. update: function (oldData) {
  46321. var data = this.data;
  46322. this.enterVREnabled = data.enterVR;
  46323. },
  46324. remove: function () {
  46325. window.removeEventListener('keyup', this.listener);
  46326. }
  46327. });
  46328. },{"../../core/component":125,"../../utils/":195}],103:[function(_dereq_,module,exports){
  46329. var debug = _dereq_('../../utils/debug');
  46330. var registerComponent = _dereq_('../../core/component').registerComponent;
  46331. var warn = debug('components:pool:warn');
  46332. /**
  46333. * Pool component.
  46334. * A pool of entities that will be reused.
  46335. * It avoids creating and destroying the same kind of entities
  46336. * in dynamic scenes. It will help reduce GC pauses. Useful for example
  46337. * in a game where you want to reuse enemies entities.
  46338. *
  46339. * @member {array} availableEls - Available entities in the pool.
  46340. * @member {array} usedEls - Entities of the pool in use.
  46341. *
  46342. */
  46343. module.exports.Component = registerComponent('pool', {
  46344. schema: {
  46345. mixin: {default: ''},
  46346. size: {default: 0},
  46347. dynamic: {default: false}
  46348. },
  46349. multiple: true,
  46350. initPool: function () {
  46351. var i;
  46352. var mixin = this.data.mixin;
  46353. if (!mixin) { return; }
  46354. this.availableEls = [];
  46355. this.usedEls = [];
  46356. for (i = 0; i < this.data.size; ++i) {
  46357. this.createEntity();
  46358. }
  46359. },
  46360. update: function (oldData) {
  46361. var data = this.data;
  46362. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  46363. this.initPool();
  46364. }
  46365. },
  46366. /**
  46367. * Add a new entity to the list of available entities.
  46368. */
  46369. createEntity: function () {
  46370. var el = document.createElement('a-entity');
  46371. el.play = this.wrapPlay(el.play);
  46372. el.setAttribute('mixin', this.data.mixin);
  46373. el.setAttribute('visible', false);
  46374. this.el.appendChild(el);
  46375. this.availableEls.push(el);
  46376. },
  46377. /**
  46378. * Play wrapper for pooled entities. When pausing and playing
  46379. * a scene we don't want to play the entities that are not in use
  46380. */
  46381. wrapPlay: function (playMethod) {
  46382. var usedEls = this.usedEls;
  46383. return function () {
  46384. if (usedEls.indexOf(this) === -1) { return; }
  46385. playMethod.call(this);
  46386. };
  46387. },
  46388. /**
  46389. * Used to request one of the available entities of the pool
  46390. */
  46391. requestEntity: function () {
  46392. var el;
  46393. if (this.availableEls.length === 0) {
  46394. if (this.data.dynamic === false) {
  46395. warn('Requested entity from empty pool ' + this.name);
  46396. return;
  46397. } else {
  46398. warn('Requested entity from empty pool. This pool is dynamic' +
  46399. 'and will resize automatically. You might want to increase its initial size' + this.name);
  46400. }
  46401. this.createEntity();
  46402. }
  46403. el = this.availableEls.shift();
  46404. this.usedEls.push(el);
  46405. el.setAttribute('visible', true);
  46406. return el;
  46407. },
  46408. /**
  46409. * Used to return a used entity to the pool
  46410. */
  46411. returnEntity: function (el) {
  46412. var index = this.usedEls.indexOf(el);
  46413. if (index === -1) {
  46414. warn('The returned entity was not previously pooled from ' + this.name);
  46415. return;
  46416. }
  46417. this.usedEls.splice(index, 1);
  46418. this.availableEls.push(el);
  46419. el.setAttribute('visible', false);
  46420. el.pause();
  46421. }
  46422. });
  46423. },{"../../core/component":125,"../../utils/debug":191}],104:[function(_dereq_,module,exports){
  46424. /* global ImageData, URL */
  46425. var registerComponent = _dereq_('../../core/component').registerComponent;
  46426. var THREE = _dereq_('../../lib/three');
  46427. var VERTEX_SHADER = [
  46428. 'attribute vec3 position;',
  46429. 'attribute vec2 uv;',
  46430. 'uniform mat4 projectionMatrix;',
  46431. 'uniform mat4 modelViewMatrix;',
  46432. 'varying vec2 vUv;',
  46433. 'void main() {',
  46434. ' vUv = vec2( 1.- uv.x, uv.y );',
  46435. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  46436. '}'
  46437. ].join('\n');
  46438. var FRAGMENT_SHADER = [
  46439. 'precision mediump float;',
  46440. 'uniform samplerCube map;',
  46441. 'varying vec2 vUv;',
  46442. '#define M_PI 3.141592653589793238462643383279',
  46443. 'void main() {',
  46444. ' vec2 uv = vUv;',
  46445. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  46446. ' float latitude = uv.y * M_PI;',
  46447. ' vec3 dir = vec3(',
  46448. ' - sin( longitude ) * sin( latitude ),',
  46449. ' cos( latitude ),',
  46450. ' - cos( longitude ) * sin( latitude )',
  46451. ' );',
  46452. ' normalize( dir );',
  46453. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  46454. '}'
  46455. ].join('\n');
  46456. /**
  46457. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  46458. * It can be configured to either take 360&deg; captures (`equirectangular`)
  46459. * or regular screenshots (`projection`)
  46460. *
  46461. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  46462. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  46463. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  46464. * WebGLRenderTarget with an ortographic camera.
  46465. */
  46466. module.exports.Component = registerComponent('screenshot', {
  46467. schema: {
  46468. width: {default: 4096},
  46469. height: {default: 2048}
  46470. },
  46471. init: function () {
  46472. var el = this.el;
  46473. var self = this;
  46474. if (el.renderer) {
  46475. setup();
  46476. } else {
  46477. el.addEventListener('render-target-loaded', setup);
  46478. }
  46479. function setup () {
  46480. var gl = el.renderer.getContext();
  46481. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  46482. self.material = new THREE.RawShaderMaterial({
  46483. uniforms: {map: {type: 't', value: null}},
  46484. vertexShader: VERTEX_SHADER,
  46485. fragmentShader: FRAGMENT_SHADER,
  46486. side: THREE.DoubleSide
  46487. });
  46488. self.quad = new THREE.Mesh(
  46489. new THREE.PlaneBufferGeometry(1, 1),
  46490. self.material
  46491. );
  46492. self.quad.visible = false;
  46493. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  46494. self.canvas = document.createElement('canvas');
  46495. self.ctx = self.canvas.getContext('2d');
  46496. if (el.camera) { el.camera.add(self.quad); }
  46497. self.onKeyDown = self.onKeyDown.bind(self);
  46498. self.onCameraActive = self.onCameraActive.bind(self);
  46499. el.addEventListener('camera-set-active', self.onCameraActive);
  46500. }
  46501. },
  46502. getRenderTarget: function (width, height) {
  46503. return new THREE.WebGLRenderTarget(width, height, {
  46504. minFilter: THREE.LinearFilter,
  46505. magFilter: THREE.LinearFilter,
  46506. wrapS: THREE.ClampToEdgeWrapping,
  46507. wrapT: THREE.ClampToEdgeWrapping,
  46508. format: THREE.RGBAFormat,
  46509. type: THREE.UnsignedByteType
  46510. });
  46511. },
  46512. resize: function (width, height) {
  46513. // Resize quad.
  46514. this.quad.scale.set(width, height, 1);
  46515. // Resize camera.
  46516. this.camera.left = -1 * width / 2;
  46517. this.camera.right = width / 2;
  46518. this.camera.top = height / 2;
  46519. this.camera.bottom = -1 * height / 2;
  46520. this.camera.updateProjectionMatrix();
  46521. // Resize canvas.
  46522. this.canvas.width = width;
  46523. this.canvas.height = height;
  46524. },
  46525. play: function () {
  46526. window.addEventListener('keydown', this.onKeyDown);
  46527. },
  46528. onCameraActive: function (evt) {
  46529. var cameraParent = this.quad.parent;
  46530. if (cameraParent) { cameraParent.remove(this.quad); }
  46531. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  46532. },
  46533. /**
  46534. * <ctrl> + <alt> + s = Regular screenshot.
  46535. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  46536. */
  46537. onKeyDown: function (evt) {
  46538. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  46539. if (!this.data || !shortcutPressed) { return; }
  46540. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  46541. this.capture(projection);
  46542. },
  46543. /**
  46544. * Capture a screenshot of the scene.
  46545. *
  46546. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  46547. */
  46548. setCapture: function (projection) {
  46549. var el = this.el;
  46550. var size;
  46551. var camera;
  46552. var cubeCamera;
  46553. // Configure camera.
  46554. if (projection === 'perspective') {
  46555. // Quad is only used in equirectangular mode. Hide it in this case.
  46556. this.quad.visible = false;
  46557. // Use scene camera.
  46558. camera = el.camera;
  46559. size = {width: this.data.width, height: this.data.height};
  46560. } else {
  46561. // Use ortho camera.
  46562. camera = this.camera;
  46563. // Copy position and rotation of scene camera into the ortho one.
  46564. camera.position.copy(el.camera.getWorldPosition());
  46565. camera.rotation.copy(el.camera.getWorldRotation());
  46566. // Create cube camera and copy position from scene camera.
  46567. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  46568. Math.min(this.cubeMapSize, 2048));
  46569. cubeCamera.position.copy(el.camera.getWorldPosition());
  46570. cubeCamera.rotation.copy(el.camera.getWorldRotation());
  46571. // Render scene with cube camera.
  46572. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  46573. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  46574. size = {width: this.data.width, height: this.data.height};
  46575. // Use quad to project image taken by the cube camera.
  46576. this.quad.visible = true;
  46577. }
  46578. return {
  46579. camera: camera,
  46580. size: size,
  46581. projection: projection
  46582. };
  46583. },
  46584. /**
  46585. * Maintained for backwards compatibility.
  46586. */
  46587. capture: function (projection) {
  46588. var params = this.setCapture(projection);
  46589. this.renderCapture(params.camera, params.size, params.projection);
  46590. // Trigger file download.
  46591. this.saveCapture();
  46592. },
  46593. /**
  46594. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  46595. */
  46596. getCanvas: function (projection) {
  46597. var params = this.setCapture(projection);
  46598. this.renderCapture(params.camera, params.size, params.projection);
  46599. return this.canvas;
  46600. },
  46601. renderCapture: function (camera, size, projection) {
  46602. var autoClear = this.el.renderer.autoClear;
  46603. var el = this.el;
  46604. var imageData;
  46605. var output;
  46606. var pixels;
  46607. var renderer = this.el.renderer;
  46608. // Create rendering target and buffer to store the read pixels.
  46609. output = this.getRenderTarget(size.width, size.height);
  46610. pixels = new Uint8Array(4 * size.width * size.height);
  46611. // Resize quad, camera, and canvas.
  46612. this.resize(size.width, size.height);
  46613. // Render scene to render target.
  46614. renderer.autoClear = true;
  46615. renderer.render(el.object3D, camera, output, true);
  46616. renderer.autoClear = autoClear;
  46617. // Read image pizels back.
  46618. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  46619. if (projection === 'perspective') {
  46620. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  46621. }
  46622. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  46623. // Hide quad after projecting the image.
  46624. this.quad.visible = false;
  46625. // Copy pixels into canvas.
  46626. this.ctx.putImageData(imageData, 0, 0);
  46627. },
  46628. flipPixelsVertically: function (pixels, width, height) {
  46629. var flippedPixels = pixels.slice(0);
  46630. for (var x = 0; x < width; ++x) {
  46631. for (var y = 0; y < height; ++y) {
  46632. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  46633. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  46634. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  46635. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  46636. }
  46637. }
  46638. return flippedPixels;
  46639. },
  46640. /**
  46641. * Download capture to file.
  46642. */
  46643. saveCapture: function () {
  46644. this.canvas.toBlob(function (blob) {
  46645. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  46646. var linkEl = document.createElement('a');
  46647. var url = URL.createObjectURL(blob);
  46648. linkEl.href = url;
  46649. linkEl.setAttribute('download', fileName);
  46650. linkEl.innerHTML = 'downloading...';
  46651. linkEl.style.display = 'none';
  46652. document.body.appendChild(linkEl);
  46653. setTimeout(function () {
  46654. linkEl.click();
  46655. document.body.removeChild(linkEl);
  46656. }, 1);
  46657. }, 'image/png');
  46658. }
  46659. });
  46660. },{"../../core/component":125,"../../lib/three":173}],105:[function(_dereq_,module,exports){
  46661. var registerComponent = _dereq_('../../core/component').registerComponent;
  46662. var RStats = _dereq_('../../../vendor/rStats');
  46663. var utils = _dereq_('../../utils');
  46664. _dereq_('../../../vendor/rStats.extras');
  46665. _dereq_('../../lib/rStatsAframe');
  46666. var AFrameStats = window.aframeStats;
  46667. var bind = utils.bind;
  46668. var HIDDEN_CLASS = 'a-hidden';
  46669. var ThreeStats = window.threeStats;
  46670. /**
  46671. * Stats appended to document.body by RStats.
  46672. */
  46673. module.exports.Component = registerComponent('stats', {
  46674. schema: {default: true},
  46675. init: function () {
  46676. var scene = this.el;
  46677. if (utils.getUrlParameter('stats') === 'false') { return; }
  46678. this.stats = createStats(scene);
  46679. this.statsEl = document.querySelector('.rs-base');
  46680. this.hideBound = bind(this.hide, this);
  46681. this.showBound = bind(this.show, this);
  46682. scene.addEventListener('enter-vr', this.hideBound);
  46683. scene.addEventListener('exit-vr', this.showBound);
  46684. },
  46685. update: function () {
  46686. if (!this.stats) { return; }
  46687. return (!this.data) ? this.hide() : this.show();
  46688. },
  46689. remove: function () {
  46690. this.el.removeEventListener('enter-vr', this.hideBound);
  46691. this.el.removeEventListener('exit-vr', this.showBound);
  46692. if (!this.statsEl) { return; } // Scene detached.
  46693. this.statsEl.parentNode.removeChild(this.statsEl);
  46694. },
  46695. tick: function () {
  46696. var stats = this.stats;
  46697. if (!stats) { return; }
  46698. stats('rAF').tick();
  46699. stats('FPS').frame();
  46700. stats().update();
  46701. },
  46702. hide: function () {
  46703. this.statsEl.classList.add(HIDDEN_CLASS);
  46704. },
  46705. show: function () {
  46706. this.statsEl.classList.remove(HIDDEN_CLASS);
  46707. }
  46708. });
  46709. function createStats (scene) {
  46710. var threeStats = new ThreeStats(scene.renderer);
  46711. var aframeStats = new AFrameStats(scene);
  46712. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46713. return new RStats({
  46714. css: [], // Our stylesheet is injected from `src/index.js`.
  46715. values: {
  46716. fps: {caption: 'fps', below: 30}
  46717. },
  46718. groups: [
  46719. {caption: 'Framerate', values: ['fps', 'raf']}
  46720. ],
  46721. plugins: plugins
  46722. });
  46723. }
  46724. },{"../../../vendor/rStats":204,"../../../vendor/rStats.extras":203,"../../core/component":125,"../../lib/rStatsAframe":172,"../../utils":195}],106:[function(_dereq_,module,exports){
  46725. var registerComponent = _dereq_('../../core/component').registerComponent;
  46726. var constants = _dereq_('../../constants/');
  46727. var utils = _dereq_('../../utils/');
  46728. var bind = utils.bind;
  46729. var ENTER_VR_CLASS = 'a-enter-vr';
  46730. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46731. var HIDDEN_CLASS = 'a-hidden';
  46732. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46733. /**
  46734. * UI for entering VR mode.
  46735. */
  46736. module.exports.Component = registerComponent('vr-mode-ui', {
  46737. dependencies: ['canvas'],
  46738. schema: {
  46739. enabled: {default: true}
  46740. },
  46741. init: function () {
  46742. var self = this;
  46743. var sceneEl = this.el;
  46744. if (utils.getUrlParameter('ui') === 'false') { return; }
  46745. this.enterVR = bind(sceneEl.enterVR, sceneEl);
  46746. this.exitVR = bind(sceneEl.exitVR, sceneEl);
  46747. this.insideLoader = false;
  46748. this.enterVREl = null;
  46749. this.orientationModalEl = null;
  46750. // Hide/show VR UI when entering/exiting VR mode.
  46751. sceneEl.addEventListener('enter-vr', bind(this.updateEnterVRInterface, this));
  46752. sceneEl.addEventListener('exit-vr', bind(this.updateEnterVRInterface, this));
  46753. window.addEventListener('message', function (event) {
  46754. if (event.data.type === 'loaderReady') {
  46755. self.insideLoader = true;
  46756. self.remove();
  46757. }
  46758. });
  46759. // Modal that tells the user to change orientation if in portrait.
  46760. window.addEventListener('orientationchange',
  46761. bind(this.toggleOrientationModalIfNeeded, this));
  46762. },
  46763. update: function () {
  46764. var sceneEl = this.el;
  46765. if (!this.data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46766. return this.remove();
  46767. }
  46768. if (this.enterVREl || this.orientationModalEl) { return; }
  46769. // Add UI if enabled and not already present.
  46770. this.enterVREl = createEnterVRButton(this.enterVR);
  46771. sceneEl.appendChild(this.enterVREl);
  46772. this.orientationModalEl = createOrientationModal(this.exitVR);
  46773. sceneEl.appendChild(this.orientationModalEl);
  46774. this.updateEnterVRInterface();
  46775. },
  46776. remove: function () {
  46777. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46778. if (uiElement) {
  46779. uiElement.parentNode.removeChild(uiElement);
  46780. }
  46781. });
  46782. },
  46783. updateEnterVRInterface: function () {
  46784. this.toggleEnterVRButtonIfNeeded();
  46785. this.toggleOrientationModalIfNeeded();
  46786. },
  46787. toggleEnterVRButtonIfNeeded: function () {
  46788. var sceneEl = this.el;
  46789. if (!this.enterVREl) { return; }
  46790. if (sceneEl.is('vr-mode')) {
  46791. this.enterVREl.classList.add(HIDDEN_CLASS);
  46792. } else {
  46793. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46794. }
  46795. },
  46796. toggleOrientationModalIfNeeded: function () {
  46797. var sceneEl = this.el;
  46798. var orientationModalEl = this.orientationModalEl;
  46799. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46800. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46801. // Show if in VR mode on portrait.
  46802. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46803. } else {
  46804. orientationModalEl.classList.add(HIDDEN_CLASS);
  46805. }
  46806. }
  46807. });
  46808. /**
  46809. * Creates a button that when clicked will enter into stereo-rendering mode for VR.
  46810. *
  46811. * Structure: <div><button></div>
  46812. *
  46813. * @param {function} enterVRHandler
  46814. * @returns {Element} Wrapper <div>.
  46815. */
  46816. function createEnterVRButton (enterVRHandler) {
  46817. var vrButton;
  46818. var wrapper;
  46819. // Create elements.
  46820. wrapper = document.createElement('div');
  46821. wrapper.classList.add(ENTER_VR_CLASS);
  46822. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46823. vrButton = document.createElement('button');
  46824. vrButton.className = ENTER_VR_BTN_CLASS;
  46825. vrButton.setAttribute('title', 'Enter VR mode with a headset or fullscreen mode on a desktop. Visit https://webvr.rocks or https://webvr.info for more information.');
  46826. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46827. // Insert elements.
  46828. wrapper.appendChild(vrButton);
  46829. vrButton.addEventListener('click', function (evt) {
  46830. enterVRHandler();
  46831. });
  46832. return wrapper;
  46833. }
  46834. /**
  46835. * Create a modal that tells mobile users to orient the phone to landscape.
  46836. * Add a close button that if clicked, exits VR and closes the modal.
  46837. */
  46838. function createOrientationModal (exitVRHandler) {
  46839. var modal = document.createElement('div');
  46840. modal.className = ORIENTATION_MODAL_CLASS;
  46841. modal.classList.add(HIDDEN_CLASS);
  46842. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46843. var exit = document.createElement('button');
  46844. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46845. exit.innerHTML = 'Exit VR';
  46846. // Exit VR on close.
  46847. exit.addEventListener('click', exitVRHandler);
  46848. modal.appendChild(exit);
  46849. return modal;
  46850. }
  46851. },{"../../constants/":116,"../../core/component":125,"../../utils/":195}],107:[function(_dereq_,module,exports){
  46852. var component = _dereq_('../core/component');
  46853. var THREE = _dereq_('../lib/three');
  46854. var bind = _dereq_('../utils/bind');
  46855. var registerComponent = component.registerComponent;
  46856. /**
  46857. * Shadow component.
  46858. *
  46859. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46860. * shadows as specified by the `cast` and `receive` properties.
  46861. */
  46862. module.exports.Component = registerComponent('shadow', {
  46863. schema: {
  46864. cast: {default: true},
  46865. receive: {default: true}
  46866. },
  46867. init: function () {
  46868. this.onMeshChanged = bind(this.update, this);
  46869. this.el.addEventListener('object3dset', this.onMeshChanged);
  46870. this.system.setShadowMapEnabled(true);
  46871. },
  46872. update: function () {
  46873. var data = this.data;
  46874. this.updateDescendants(data.cast, data.receive);
  46875. },
  46876. remove: function () {
  46877. var el = this.el;
  46878. el.removeEventListener('object3dset', this.onMeshChanged);
  46879. this.updateDescendants(false, false);
  46880. },
  46881. updateDescendants: function (cast, receive) {
  46882. var sceneEl = this.el.sceneEl;
  46883. this.el.object3D.traverse(function (node) {
  46884. if (!(node instanceof THREE.Mesh)) { return; }
  46885. node.castShadow = cast;
  46886. node.receiveShadow = receive;
  46887. // If scene has already rendered, materials must be updated.
  46888. if (sceneEl.hasLoaded && node.material) {
  46889. var materials = node.material.materials || [node.material];
  46890. for (var i = 0; i < materials.length; i++) {
  46891. materials[i].needsUpdate = true;
  46892. }
  46893. }
  46894. });
  46895. }
  46896. });
  46897. },{"../core/component":125,"../lib/three":173,"../utils/bind":189}],108:[function(_dereq_,module,exports){
  46898. var registerComponent = _dereq_('../core/component').registerComponent;
  46899. var debug = _dereq_('../utils/debug');
  46900. var bind = _dereq_('../utils/bind');
  46901. var THREE = _dereq_('../lib/three');
  46902. var warn = debug('components:sound:warn');
  46903. /**
  46904. * Sound component.
  46905. */
  46906. module.exports.Component = registerComponent('sound', {
  46907. schema: {
  46908. autoplay: {default: false},
  46909. distanceModel: {default: 'inverse',
  46910. oneOf: ['linear', 'inverse', 'exponential']},
  46911. loop: {default: false},
  46912. maxDistance: {default: 10000},
  46913. on: {default: ''},
  46914. poolSize: {default: 1},
  46915. positional: {default: true},
  46916. refDistance: {default: 1},
  46917. rolloffFactor: {default: 1},
  46918. src: {type: 'audio'},
  46919. volume: {default: 1}
  46920. },
  46921. multiple: true,
  46922. init: function () {
  46923. this.listener = null;
  46924. this.audioLoader = new THREE.AudioLoader();
  46925. this.pool = new THREE.Group();
  46926. this.loaded = false;
  46927. this.mustPlay = false;
  46928. this.playSound = bind(this.playSound, this);
  46929. },
  46930. update: function (oldData) {
  46931. var data = this.data;
  46932. var srcChanged = data.src !== oldData.src;
  46933. // Create new sound if not yet created or changing `src`.
  46934. if (srcChanged) {
  46935. if (!data.src) {
  46936. warn('Audio source was not specified with `src`');
  46937. return;
  46938. }
  46939. this.setupSound();
  46940. }
  46941. this.pool.children.forEach(function (sound) {
  46942. if (data.positional) {
  46943. sound.setDistanceModel(data.distanceModel);
  46944. sound.setMaxDistance(data.maxDistance);
  46945. sound.setRefDistance(data.refDistance);
  46946. sound.setRolloffFactor(data.rolloffFactor);
  46947. }
  46948. sound.setLoop(data.loop);
  46949. sound.setVolume(data.volume);
  46950. sound.isPaused = false;
  46951. });
  46952. if (data.on !== oldData.on) {
  46953. this.updateEventListener(oldData.on);
  46954. }
  46955. // All sound values set. Load in `src`.
  46956. if (srcChanged) {
  46957. var self = this;
  46958. this.loaded = false;
  46959. this.audioLoader.load(data.src, function (buffer) {
  46960. self.pool.children.forEach(function (sound) {
  46961. sound.setBuffer(buffer);
  46962. });
  46963. self.loaded = true;
  46964. // Remove this key from cache, otherwise we can't play it again
  46965. THREE.Cache.remove(data.src);
  46966. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46967. self.el.emit('sound-loaded');
  46968. });
  46969. }
  46970. },
  46971. pause: function () {
  46972. this.stopSound();
  46973. this.removeEventListener();
  46974. },
  46975. play: function () {
  46976. if (this.data.autoplay) { this.playSound(); }
  46977. this.updateEventListener();
  46978. },
  46979. remove: function () {
  46980. this.removeEventListener();
  46981. this.el.removeObject3D(this.attrName);
  46982. try {
  46983. this.pool.children.forEach(function (sound) {
  46984. sound.disconnect();
  46985. });
  46986. } catch (e) {
  46987. // disconnect() will throw if it was never connected initially.
  46988. warn('Audio source not properly disconnected');
  46989. }
  46990. },
  46991. /**
  46992. * Update listener attached to the user defined on event.
  46993. */
  46994. updateEventListener: function (oldEvt) {
  46995. var el = this.el;
  46996. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  46997. el.addEventListener(this.data.on, this.playSound);
  46998. },
  46999. removeEventListener: function () {
  47000. this.el.removeEventListener(this.data.on, this.playSound);
  47001. },
  47002. /**
  47003. * Removes current sound object, creates new sound object, adds to entity.
  47004. *
  47005. * @returns {object} sound
  47006. */
  47007. setupSound: function () {
  47008. var el = this.el;
  47009. var sceneEl = el.sceneEl;
  47010. if (this.pool.children.length > 0) {
  47011. this.stopSound();
  47012. el.removeObject3D('sound');
  47013. }
  47014. // Only want one AudioListener. Cache it on the scene.
  47015. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  47016. sceneEl.audioListener = listener;
  47017. if (sceneEl.camera) {
  47018. sceneEl.camera.add(listener);
  47019. }
  47020. // Wait for camera if necessary.
  47021. sceneEl.addEventListener('camera-set-active', function (evt) {
  47022. evt.detail.cameraEl.getObject3D('camera').add(listener);
  47023. });
  47024. // Create [poolSize] audio instances and attach them to pool
  47025. this.pool = new THREE.Group();
  47026. for (var i = 0; i < this.data.poolSize; i++) {
  47027. var sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener);
  47028. this.pool.add(sound);
  47029. }
  47030. el.setObject3D(this.attrName, this.pool);
  47031. this.pool.children.forEach(function (sound) {
  47032. sound.onEnded = function () {
  47033. sound.isPlaying = false;
  47034. el.emit('sound-ended', {index: i});
  47035. };
  47036. });
  47037. },
  47038. /**
  47039. * Pause all the sounds in the pool.
  47040. */
  47041. pauseSound: function () {
  47042. this.isPlaying = false;
  47043. this.pool.children.forEach(function (sound) {
  47044. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { return; }
  47045. sound.isPaused = true;
  47046. sound.pause();
  47047. });
  47048. },
  47049. /**
  47050. * Look for an unused sound in the pool and play it if found.
  47051. */
  47052. playSound: function () {
  47053. if (!this.loaded) {
  47054. warn('Sound not loaded yet. It will be played once it finished loading');
  47055. this.mustPlay = true;
  47056. return;
  47057. }
  47058. var found = false;
  47059. this.isPlaying = true;
  47060. this.pool.children.forEach(function (sound) {
  47061. if (!sound.isPlaying && sound.buffer && !found) {
  47062. sound.play();
  47063. sound.isPaused = false;
  47064. found = true;
  47065. return;
  47066. }
  47067. });
  47068. if (!found) {
  47069. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  47070. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  47071. return;
  47072. }
  47073. this.mustPlay = false;
  47074. },
  47075. /**
  47076. * Stop all the sounds in the pool.
  47077. */
  47078. stopSound: function () {
  47079. this.isPlaying = false;
  47080. this.pool.children.forEach(function (sound) {
  47081. if (!sound.source || !sound.source.buffer) { return; }
  47082. sound.stop();
  47083. });
  47084. }
  47085. });
  47086. },{"../core/component":125,"../lib/three":173,"../utils/bind":189,"../utils/debug":191}],109:[function(_dereq_,module,exports){
  47087. var createTextGeometry = _dereq_('three-bmfont-text');
  47088. var loadBMFont = _dereq_('load-bmfont');
  47089. var registerComponent = _dereq_('../core/component').registerComponent;
  47090. var coreShader = _dereq_('../core/shader');
  47091. var THREE = _dereq_('../lib/three');
  47092. var utils = _dereq_('../utils/');
  47093. var error = utils.debug('components:text:error');
  47094. var shaders = coreShader.shaders;
  47095. var warn = utils.debug('components:text:warn');
  47096. // 1 to match other A-Frame default widths.
  47097. var DEFAULT_WIDTH = 1;
  47098. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  47099. var MAX_ANISOTROPY = 16;
  47100. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  47101. var FONTS = {
  47102. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  47103. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  47104. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  47105. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  47106. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  47107. monoid: FONT_BASE_URL + 'Monoid.fnt',
  47108. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  47109. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  47110. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  47111. };
  47112. var MSDF_FONTS = ['roboto'];
  47113. var DEFAULT_FONT = 'roboto';
  47114. module.exports.FONTS = FONTS;
  47115. var cache = new PromiseCache();
  47116. var fontWidthFactors = {};
  47117. var textures = {};
  47118. /**
  47119. * SDF-based text component.
  47120. * Based on https://github.com/Jam3/three-bmfont-text.
  47121. *
  47122. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  47123. * original `sdf` shader.
  47124. */
  47125. module.exports.Component = registerComponent('text', {
  47126. multiple: true,
  47127. schema: {
  47128. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  47129. alphaTest: {default: 0.5},
  47130. // `anchor` defaults to center to match geometries.
  47131. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  47132. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  47133. color: {type: 'color', default: '#FFF'},
  47134. font: {type: 'string', default: DEFAULT_FONT},
  47135. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  47136. fontImage: {type: 'string'},
  47137. // `height` has no default, will be populated at layout.
  47138. height: {type: 'number'},
  47139. letterSpacing: {type: 'number', default: 0},
  47140. // `lineHeight` defaults to font's `lineHeight` value.
  47141. lineHeight: {type: 'number'},
  47142. opacity: {type: 'number', default: 1.0},
  47143. shader: {default: 'sdf', oneOf: shaders},
  47144. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  47145. tabSize: {default: 4},
  47146. transparent: {default: true},
  47147. value: {type: 'string'},
  47148. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  47149. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  47150. width: {type: 'number'},
  47151. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  47152. wrapCount: {type: 'number', default: 40},
  47153. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  47154. wrapPixels: {type: 'number'},
  47155. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  47156. yOffset: {type: 'number', default: 0},
  47157. // `zOffset` will provide a small z offset to avoid z-fighting.
  47158. zOffset: {type: 'number', default: 0.001}
  47159. },
  47160. init: function () {
  47161. this.geometry = createTextGeometry();
  47162. this.createOrUpdateMaterial();
  47163. this.mesh = new THREE.Mesh(this.geometry, this.material);
  47164. this.el.setObject3D(this.attrName, this.mesh);
  47165. },
  47166. update: function (oldData) {
  47167. var data = coerceData(this.data);
  47168. var font = this.currentFont;
  47169. var fontImage = this.getFontImageSrc();
  47170. if (textures[fontImage]) {
  47171. this.texture = textures[fontImage];
  47172. } else {
  47173. // Create texture per font.
  47174. this.texture = textures[fontImage] = new THREE.Texture();
  47175. this.texture.anisotropy = MAX_ANISOTROPY;
  47176. }
  47177. // Update material.
  47178. this.createOrUpdateMaterial();
  47179. // New font. `updateFont` will later change data and layout.
  47180. if (oldData.font !== data.font) {
  47181. this.updateFont();
  47182. return;
  47183. }
  47184. // Update geometry and layout.
  47185. if (font) {
  47186. this.updateGeometry(this.geometry, data, font);
  47187. this.updateLayout(data);
  47188. }
  47189. },
  47190. /**
  47191. * Clean up geometry, material, texture, mesh, objects.
  47192. */
  47193. remove: function () {
  47194. this.geometry.dispose();
  47195. this.geometry = null;
  47196. this.el.removeObject3D(this.attrName);
  47197. this.material.dispose();
  47198. this.material = null;
  47199. this.texture.dispose();
  47200. this.texture = null;
  47201. if (this.shaderObject) {
  47202. delete this.shaderObject;
  47203. }
  47204. },
  47205. /**
  47206. * Update the shader of the material.
  47207. */
  47208. createOrUpdateMaterial: function () {
  47209. var data = this.data;
  47210. var hasChangedShader;
  47211. var material = this.material;
  47212. var NewShader;
  47213. var shaderData;
  47214. var shaderName;
  47215. // Infer shader if using a stock font (or from `-msdf` filename convention).
  47216. shaderName = data.shader;
  47217. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  47218. shaderName = 'msdf';
  47219. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  47220. shaderName = 'sdf';
  47221. }
  47222. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  47223. shaderData = {
  47224. alphaTest: data.alphaTest,
  47225. color: data.color,
  47226. map: this.texture,
  47227. opacity: data.opacity,
  47228. side: parseSide(data.side),
  47229. transparent: data.transparent
  47230. };
  47231. // Shader has not changed, do an update.
  47232. if (!hasChangedShader) {
  47233. // Update shader material.
  47234. this.shaderObject.update(shaderData);
  47235. // Apparently, was not set on `init` nor `update`.
  47236. material.transparent = shaderData.transparent;
  47237. updateBaseMaterial(material, shaderData);
  47238. return;
  47239. }
  47240. // Shader has changed. Create a shader material.
  47241. NewShader = createShader(this.el, shaderName, shaderData);
  47242. this.material = NewShader.material;
  47243. this.shaderObject = NewShader.shader;
  47244. // Set new shader material.
  47245. updateBaseMaterial(this.material, shaderData);
  47246. if (this.mesh) { this.mesh.material = this.material; }
  47247. },
  47248. /**
  47249. * Load font for geometry, load font image for material, and apply.
  47250. */
  47251. updateFont: function () {
  47252. var data = this.data;
  47253. var el = this.el;
  47254. var fontSrc;
  47255. var geometry = this.geometry;
  47256. var self = this;
  47257. if (!data.font) { warn('No font specified. Using the default font.'); }
  47258. // Make invisible during font swap.
  47259. this.mesh.visible = false;
  47260. // Look up font URL to use, and perform cached load.
  47261. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  47262. cache.get(fontSrc, function doLoadFont () {
  47263. return loadFont(fontSrc, data.yOffset);
  47264. }).then(function setFont (font) {
  47265. var coercedData;
  47266. var fontImgSrc;
  47267. if (font.pages.length !== 1) {
  47268. throw new Error('Currently only single-page bitmap fonts are supported.');
  47269. }
  47270. if (!fontWidthFactors[fontSrc]) {
  47271. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  47272. }
  47273. // Update geometry given font metrics.
  47274. coercedData = coerceData(data);
  47275. self.updateGeometry(geometry, self.data, font);
  47276. // Set font and update layout.
  47277. self.currentFont = font;
  47278. self.updateLayout(coercedData);
  47279. // Look up font image URL to use, and perform cached load.
  47280. fontImgSrc = self.getFontImageSrc();
  47281. cache.get(fontImgSrc, function () {
  47282. return loadTexture(fontImgSrc);
  47283. }).then(function (image) {
  47284. // Make mesh visible and apply font image as texture.
  47285. var texture = self.texture;
  47286. texture.image = image;
  47287. texture.needsUpdate = true;
  47288. textures[fontImgSrc] = texture;
  47289. self.texture = texture;
  47290. self.mesh.visible = true;
  47291. el.emit('textfontset', {font: data.font, fontObj: font});
  47292. }).catch(function (err) {
  47293. error(err);
  47294. throw err;
  47295. });
  47296. }).catch(function (err) {
  47297. error(err);
  47298. throw err;
  47299. });
  47300. },
  47301. getFontImageSrc: function () {
  47302. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  47303. return this.data.fontImage || fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  47304. },
  47305. /**
  47306. * Update layout with anchor, alignment, baseline, and considering any meshes.
  47307. */
  47308. updateLayout: function (data) {
  47309. var anchor;
  47310. var baseline;
  47311. var el = this.el;
  47312. var geometry = this.geometry;
  47313. var geometryComponent = el.getAttribute('geometry');
  47314. var height;
  47315. var layout = geometry.layout;
  47316. var mesh = this.mesh;
  47317. var textRenderWidth;
  47318. var textScale;
  47319. var width;
  47320. var x;
  47321. var y;
  47322. // Determine width to use (defined width, geometry's width, or default width).
  47323. geometryComponent = el.getAttribute('geometry');
  47324. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  47325. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  47326. // Note that experimental factor will never be correct for variable width fonts.
  47327. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  47328. this.currentFont.widthFactor);
  47329. textScale = width / textRenderWidth;
  47330. // Determine height to use.
  47331. height = textScale * (layout.height + layout.descender);
  47332. // Update geometry dimensions to match text layout if width and height are set to 0.
  47333. // For example, scales a plane to fit text.
  47334. if (geometryComponent) {
  47335. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  47336. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  47337. }
  47338. // Calculate X position to anchor text left, center, or right.
  47339. anchor = data.anchor === 'align' ? data.align : data.anchor;
  47340. if (anchor === 'left') {
  47341. x = 0;
  47342. } else if (anchor === 'right') {
  47343. x = -1 * layout.width;
  47344. } else if (anchor === 'center') {
  47345. x = -1 * layout.width / 2;
  47346. } else {
  47347. throw new TypeError('Invalid text.anchor property value', anchor);
  47348. }
  47349. // Calculate Y position to anchor text top, center, or bottom.
  47350. baseline = data.baseline;
  47351. if (baseline === 'bottom') {
  47352. y = 0;
  47353. } else if (baseline === 'top') {
  47354. y = -1 * layout.height + layout.ascender;
  47355. } else if (baseline === 'center') {
  47356. y = -1 * layout.height / 2;
  47357. } else {
  47358. throw new TypeError('Invalid text.baseline property value', baseline);
  47359. }
  47360. // Position and scale mesh to apply layout.
  47361. mesh.position.x = x * textScale;
  47362. mesh.position.y = y * textScale;
  47363. // Place text slightly in front to avoid Z-fighting.
  47364. mesh.position.z = data.zOffset;
  47365. mesh.scale.set(textScale, -1 * textScale, textScale);
  47366. this.geometry.computeBoundingSphere();
  47367. },
  47368. /**
  47369. * Grab font from the constant.
  47370. * Set as a method for test stubbing purposes.
  47371. */
  47372. lookupFont: function (key) {
  47373. return FONTS[key];
  47374. },
  47375. /**
  47376. * Update the text geometry using `three-bmfont-text.update`.
  47377. */
  47378. updateGeometry: function (geometry, data, font) {
  47379. geometry.update(utils.extend({}, data, {
  47380. font: font,
  47381. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  47382. text: data.value.toString().replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  47383. lineHeight: data.lineHeight || font.common.lineHeight
  47384. }));
  47385. }
  47386. });
  47387. function parseSide (side) {
  47388. switch (side) {
  47389. case 'back': {
  47390. return THREE.BackSide;
  47391. }
  47392. case 'double': {
  47393. return THREE.DoubleSide;
  47394. }
  47395. default: {
  47396. return THREE.FrontSide;
  47397. }
  47398. }
  47399. }
  47400. /**
  47401. * Coerce some data to numbers.
  47402. * as they will be passed directly into text creation and update
  47403. */
  47404. function coerceData (data) {
  47405. data = utils.clone(data);
  47406. if (data.lineHeight !== undefined) {
  47407. data.lineHeight = parseFloat(data.lineHeight);
  47408. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  47409. }
  47410. if (data.width !== undefined) {
  47411. data.width = parseFloat(data.width);
  47412. if (!isFinite(data.width)) { data.width = undefined; }
  47413. }
  47414. return data;
  47415. }
  47416. /**
  47417. * @returns {Promise}
  47418. */
  47419. function loadFont (src, yOffset) {
  47420. return new Promise(function (resolve, reject) {
  47421. loadBMFont(src, function (err, font) {
  47422. if (err) {
  47423. error('Error loading font', src);
  47424. reject(err);
  47425. return;
  47426. }
  47427. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  47428. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  47429. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  47430. resolve(font);
  47431. });
  47432. });
  47433. }
  47434. /**
  47435. * @returns {Promise}
  47436. */
  47437. function loadTexture (src) {
  47438. return new Promise(function (resolve, reject) {
  47439. new THREE.ImageLoader().load(src, function (image) {
  47440. resolve(image);
  47441. }, undefined, function () {
  47442. error('Error loading font image', src);
  47443. reject(null);
  47444. });
  47445. });
  47446. }
  47447. function createShader (el, shaderName, data) {
  47448. var shader;
  47449. var shaderObject;
  47450. // Set up Shader.
  47451. shaderObject = new shaders[shaderName].Shader();
  47452. shaderObject.el = el;
  47453. shaderObject.init(data);
  47454. shaderObject.update(data);
  47455. // Get material.
  47456. shader = shaderObject.material;
  47457. // Apparently, was not set on `init` nor `update`.
  47458. shader.transparent = data.transparent;
  47459. return {
  47460. material: shader,
  47461. shader: shaderObject
  47462. };
  47463. }
  47464. /**
  47465. * @todo Add more supported material properties (e.g., `visible`).
  47466. */
  47467. function updateBaseMaterial (material, data) {
  47468. material.side = data.side;
  47469. }
  47470. /**
  47471. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  47472. * Note that experimental factor will never be correct for variable width fonts.
  47473. */
  47474. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  47475. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  47476. }
  47477. /**
  47478. * Compute default font width factor to use.
  47479. */
  47480. function computeFontWidthFactor (font) {
  47481. var sum = 0;
  47482. var digitsum = 0;
  47483. var digits = 0;
  47484. font.chars.map(function (ch) {
  47485. sum += ch.xadvance;
  47486. if (ch.id >= 48 && ch.id <= 57) {
  47487. digits++;
  47488. digitsum += ch.xadvance;
  47489. }
  47490. });
  47491. return digits ? digitsum / digits : sum / font.chars.length;
  47492. }
  47493. /**
  47494. * Get or create a promise given a key and promise generator.
  47495. * @todo Move to a utility and use in other parts of A-Frame.
  47496. */
  47497. function PromiseCache () {
  47498. var cache = this.cache = {};
  47499. this.get = function (key, promiseGenerator) {
  47500. if (key in cache) {
  47501. return cache[key];
  47502. }
  47503. cache[key] = promiseGenerator();
  47504. return cache[key];
  47505. };
  47506. }
  47507. },{"../core/component":125,"../core/shader":134,"../lib/three":173,"../utils/":195,"load-bmfont":24,"three-bmfont-text":37}],110:[function(_dereq_,module,exports){
  47508. var registerComponent = _dereq_('../core/component').registerComponent;
  47509. var controllerUtils = _dereq_('../utils/tracked-controls');
  47510. var THREE = _dereq_('../lib/three');
  47511. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  47512. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  47513. // Vector from eyes to elbow (divided by user height).
  47514. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  47515. // Vector from eyes to elbow (divided by user height).
  47516. var FOREARM = {x: 0, y: 0, z: -0.175};
  47517. /**
  47518. * Tracked controls component.
  47519. * Wrap the gamepad API for pose and button states.
  47520. * Select the appropriate controller and apply pose to the entity.
  47521. * Observe button states and emit appropriate events.
  47522. *
  47523. * @property {number} controller - Index of controller in array returned by Gamepad API. Only used if hand property is not set.
  47524. * @property {string} id - Selected controller among those returned by Gamepad API.
  47525. * @property {number} hand - If multiple controllers found with id, choose the one with the given value for hand. If set, we ignore 'controller' property
  47526. */
  47527. module.exports.Component = registerComponent('tracked-controls', {
  47528. schema: {
  47529. controller: {default: 0},
  47530. id: {type: 'string', default: ''},
  47531. hand: {type: 'string', default: ''},
  47532. idPrefix: {type: 'string', default: ''},
  47533. rotationOffset: {default: 0},
  47534. // Arm model parameters when not 6DoF.
  47535. armModel: {default: true},
  47536. headElement: {type: 'selector'}
  47537. },
  47538. init: function () {
  47539. this.axis = [0, 0, 0];
  47540. this.buttonStates = {};
  47541. this.targetControllerNumber = this.data.controller;
  47542. this.dolly = new THREE.Object3D();
  47543. this.controllerEuler = new THREE.Euler();
  47544. this.controllerEuler.order = 'YXZ';
  47545. this.controllerPosition = new THREE.Vector3();
  47546. this.controllerQuaternion = new THREE.Quaternion();
  47547. this.deltaControllerPosition = new THREE.Vector3();
  47548. this.position = new THREE.Vector3();
  47549. this.rotation = {};
  47550. this.standingMatrix = new THREE.Matrix4();
  47551. this.previousControllerPosition = new THREE.Vector3();
  47552. this.updateGamepad();
  47553. },
  47554. tick: function (time, delta) {
  47555. var mesh = this.el.getObject3D('mesh');
  47556. // Update mesh animations.
  47557. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  47558. this.updateGamepad();
  47559. this.updatePose();
  47560. this.updateButtons();
  47561. },
  47562. /**
  47563. * Return default user height to use for non-6DOF arm model.
  47564. */
  47565. defaultUserHeight: function () {
  47566. return DEFAULT_CAMERA_HEIGHT;
  47567. },
  47568. /**
  47569. * Return head element to use for non-6DOF arm model.
  47570. */
  47571. getHeadElement: function () {
  47572. return this.data.headElement || this.el.sceneEl.camera.el;
  47573. },
  47574. /**
  47575. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  47576. */
  47577. updateGamepad: function () {
  47578. var data = this.data;
  47579. var controller = controllerUtils.findMatchingController(
  47580. this.system.controllers,
  47581. data.id,
  47582. data.idPrefix,
  47583. data.hand,
  47584. data.controller
  47585. );
  47586. this.controller = controller;
  47587. },
  47588. applyArmModel: function (controllerPosition) {
  47589. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  47590. var controller = this.controller;
  47591. var controllerEuler = this.controllerEuler;
  47592. var controllerQuaternion = this.controllerQuaternion;
  47593. var deltaControllerPosition = this.deltaControllerPosition;
  47594. var hand;
  47595. var headCamera;
  47596. var headEl;
  47597. var headObject3D;
  47598. var pose;
  47599. var userHeight;
  47600. headEl = this.getHeadElement();
  47601. headObject3D = headEl.object3D;
  47602. headCamera = headEl.components.camera;
  47603. userHeight = (headCamera ? headCamera.data.userHeight : 0) || this.defaultUserHeight();
  47604. pose = controller.pose;
  47605. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  47606. // Use camera position as head position.
  47607. controllerPosition.copy(headObject3D.position);
  47608. // Set offset for degenerate "arm model" to elbow.
  47609. deltaControllerPosition.set(
  47610. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  47611. EYES_TO_ELBOW.y, // Lower than our eyes.
  47612. EYES_TO_ELBOW.z); // Slightly out in front.
  47613. // Scale offset by user height.
  47614. deltaControllerPosition.multiplyScalar(userHeight);
  47615. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  47616. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  47617. // Apply rotated offset to position.
  47618. controllerPosition.add(deltaControllerPosition);
  47619. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  47620. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  47621. // Scale offset by user height.
  47622. deltaControllerPosition.multiplyScalar(userHeight);
  47623. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  47624. if (pose.orientation) {
  47625. controllerQuaternion.fromArray(pose.orientation);
  47626. } else {
  47627. controllerQuaternion.copy(headObject3D.quaternion);
  47628. }
  47629. controllerEuler.setFromQuaternion(controllerQuaternion);
  47630. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  47631. deltaControllerPosition.applyEuler(controllerEuler);
  47632. // Apply rotated offset to position.
  47633. controllerPosition.add(deltaControllerPosition);
  47634. },
  47635. /**
  47636. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  47637. */
  47638. updatePose: function () {
  47639. var controller = this.controller;
  47640. var controllerEuler = this.controllerEuler;
  47641. var controllerPosition = this.controllerPosition;
  47642. var elPosition;
  47643. var previousControllerPosition = this.previousControllerPosition;
  47644. var dolly = this.dolly;
  47645. var el = this.el;
  47646. var pose;
  47647. var standingMatrix = this.standingMatrix;
  47648. var vrDisplay = this.system.vrDisplay;
  47649. var headEl = this.getHeadElement();
  47650. var headCamera = headEl.components.camera;
  47651. var userHeight = (headCamera ? headCamera.data.userHeight : 0) || this.defaultUserHeight();
  47652. if (!controller) { return; }
  47653. // Compose pose from Gamepad.
  47654. pose = controller.pose;
  47655. if (pose.orientation !== null) {
  47656. dolly.quaternion.fromArray(pose.orientation);
  47657. }
  47658. // controller position or arm model
  47659. if (pose.position !== null) {
  47660. dolly.position.fromArray(pose.position);
  47661. } else {
  47662. // Controller not 6DOF, apply arm model.
  47663. if (this.data.armModel) { this.applyArmModel(dolly.position); }
  47664. }
  47665. // Apply transforms, if 6DOF and in VR.
  47666. if (pose.position != null && vrDisplay) {
  47667. if (vrDisplay.stageParameters) {
  47668. standingMatrix.fromArray(vrDisplay.stageParameters.sittingToStandingTransform);
  47669. dolly.matrix.compose(dolly.position, dolly.quaternion, dolly.scale);
  47670. dolly.matrix.multiplyMatrices(standingMatrix, dolly.matrix);
  47671. } else {
  47672. // Apply default camera height
  47673. dolly.position.y += userHeight;
  47674. dolly.matrix.compose(dolly.position, dolly.quaternion, dolly.scale);
  47675. }
  47676. } else {
  47677. dolly.matrix.compose(dolly.position, dolly.quaternion, dolly.scale);
  47678. }
  47679. // Decompose.
  47680. controllerEuler.setFromRotationMatrix(dolly.matrix);
  47681. controllerPosition.setFromMatrixPosition(dolly.matrix);
  47682. // Apply rotation.
  47683. this.rotation.x = THREE.Math.radToDeg(controllerEuler.x);
  47684. this.rotation.y = THREE.Math.radToDeg(controllerEuler.y);
  47685. this.rotation.z = THREE.Math.radToDeg(controllerEuler.z) + this.data.rotationOffset;
  47686. el.setAttribute('rotation', this.rotation);
  47687. // Apply position.
  47688. elPosition = el.getAttribute('position');
  47689. this.position.copy(elPosition).sub(previousControllerPosition).add(controllerPosition);
  47690. el.setAttribute('position', this.position);
  47691. previousControllerPosition.copy(controllerPosition);
  47692. },
  47693. /**
  47694. * Handle button changes including axes, presses, touches, values.
  47695. */
  47696. updateButtons: function () {
  47697. var buttonState;
  47698. var controller = this.controller;
  47699. var id;
  47700. if (!controller) { return; }
  47701. // Check every button.
  47702. for (id = 0; id < controller.buttons.length; ++id) {
  47703. // Initialize button state.
  47704. if (!this.buttonStates[id]) {
  47705. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  47706. }
  47707. buttonState = controller.buttons[id];
  47708. this.handleButton(id, buttonState);
  47709. }
  47710. // Check axes.
  47711. this.handleAxes();
  47712. },
  47713. /**
  47714. * Handle presses and touches for a single button.
  47715. *
  47716. * @param {number} id - Index of button in Gamepad button array.
  47717. * @param {number} buttonState - Value of button state from 0 to 1.
  47718. * @returns {boolean} Whether button has changed in any way.
  47719. */
  47720. handleButton: function (id, buttonState) {
  47721. var changed = this.handlePress(id, buttonState) ||
  47722. this.handleTouch(id, buttonState) ||
  47723. this.handleValue(id, buttonState);
  47724. if (!changed) { return false; }
  47725. this.el.emit('buttonchanged', {id: id, state: buttonState});
  47726. return true;
  47727. },
  47728. /**
  47729. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  47730. * Compare each component of the axis to the previous value to determine change.
  47731. *
  47732. * @returns {boolean} Whether axes changed.
  47733. */
  47734. handleAxes: function () {
  47735. var changed = false;
  47736. var controllerAxes = this.controller.axes;
  47737. var i;
  47738. var previousAxis = this.axis;
  47739. var changedAxes = [];
  47740. // Check if axis changed.
  47741. for (i = 0; i < controllerAxes.length; ++i) {
  47742. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  47743. if (changedAxes[i]) { changed = true; }
  47744. }
  47745. if (!changed) { return false; }
  47746. this.axis = controllerAxes.slice();
  47747. this.el.emit('axismove', {axis: this.axis, changed: changedAxes});
  47748. return true;
  47749. },
  47750. /**
  47751. * Determine whether a button press has occured and emit events as appropriate.
  47752. *
  47753. * @param {string} id - ID of the button to check.
  47754. * @param {object} buttonState - State of the button to check.
  47755. * @returns {boolean} Whether button press state changed.
  47756. */
  47757. handlePress: function (id, buttonState) {
  47758. var evtName;
  47759. var previousButtonState = this.buttonStates[id];
  47760. // Not changed.
  47761. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47762. evtName = buttonState.pressed ? 'down' : 'up';
  47763. this.el.emit('button' + evtName, {id: id, state: buttonState});
  47764. previousButtonState.pressed = buttonState.pressed;
  47765. return true;
  47766. },
  47767. /**
  47768. * Determine whether a button touch has occured and emit events as appropriate.
  47769. *
  47770. * @param {string} id - ID of the button to check.
  47771. * @param {object} buttonState - State of the button to check.
  47772. * @returns {boolean} Whether button touch state changed.
  47773. */
  47774. handleTouch: function (id, buttonState) {
  47775. var evtName;
  47776. var previousButtonState = this.buttonStates[id];
  47777. // Not changed.
  47778. if (buttonState.touched === previousButtonState.touched) { return false; }
  47779. evtName = buttonState.touched ? 'start' : 'end';
  47780. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  47781. this.el.emit('touch' + evtName, {id: id, state: buttonState}, true, {touches: []});
  47782. previousButtonState.touched = buttonState.touched;
  47783. return true;
  47784. },
  47785. /**
  47786. * Determine whether a button value has changed.
  47787. *
  47788. * @param {string} id - Id of the button to check.
  47789. * @param {object} buttonState - State of the button to check.
  47790. * @returns {boolean} Whether button value changed.
  47791. */
  47792. handleValue: function (id, buttonState) {
  47793. var previousButtonState = this.buttonStates[id];
  47794. // Not changed.
  47795. if (buttonState.value === previousButtonState.value) { return false; }
  47796. previousButtonState.value = buttonState.value;
  47797. return true;
  47798. }
  47799. });
  47800. },{"../constants":116,"../core/component":125,"../lib/three":173,"../utils/tracked-controls":200}],111:[function(_dereq_,module,exports){
  47801. var registerComponent = _dereq_('../core/component').registerComponent;
  47802. /**
  47803. * Visibility component.
  47804. */
  47805. module.exports.Component = registerComponent('visible', {
  47806. schema: {default: true},
  47807. update: function () {
  47808. this.el.object3D.visible = this.data;
  47809. }
  47810. });
  47811. },{"../core/component":125}],112:[function(_dereq_,module,exports){
  47812. var registerComponent = _dereq_('../core/component').registerComponent;
  47813. var utils = _dereq_('../utils/');
  47814. var bind = utils.bind;
  47815. var checkControllerPresentAndSetup = utils.trackedControls.checkControllerPresentAndSetup;
  47816. var emitIfAxesChanged = utils.trackedControls.emitIfAxesChanged;
  47817. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47818. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47819. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47820. /**
  47821. * Vive controls.
  47822. * Interface with Vive controllers and map Gamepad events to controller buttons:
  47823. * trackpad, trigger, grip, menu, system
  47824. * Load a controller model and highlight the pressed buttons.
  47825. */
  47826. module.exports.Component = registerComponent('vive-controls', {
  47827. schema: {
  47828. hand: {default: 'left'},
  47829. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47830. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47831. model: {default: true},
  47832. rotationOffset: {default: 0}
  47833. },
  47834. /**
  47835. * Button IDs:
  47836. * 0 - trackpad
  47837. * 1 - trigger (intensity value from 0.5 to 1)
  47838. * 2 - grip
  47839. * 3 - menu (dispatch but better for menu options)
  47840. * 4 - system (never dispatched on this layer)
  47841. */
  47842. mapping: {
  47843. axes: {trackpad: [0, 1]},
  47844. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47845. },
  47846. init: function () {
  47847. var self = this;
  47848. this.animationActive = 'pointing';
  47849. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  47850. this.controllerPresent = false;
  47851. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  47852. this.lastControllerCheck = 0;
  47853. this.onButtonChanged = bind(this.onButtonChanged, this);
  47854. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  47855. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  47856. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  47857. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  47858. this.onAxisMoved = bind(this.onAxisMoved, this);
  47859. this.previousButtonValues = {};
  47860. this.bindMethods();
  47861. },
  47862. play: function () {
  47863. this.checkIfControllerPresent();
  47864. this.addControllersUpdateListener();
  47865. },
  47866. pause: function () {
  47867. this.removeEventListeners();
  47868. this.removeControllersUpdateListener();
  47869. },
  47870. bindMethods: function () {
  47871. this.onModelLoaded = bind(this.onModelLoaded, this);
  47872. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47873. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47874. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47875. this.onAxisMoved = bind(this.onAxisMoved, this);
  47876. },
  47877. addEventListeners: function () {
  47878. var el = this.el;
  47879. el.addEventListener('buttonchanged', this.onButtonChanged);
  47880. el.addEventListener('buttondown', this.onButtonDown);
  47881. el.addEventListener('buttonup', this.onButtonUp);
  47882. el.addEventListener('touchend', this.onButtonTouchEnd);
  47883. el.addEventListener('touchstart', this.onButtonTouchStart);
  47884. el.addEventListener('model-loaded', this.onModelLoaded);
  47885. el.addEventListener('axismove', this.onAxisMoved);
  47886. this.controllerEventsActive = true;
  47887. },
  47888. removeEventListeners: function () {
  47889. var el = this.el;
  47890. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47891. el.removeEventListener('buttondown', this.onButtonDown);
  47892. el.removeEventListener('buttonup', this.onButtonUp);
  47893. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47894. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47895. el.removeEventListener('model-loaded', this.onModelLoaded);
  47896. el.removeEventListener('axismove', this.onAxisMoved);
  47897. this.controllerEventsActive = false;
  47898. },
  47899. /**
  47900. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  47901. * var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  47902. { hand: data.hand });
  47903. * Until then, use hardcoded index.
  47904. */
  47905. checkIfControllerPresent: function () {
  47906. var data = this.data;
  47907. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47908. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  47909. },
  47910. injectTrackedControls: function () {
  47911. var el = this.el;
  47912. var data = this.data;
  47913. // If we have an OpenVR Gamepad, use the fixed mapping.
  47914. el.setAttribute('tracked-controls', {
  47915. idPrefix: GAMEPAD_ID_PREFIX,
  47916. // Hand IDs: 0 = right, 1 = left, 2 = anything else.
  47917. controller: data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2,
  47918. rotationOffset: data.rotationOffset
  47919. });
  47920. // Load model.
  47921. if (!this.data.model) { return; }
  47922. this.el.setAttribute('obj-model', {
  47923. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47924. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47925. });
  47926. },
  47927. addControllersUpdateListener: function () {
  47928. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47929. },
  47930. removeControllersUpdateListener: function () {
  47931. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47932. },
  47933. onControllersUpdate: function () {
  47934. this.checkIfControllerPresent();
  47935. },
  47936. /**
  47937. * Rotate the trigger button based on how hard the trigger is pressed.
  47938. */
  47939. onButtonChanged: function (evt) {
  47940. var button = this.mapping.buttons[evt.detail.id];
  47941. var buttonMeshes = this.buttonMeshes;
  47942. var analogValue;
  47943. if (!button) { return; }
  47944. if (button === 'trigger') {
  47945. analogValue = evt.detail.state.value;
  47946. // Update trigger rotation depending on button value.
  47947. if (buttonMeshes && buttonMeshes.trigger) {
  47948. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47949. }
  47950. }
  47951. // Pass along changed event with button state, using button mapping for convenience.
  47952. this.el.emit(button + 'changed', evt.detail.state);
  47953. },
  47954. onModelLoaded: function (evt) {
  47955. var buttonMeshes;
  47956. var controllerObject3D = evt.detail.model;
  47957. var self = this;
  47958. if (!this.data.model) { return; }
  47959. // Store button meshes object to be able to change their colors.
  47960. buttonMeshes = this.buttonMeshes = {};
  47961. buttonMeshes.grip = {
  47962. left: controllerObject3D.getObjectByName('leftgrip'),
  47963. right: controllerObject3D.getObjectByName('rightgrip')
  47964. };
  47965. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47966. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47967. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47968. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47969. // Set default colors.
  47970. Object.keys(buttonMeshes).forEach(function (buttonName) {
  47971. self.setButtonColor(buttonName, self.data.buttonColor);
  47972. });
  47973. // Offset pivot point.
  47974. controllerObject3D.position.set(0, -0.015, 0.04);
  47975. },
  47976. onAxisMoved: function (evt) {
  47977. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  47978. },
  47979. onButtonEvent: function (id, evtName) {
  47980. var buttonName = this.mapping.buttons[id];
  47981. var color;
  47982. var i;
  47983. var isTouch = evtName.indexOf('touch') !== -1;
  47984. // Emit events.
  47985. if (Array.isArray(buttonName)) {
  47986. for (i = 0; i < buttonName.length; i++) {
  47987. this.el.emit(buttonName[i] + evtName);
  47988. }
  47989. } else {
  47990. this.el.emit(buttonName + evtName);
  47991. }
  47992. if (!this.data.model) { return; }
  47993. // Don't change color for trackpad touch.
  47994. if (isTouch) { return; }
  47995. // Update colors.
  47996. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47997. if (Array.isArray(buttonName)) {
  47998. for (i = 0; i < buttonName.length; i++) {
  47999. this.setButtonColor(buttonName[i], color);
  48000. }
  48001. } else {
  48002. this.setButtonColor(buttonName, color);
  48003. }
  48004. },
  48005. setButtonColor: function (buttonName, color) {
  48006. var buttonMeshes = this.buttonMeshes;
  48007. if (!buttonMeshes) { return; }
  48008. // Need to do both left and right sides for grip.
  48009. if (buttonName === 'grip') {
  48010. buttonMeshes.grip.left.material.color.set(color);
  48011. buttonMeshes.grip.right.material.color.set(color);
  48012. return;
  48013. }
  48014. buttonMeshes[buttonName].material.color.set(color);
  48015. }
  48016. });
  48017. },{"../core/component":125,"../utils/":195}],113:[function(_dereq_,module,exports){
  48018. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  48019. var registerComponent = _dereq_('../core/component').registerComponent;
  48020. var THREE = _dereq_('../lib/three');
  48021. var utils = _dereq_('../utils/');
  48022. var bind = utils.bind;
  48023. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  48024. var CLAMP_VELOCITY = 0.00001;
  48025. var MAX_DELTA = 0.2;
  48026. var KEYS = [
  48027. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  48028. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  48029. ];
  48030. /**
  48031. * WASD component to control entities using WASD keys.
  48032. */
  48033. module.exports.Component = registerComponent('wasd-controls', {
  48034. schema: {
  48035. acceleration: {default: 65},
  48036. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  48037. adEnabled: {default: true},
  48038. adInverted: {default: false},
  48039. easing: {default: 20},
  48040. enabled: {default: true},
  48041. fly: {default: false},
  48042. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  48043. wsEnabled: {default: true},
  48044. wsInverted: {default: false}
  48045. },
  48046. init: function () {
  48047. // To keep track of the pressed keys.
  48048. this.keys = {};
  48049. this.position = {};
  48050. this.velocity = new THREE.Vector3();
  48051. // Bind methods and add event listeners.
  48052. this.onBlur = bind(this.onBlur, this);
  48053. this.onFocus = bind(this.onFocus, this);
  48054. this.onKeyDown = bind(this.onKeyDown, this);
  48055. this.onKeyUp = bind(this.onKeyUp, this);
  48056. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  48057. this.attachVisibilityEventListeners();
  48058. },
  48059. tick: function (time, delta) {
  48060. var currentPosition;
  48061. var data = this.data;
  48062. var el = this.el;
  48063. var movementVector;
  48064. var position = this.position;
  48065. var velocity = this.velocity;
  48066. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  48067. isEmptyObject(this.keys)) { return; }
  48068. // Update velocity.
  48069. delta = delta / 1000;
  48070. this.updateVelocity(delta);
  48071. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  48072. // Get movement vector and translate position.
  48073. currentPosition = el.getAttribute('position');
  48074. movementVector = this.getMovementVector(delta);
  48075. position.x = currentPosition.x + movementVector.x;
  48076. position.y = currentPosition.y + movementVector.y;
  48077. position.z = currentPosition.z + movementVector.z;
  48078. el.setAttribute('position', position);
  48079. },
  48080. remove: function () {
  48081. this.removeKeyEventListeners();
  48082. this.removeVisibilityEventListeners();
  48083. },
  48084. play: function () {
  48085. this.attachKeyEventListeners();
  48086. },
  48087. pause: function () {
  48088. this.keys = {};
  48089. this.removeKeyEventListeners();
  48090. },
  48091. updateVelocity: function (delta) {
  48092. var acceleration;
  48093. var adAxis;
  48094. var adSign;
  48095. var data = this.data;
  48096. var keys = this.keys;
  48097. var velocity = this.velocity;
  48098. var wsAxis;
  48099. var wsSign;
  48100. adAxis = data.adAxis;
  48101. wsAxis = data.wsAxis;
  48102. // If FPS too low, reset velocity.
  48103. if (delta > MAX_DELTA) {
  48104. velocity[adAxis] = 0;
  48105. velocity[wsAxis] = 0;
  48106. return;
  48107. }
  48108. // Decay velocity.
  48109. if (velocity[adAxis] !== 0) {
  48110. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  48111. }
  48112. if (velocity[wsAxis] !== 0) {
  48113. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  48114. }
  48115. // Clamp velocity easing.
  48116. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  48117. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  48118. if (!data.enabled) { return; }
  48119. // Update velocity using keys pressed.
  48120. acceleration = data.acceleration;
  48121. if (data.adEnabled) {
  48122. adSign = data.adInverted ? -1 : 1;
  48123. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  48124. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  48125. }
  48126. if (data.wsEnabled) {
  48127. wsSign = data.wsInverted ? -1 : 1;
  48128. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  48129. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  48130. }
  48131. },
  48132. getMovementVector: (function () {
  48133. var directionVector = new THREE.Vector3(0, 0, 0);
  48134. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  48135. return function (delta) {
  48136. var rotation = this.el.getAttribute('rotation');
  48137. var velocity = this.velocity;
  48138. var xRotation;
  48139. directionVector.copy(velocity);
  48140. directionVector.multiplyScalar(delta);
  48141. // Absolute.
  48142. if (!rotation) { return directionVector; }
  48143. xRotation = this.data.fly ? rotation.x : 0;
  48144. // Transform direction relative to heading.
  48145. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  48146. directionVector.applyEuler(rotationEuler);
  48147. return directionVector;
  48148. };
  48149. })(),
  48150. attachVisibilityEventListeners: function () {
  48151. window.addEventListener('blur', this.onBlur);
  48152. window.addEventListener('focus', this.onFocus);
  48153. document.addEventListener('visibilitychange', this.onVisibilityChange);
  48154. },
  48155. removeVisibilityEventListeners: function () {
  48156. window.removeEventListener('blur', this.onBlur);
  48157. window.removeEventListener('focus', this.onFocus);
  48158. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  48159. },
  48160. attachKeyEventListeners: function () {
  48161. window.addEventListener('keydown', this.onKeyDown);
  48162. window.addEventListener('keyup', this.onKeyUp);
  48163. },
  48164. removeKeyEventListeners: function () {
  48165. window.removeEventListener('keydown', this.onKeyDown);
  48166. window.removeEventListener('keyup', this.onKeyUp);
  48167. },
  48168. onBlur: function () {
  48169. this.pause();
  48170. },
  48171. onFocus: function () {
  48172. this.play();
  48173. },
  48174. onVisibilityChange: function () {
  48175. if (document.hidden) {
  48176. this.onBlur();
  48177. } else {
  48178. this.onFocus();
  48179. }
  48180. },
  48181. onKeyDown: function (event) {
  48182. var code;
  48183. if (!shouldCaptureKeyEvent(event)) { return; }
  48184. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  48185. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  48186. },
  48187. onKeyUp: function (event) {
  48188. var code;
  48189. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  48190. delete this.keys[code];
  48191. }
  48192. });
  48193. function isEmptyObject (keys) {
  48194. var key;
  48195. for (key in keys) { return false; }
  48196. return true;
  48197. }
  48198. },{"../constants":116,"../core/component":125,"../lib/three":173,"../utils/":195}],114:[function(_dereq_,module,exports){
  48199. /* global THREE */
  48200. var bind = _dereq_('../utils/bind');
  48201. var registerComponent = _dereq_('../core/component').registerComponent;
  48202. var controllerUtils = _dereq_('../utils/tracked-controls');
  48203. var utils = _dereq_('../utils/');
  48204. var debug = utils.debug('components:windows-motion-controls:debug');
  48205. var warn = utils.debug('components:windows-motion-controls:warn');
  48206. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  48207. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  48208. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  48209. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  48210. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  48211. /**
  48212. * Windows Motion Controller controls.
  48213. * Interface with Windows Motion Controller controllers and map Gamepad events to
  48214. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  48215. * Load a controller model and transform the pressed buttons.
  48216. */
  48217. module.exports.Component = registerComponent('windows-motion-controls', {
  48218. schema: {
  48219. hand: {default: DEFAULT_HANDEDNESS},
  48220. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  48221. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  48222. pair: {default: 0},
  48223. // If true, loads the controller glTF asset.
  48224. model: {default: true},
  48225. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  48226. hideDisconnected: {default: true}
  48227. },
  48228. mapping: {
  48229. // A-Frame specific semantic axis names
  48230. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  48231. // A-Frame specific semantic button names
  48232. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  48233. // A mapping of the semantic name to node name in the glTF model file,
  48234. // that should be transformed by axis value.
  48235. // This array mirrors the browser Gamepad.axes array, such that
  48236. // the mesh corresponding to axis 0 is in this array index 0.
  48237. axisMeshNames: [
  48238. 'THUMBSTICK_X',
  48239. 'THUMBSTICK_Y',
  48240. 'TOUCHPAD_TOUCH_X',
  48241. 'TOUCHPAD_TOUCH_Y'
  48242. ],
  48243. // A mapping of the semantic name to button node name in the glTF model file,
  48244. // that should be transformed by button value.
  48245. buttonMeshNames: {
  48246. 'trigger': 'SELECT',
  48247. 'menu': 'MENU',
  48248. 'grip': 'GRASP',
  48249. 'thumbstick': 'THUMBSTICK_PRESS',
  48250. 'trackpad': 'TOUCHPAD_PRESS'
  48251. },
  48252. pointingPoseMeshName: 'POINTING_POSE'
  48253. },
  48254. bindMethods: function () {
  48255. this.onModelError = bind(this.onModelError, this);
  48256. this.onModelLoaded = bind(this.onModelLoaded, this);
  48257. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48258. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48259. this.onAxisMoved = bind(this.onAxisMoved, this);
  48260. },
  48261. init: function () {
  48262. var self = this;
  48263. var el = this.el;
  48264. this.onButtonChanged = bind(this.onButtonChanged, this);
  48265. this.onButtonDown = function (evt) { self.onButtonEvent(evt, 'down'); };
  48266. this.onButtonUp = function (evt) { self.onButtonEvent(evt, 'up'); };
  48267. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt, 'touchstart'); };
  48268. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt, 'touchend'); };
  48269. this.onControllerConnected = function () { self.setModelVisibility(true); };
  48270. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  48271. this.controllerPresent = false;
  48272. this.lastControllerCheck = 0;
  48273. this.previousButtonValues = {};
  48274. this.bindMethods();
  48275. // Cache for submeshes that we have looked up by name.
  48276. this.loadedMeshInfo = {
  48277. buttonMeshes: null,
  48278. axisMeshes: null
  48279. };
  48280. // Pointing poses
  48281. this.rayOrigin = {
  48282. origin: new THREE.Vector3(),
  48283. direction: new THREE.Vector3(0, 0, -1),
  48284. createdFromMesh: false
  48285. };
  48286. // Stored on object to allow for mocking in tests
  48287. this.emitIfAxesChanged = controllerUtils.emitIfAxesChanged;
  48288. this.checkControllerPresentAndSetup = controllerUtils.checkControllerPresentAndSetup;
  48289. el.addEventListener('controllerconnected', this.onControllerConnected);
  48290. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  48291. },
  48292. addEventListeners: function () {
  48293. var el = this.el;
  48294. el.addEventListener('buttonchanged', this.onButtonChanged);
  48295. el.addEventListener('buttondown', this.onButtonDown);
  48296. el.addEventListener('buttonup', this.onButtonUp);
  48297. el.addEventListener('touchstart', this.onButtonTouchStart);
  48298. el.addEventListener('touchend', this.onButtonTouchEnd);
  48299. el.addEventListener('axismove', this.onAxisMoved);
  48300. el.addEventListener('model-error', this.onModelError);
  48301. el.addEventListener('model-loaded', this.onModelLoaded);
  48302. this.controllerEventsActive = true;
  48303. },
  48304. removeEventListeners: function () {
  48305. var el = this.el;
  48306. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48307. el.removeEventListener('buttondown', this.onButtonDown);
  48308. el.removeEventListener('buttonup', this.onButtonUp);
  48309. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48310. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48311. el.removeEventListener('axismove', this.onAxisMoved);
  48312. el.removeEventListener('model-error', this.onModelError);
  48313. el.removeEventListener('model-loaded', this.onModelLoaded);
  48314. this.controllerEventsActive = false;
  48315. },
  48316. checkIfControllerPresent: function () {
  48317. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  48318. hand: this.data.hand,
  48319. index: this.data.pair
  48320. });
  48321. },
  48322. play: function () {
  48323. this.checkIfControllerPresent();
  48324. this.addControllersUpdateListener();
  48325. },
  48326. pause: function () {
  48327. this.removeEventListeners();
  48328. this.removeControllersUpdateListener();
  48329. },
  48330. updateControllerModel: function () {
  48331. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  48332. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  48333. this.modelReady();
  48334. return;
  48335. }
  48336. var sourceUrl = this.createControllerModelUrl();
  48337. this.loadModel(sourceUrl);
  48338. },
  48339. /**
  48340. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  48341. * art assets.
  48342. */
  48343. createControllerModelUrl: function (forceDefault) {
  48344. // Determine the device specific folder based on the ID suffix
  48345. var trackedControlsComponent = this.el.components['tracked-controls'];
  48346. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  48347. var device = 'default';
  48348. var hand = this.data.hand;
  48349. var filename;
  48350. if (controller) {
  48351. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  48352. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  48353. // In this case, we want to load the universal model, so need to get the '' from the controller.
  48354. hand = controller.hand;
  48355. if (!forceDefault) {
  48356. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  48357. device = ((match && match[0]) || device);
  48358. }
  48359. }
  48360. // Hand
  48361. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  48362. // Final url
  48363. return MODEL_BASE_URL + device + '/' + filename;
  48364. },
  48365. injectTrackedControls: function () {
  48366. var data = this.data;
  48367. this.el.setAttribute('tracked-controls', {
  48368. idPrefix: GAMEPAD_ID_PREFIX,
  48369. controller: data.pair,
  48370. hand: data.hand,
  48371. armModel: false
  48372. });
  48373. this.updateControllerModel();
  48374. },
  48375. addControllersUpdateListener: function () {
  48376. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48377. },
  48378. removeControllersUpdateListener: function () {
  48379. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48380. },
  48381. onControllersUpdate: function () {
  48382. this.checkIfControllerPresent();
  48383. },
  48384. onModelError: function (evt) {
  48385. var defaultUrl = this.createControllerModelUrl(true);
  48386. if (evt.detail.src !== defaultUrl) {
  48387. warn('Failed to load controller model for device, attempting to load default.');
  48388. this.loadModel(defaultUrl);
  48389. } else {
  48390. warn('Failed to load default controller model.');
  48391. }
  48392. },
  48393. loadModel: function (url) {
  48394. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  48395. // removed and re-loaded if the given url changes.
  48396. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  48397. },
  48398. onModelLoaded: function (evt) {
  48399. var rootNode = this.controllerModel = evt.detail.model;
  48400. var loadedMeshInfo = this.loadedMeshInfo;
  48401. var i;
  48402. var meshName;
  48403. var mesh;
  48404. var meshInfo;
  48405. debug('Processing model');
  48406. // Reset the caches
  48407. loadedMeshInfo.buttonMeshes = {};
  48408. loadedMeshInfo.axisMeshes = {};
  48409. // Cache our meshes so we aren't traversing the hierarchy per frame
  48410. if (rootNode) {
  48411. // Button Meshes
  48412. for (i = 0; i < this.mapping.buttons.length; i++) {
  48413. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  48414. if (!meshName) {
  48415. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  48416. continue;
  48417. }
  48418. mesh = rootNode.getObjectByName(meshName);
  48419. if (!mesh) {
  48420. warn('Missing button mesh with name: ' + meshName);
  48421. continue;
  48422. }
  48423. meshInfo = {
  48424. index: i,
  48425. value: getImmediateChildByName(mesh, 'VALUE'),
  48426. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  48427. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  48428. };
  48429. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  48430. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  48431. } else {
  48432. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  48433. warn('Missing button submesh under mesh with name: ' + meshName +
  48434. '(VALUE: ' + !!meshInfo.value +
  48435. ', PRESSED: ' + !!meshInfo.pressed +
  48436. ', UNPRESSED:' + !!meshInfo.unpressed +
  48437. ')');
  48438. }
  48439. }
  48440. // Axis Meshes
  48441. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  48442. meshName = this.mapping.axisMeshNames[i];
  48443. if (!meshName) {
  48444. debug('Skipping unknown axis at index: ' + i);
  48445. continue;
  48446. }
  48447. mesh = rootNode.getObjectByName(meshName);
  48448. if (!mesh) {
  48449. warn('Missing axis mesh with name: ' + meshName);
  48450. continue;
  48451. }
  48452. meshInfo = {
  48453. index: i,
  48454. value: getImmediateChildByName(mesh, 'VALUE'),
  48455. min: getImmediateChildByName(mesh, 'MIN'),
  48456. max: getImmediateChildByName(mesh, 'MAX')
  48457. };
  48458. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  48459. loadedMeshInfo.axisMeshes[i] = meshInfo;
  48460. } else {
  48461. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  48462. warn('Missing axis submesh under mesh with name: ' + meshName +
  48463. '(VALUE: ' + !!meshInfo.value +
  48464. ', MIN: ' + !!meshInfo.min +
  48465. ', MAX:' + !!meshInfo.max +
  48466. ')');
  48467. }
  48468. }
  48469. this.calculateRayOriginFromMesh(rootNode);
  48470. // Determine if the model has to be visible or not.
  48471. this.setModelVisibility();
  48472. }
  48473. debug('Model load complete.');
  48474. // Look through only immediate children. This will return null if no mesh exists with the given name.
  48475. function getImmediateChildByName (object3d, value) {
  48476. for (var i = 0, l = object3d.children.length; i < l; i++) {
  48477. var obj = object3d.children[i];
  48478. if (obj && obj['name'] === value) {
  48479. return obj;
  48480. }
  48481. }
  48482. return undefined;
  48483. }
  48484. },
  48485. calculateRayOriginFromMesh: (function () {
  48486. var quaternion = new THREE.Quaternion();
  48487. return function (rootNode) {
  48488. var mesh;
  48489. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  48490. // in the glTF (assumes that root node is at world origin)
  48491. this.rayOrigin.origin.set(0, 0, 0);
  48492. this.rayOrigin.direction.set(0, 0, -1);
  48493. this.rayOrigin.createdFromMesh = true;
  48494. // Try to read Pointing pose from the source model
  48495. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  48496. if (mesh) {
  48497. var parent = rootNode.parent;
  48498. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  48499. if (parent) {
  48500. rootNode.parent = null;
  48501. rootNode.updateMatrixWorld(true);
  48502. rootNode.parent = parent;
  48503. }
  48504. mesh.getWorldPosition(this.rayOrigin.origin);
  48505. mesh.getWorldQuaternion(quaternion);
  48506. this.rayOrigin.direction.applyQuaternion(quaternion);
  48507. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  48508. if (parent) {
  48509. rootNode.updateMatrixWorld(true);
  48510. }
  48511. } else {
  48512. debug('Mesh does not contain pointing origin data, defaulting to none.');
  48513. }
  48514. // Emit event stating that our pointing ray is now accurate.
  48515. this.modelReady();
  48516. };
  48517. })(),
  48518. lerpAxisTransform: (function () {
  48519. var quaternion = new THREE.Quaternion();
  48520. return function (axis, axisValue) {
  48521. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  48522. if (!axisMeshInfo) return;
  48523. var min = axisMeshInfo.min;
  48524. var max = axisMeshInfo.max;
  48525. var target = axisMeshInfo.value;
  48526. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  48527. var lerpValue = axisValue * 0.5 + 0.5;
  48528. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  48529. target.position.lerpVectors(min.position, max.position, lerpValue);
  48530. };
  48531. })(),
  48532. lerpButtonTransform: (function () {
  48533. var quaternion = new THREE.Quaternion();
  48534. return function (buttonName, buttonValue) {
  48535. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  48536. if (!buttonMeshInfo) return;
  48537. var min = buttonMeshInfo.unpressed;
  48538. var max = buttonMeshInfo.pressed;
  48539. var target = buttonMeshInfo.value;
  48540. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  48541. target.position.lerpVectors(min.position, max.position, buttonValue);
  48542. };
  48543. })(),
  48544. modelReady: function () {
  48545. this.el.emit('controllermodelready', {
  48546. name: 'windows-motion-controls',
  48547. model: this.data.model,
  48548. rayOrigin: this.rayOrigin
  48549. });
  48550. },
  48551. onButtonChanged: function (evt) {
  48552. var buttonName = this.mapping.buttons[evt.detail.id];
  48553. if (buttonName) {
  48554. // Update the button mesh transform
  48555. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  48556. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  48557. }
  48558. // Only emit events for buttons that we know how to map from index to name
  48559. this.el.emit(buttonName + 'changed', evt.detail.state);
  48560. }
  48561. },
  48562. onButtonEvent: function (evt, evtName) {
  48563. var buttonName = this.mapping.buttons[evt.detail.id];
  48564. debug('onButtonEvent(' + evt.detail.id + ', ' + evtName + ')');
  48565. if (buttonName) {
  48566. // Only emit events for buttons that we know how to map from index to name
  48567. this.el.emit(buttonName + evtName);
  48568. }
  48569. },
  48570. onAxisMoved: function (evt) {
  48571. var numAxes = this.mapping.axisMeshNames.length;
  48572. // Only attempt to update meshes if we have valid data.
  48573. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  48574. for (var axis = 0; axis < numAxes; axis++) {
  48575. // Update the button mesh transform
  48576. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  48577. }
  48578. }
  48579. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  48580. },
  48581. setModelVisibility: function (visible) {
  48582. var model = this.el.getObject3D('mesh');
  48583. visible = visible !== undefined ? visible : this.modelVisible;
  48584. this.modelVisible = visible;
  48585. if (!model) { return; }
  48586. model.visible = visible;
  48587. }
  48588. });
  48589. },{"../constants":116,"../core/component":125,"../utils/":195,"../utils/bind":189,"../utils/tracked-controls":200}],115:[function(_dereq_,module,exports){
  48590. /**
  48591. * Animation configuration options for TWEEN.js animations.
  48592. * Used by `<a-animation>`.
  48593. */
  48594. var TWEEN = _dereq_('@tweenjs/tween.js');
  48595. var DIRECTIONS = {
  48596. alternate: 'alternate',
  48597. alternateReverse: 'alternate-reverse',
  48598. normal: 'normal',
  48599. reverse: 'reverse'
  48600. };
  48601. var EASING_FUNCTIONS = {
  48602. 'linear': TWEEN.Easing.Linear.None,
  48603. 'ease': TWEEN.Easing.Cubic.InOut,
  48604. 'ease-in': TWEEN.Easing.Cubic.In,
  48605. 'ease-out': TWEEN.Easing.Cubic.Out,
  48606. 'ease-in-out': TWEEN.Easing.Cubic.InOut,
  48607. 'ease-cubic': TWEEN.Easing.Cubic.In,
  48608. 'ease-in-cubic': TWEEN.Easing.Cubic.In,
  48609. 'ease-out-cubic': TWEEN.Easing.Cubic.Out,
  48610. 'ease-in-out-cubic': TWEEN.Easing.Cubic.InOut,
  48611. 'ease-quad': TWEEN.Easing.Quadratic.InOut,
  48612. 'ease-in-quad': TWEEN.Easing.Quadratic.In,
  48613. 'ease-out-quad': TWEEN.Easing.Quadratic.Out,
  48614. 'ease-in-out-quad': TWEEN.Easing.Quadratic.InOut,
  48615. 'ease-quart': TWEEN.Easing.Quartic.InOut,
  48616. 'ease-in-quart': TWEEN.Easing.Quartic.In,
  48617. 'ease-out-quart': TWEEN.Easing.Quartic.Out,
  48618. 'ease-in-out-quart': TWEEN.Easing.Quartic.InOut,
  48619. 'ease-quint': TWEEN.Easing.Quintic.InOut,
  48620. 'ease-in-quint': TWEEN.Easing.Quintic.In,
  48621. 'ease-out-quint': TWEEN.Easing.Quintic.Out,
  48622. 'ease-in-out-quint': TWEEN.Easing.Quintic.InOut,
  48623. 'ease-sine': TWEEN.Easing.Sinusoidal.InOut,
  48624. 'ease-in-sine': TWEEN.Easing.Sinusoidal.In,
  48625. 'ease-out-sine': TWEEN.Easing.Sinusoidal.Out,
  48626. 'ease-in-out-sine': TWEEN.Easing.Sinusoidal.InOut,
  48627. 'ease-expo': TWEEN.Easing.Exponential.InOut,
  48628. 'ease-in-expo': TWEEN.Easing.Exponential.In,
  48629. 'ease-out-expo': TWEEN.Easing.Exponential.Out,
  48630. 'ease-in-out-expo': TWEEN.Easing.Exponential.InOut,
  48631. 'ease-circ': TWEEN.Easing.Circular.InOut,
  48632. 'ease-in-circ': TWEEN.Easing.Circular.In,
  48633. 'ease-out-circ': TWEEN.Easing.Circular.Out,
  48634. 'ease-in-out-circ': TWEEN.Easing.Circular.InOut,
  48635. 'ease-elastic': TWEEN.Easing.Elastic.InOut,
  48636. 'ease-in-elastic': TWEEN.Easing.Elastic.In,
  48637. 'ease-out-elastic': TWEEN.Easing.Elastic.Out,
  48638. 'ease-in-out-elastic': TWEEN.Easing.Elastic.InOut,
  48639. 'ease-back': TWEEN.Easing.Back.InOut,
  48640. 'ease-in-back': TWEEN.Easing.Back.In,
  48641. 'ease-out-back': TWEEN.Easing.Back.Out,
  48642. 'ease-in-out-back': TWEEN.Easing.Back.InOut,
  48643. 'ease-bounce': TWEEN.Easing.Bounce.InOut,
  48644. 'ease-in-bounce': TWEEN.Easing.Bounce.In,
  48645. 'ease-out-bounce': TWEEN.Easing.Bounce.Out,
  48646. 'ease-in-out-bounce': TWEEN.Easing.Bounce.InOut
  48647. };
  48648. var FILLS = {
  48649. backwards: 'backwards',
  48650. both: 'both',
  48651. forwards: 'forwards',
  48652. none: 'none'
  48653. };
  48654. var REPEATS = {
  48655. indefinite: 'indefinite'
  48656. };
  48657. var DEFAULTS = {
  48658. attribute: 'rotation',
  48659. begin: '',
  48660. end: '',
  48661. delay: 0,
  48662. dur: 1000,
  48663. easing: 'ease',
  48664. direction: DIRECTIONS.normal,
  48665. fill: FILLS.forwards,
  48666. from: undefined,
  48667. repeat: 0,
  48668. to: undefined
  48669. };
  48670. module.exports.defaults = DEFAULTS;
  48671. module.exports.directions = DIRECTIONS;
  48672. module.exports.easingFunctions = EASING_FUNCTIONS;
  48673. module.exports.fills = FILLS;
  48674. module.exports.repeats = REPEATS;
  48675. },{"@tweenjs/tween.js":1}],116:[function(_dereq_,module,exports){
  48676. module.exports = {
  48677. AFRAME_INJECTED: 'aframe-injected',
  48678. DEFAULT_CAMERA_HEIGHT: 1.6,
  48679. DEFAULT_HANDEDNESS: 'right',
  48680. animation: _dereq_('./animation'),
  48681. keyboardevent: _dereq_('./keyboardevent')
  48682. };
  48683. },{"./animation":115,"./keyboardevent":117}],117:[function(_dereq_,module,exports){
  48684. module.exports = {
  48685. // Tiny KeyboardEvent.code polyfill.
  48686. KEYCODE_TO_CODE: {
  48687. '38': 'ArrowUp',
  48688. '37': 'ArrowLeft',
  48689. '40': 'ArrowDown',
  48690. '39': 'ArrowRight',
  48691. '87': 'KeyW',
  48692. '65': 'KeyA',
  48693. '83': 'KeyS',
  48694. '68': 'KeyD'
  48695. }
  48696. };
  48697. },{}],118:[function(_dereq_,module,exports){
  48698. var ANode = _dereq_('./a-node');
  48699. var animationConstants = _dereq_('../constants/animation');
  48700. var coordinates = _dereq_('../utils/').coordinates;
  48701. var parseProperty = _dereq_('./schema').parseProperty;
  48702. var registerElement = _dereq_('./a-register-element').registerElement;
  48703. var TWEEN = _dereq_('@tweenjs/tween.js');
  48704. var THREE = _dereq_('../lib/three');
  48705. var utils = _dereq_('../utils/');
  48706. var bind = utils.bind;
  48707. var getComponentProperty = utils.entity.getComponentProperty;
  48708. var DEFAULTS = animationConstants.defaults;
  48709. var DIRECTIONS = animationConstants.directions;
  48710. var EASING_FUNCTIONS = animationConstants.easingFunctions;
  48711. var FILLS = animationConstants.fills;
  48712. var REPEATS = animationConstants.repeats;
  48713. var isCoordinates = coordinates.isCoordinates;
  48714. /**
  48715. * Animation element that applies Tween animation to parent element (entity).
  48716. * Takes after the Web Animations spec.
  48717. *
  48718. * @member {number} count - Decrementing counter for how many cycles of animations left to
  48719. * run.
  48720. * @member {Element} el - Entity which the animation is modifying.
  48721. * @member initialValue - Value before animation started. Used to restore state.
  48722. * @member {bool} isRunning - Whether animation is currently running.
  48723. * @member {function} partialSetAttribute -
  48724. * setAttribute function that is agnostic to whether we are setting an attribute value
  48725. * or a component property value. The el and the attribute names are bundled with
  48726. * the function.
  48727. * @member {object} tween - tween.js object.
  48728. */
  48729. module.exports.AAnimation = registerElement('a-animation', {
  48730. prototype: Object.create(ANode.prototype, {
  48731. createdCallback: {
  48732. value: function () {
  48733. this.bindMethods();
  48734. this.isRunning = false;
  48735. this.partialSetAttribute = function () { /* no-op */ };
  48736. this.tween = null;
  48737. }
  48738. },
  48739. attachedCallback: {
  48740. value: function () {
  48741. this.el = this.parentNode;
  48742. this.handleMixinUpdate();
  48743. this.update();
  48744. this.load();
  48745. }
  48746. },
  48747. attributeChangedCallback: {
  48748. value: function (attr, oldVal, newVal) {
  48749. if (!this.hasLoaded || !this.isRunning) { return; }
  48750. this.stop();
  48751. this.handleMixinUpdate();
  48752. this.update();
  48753. }
  48754. },
  48755. detachedCallback: {
  48756. value: function () {
  48757. if (!this.isRunning) { return; }
  48758. this.stop();
  48759. }
  48760. },
  48761. /**
  48762. * Builds a Tween object to handle animations.
  48763. * Uses tween.js's from, to, delay, easing, repeat, onUpdate, and onComplete.
  48764. * Note: tween.js takes objects for its `from` and `to` values.
  48765. *
  48766. * @returns {object}
  48767. */
  48768. getTween: {
  48769. value: function () {
  48770. var self = this;
  48771. var data = self.data;
  48772. var el = self.el;
  48773. var animationValues;
  48774. var attribute = data.attribute;
  48775. var delay = parseInt(data.delay, 10);
  48776. var currentValue = getComponentProperty(el, attribute);
  48777. var direction = self.getDirection(data.direction);
  48778. var easing = EASING_FUNCTIONS[data.easing];
  48779. var fill = data.fill;
  48780. var from;
  48781. var repeat = data.repeat === REPEATS.indefinite ? Infinity : 0;
  48782. var to;
  48783. var toTemp;
  48784. var yoyo = false;
  48785. animationValues = getAnimationValues(el, attribute, data.from || self.initialValue, data.to, currentValue);
  48786. from = animationValues.from;
  48787. to = animationValues.to;
  48788. self.partialSetAttribute = animationValues.partialSetAttribute;
  48789. if (self.count === undefined) {
  48790. self.count = repeat === Infinity ? 0 : parseInt(data.repeat, 10);
  48791. }
  48792. if (isNaN(delay)) { delay = 0; }
  48793. // Store initial state.
  48794. self.initialValue = self.initialValue || cloneValue(currentValue);
  48795. // Handle indefinite + forwards + alternate yoyo edge-case (#405).
  48796. if (repeat === Infinity && fill === FILLS.forwards &&
  48797. [DIRECTIONS.alternate,
  48798. DIRECTIONS.alternateReverse].indexOf(data.direction) !== -1) {
  48799. yoyo = true;
  48800. }
  48801. // If reversing, swap from and to.
  48802. if (direction === DIRECTIONS.reverse) {
  48803. toTemp = to;
  48804. to = cloneValue(from);
  48805. from = cloneValue(toTemp);
  48806. }
  48807. // If fill is backwards or both, start animation at the specified from.
  48808. if ([FILLS.backwards, FILLS.both].indexOf(fill) !== -1) {
  48809. self.partialSetAttribute(from);
  48810. }
  48811. // Create Tween.
  48812. return new TWEEN.Tween(cloneValue(from))
  48813. .to(to, data.dur)
  48814. .delay(delay)
  48815. .easing(easing)
  48816. .repeat(repeat)
  48817. .yoyo(yoyo)
  48818. .onUpdate(function () {
  48819. self.partialSetAttribute(this);
  48820. })
  48821. .onComplete(bind(self.onCompleted, self));
  48822. }
  48823. },
  48824. /**
  48825. * Animation parameters changed. Stop current animation, get a new one, and start it.
  48826. */
  48827. update: {
  48828. value: function () {
  48829. var data = this.data;
  48830. // Terminology warning if infinite used instead of indefinite
  48831. if (data.repeat === 'infinite') {
  48832. console.warn("Using 'infinite' as 'repeat' value is invalid. Use 'indefinite' instead.");
  48833. }
  48834. // Deprecation warning for begin when used as a delay.
  48835. if (data.begin !== '' && !isNaN(data.begin)) {
  48836. console.warn("Using 'begin' to specify a delay is deprecated. Use 'delay' instead.");
  48837. data.delay = data.begin;
  48838. data.begin = '';
  48839. }
  48840. var begin = data.begin;
  48841. var end = data.end;
  48842. // Cancel previous event listeners
  48843. if (this.evt) { this.removeEventListeners(this.evt); }
  48844. // Store new event name.
  48845. this.evt = {begin: begin, end: end};
  48846. // Add new event listeners
  48847. this.addEventListeners(this.evt);
  48848. // If `begin` is not defined, start the animation right away.
  48849. if (begin === '') {
  48850. this.stop();
  48851. this.start();
  48852. }
  48853. },
  48854. writable: window.debug
  48855. },
  48856. /**
  48857. * Callback for when a cycle of an animation is complete. Handles when to completely
  48858. * finish the animation.
  48859. *
  48860. * If `repeat` is set to a value, this method is called after each repeat. Repeats are
  48861. * handled by ending the current animation and creating a new one with `count` updated.
  48862. * Note that this method is *not* called if repeat is set to `indefinite`.
  48863. */
  48864. onCompleted: {
  48865. value: function () {
  48866. var data = this.data;
  48867. this.isRunning = false;
  48868. if ([FILLS.backwards, FILLS.none].indexOf(data.fill) !== -1) {
  48869. this.partialSetAttribute(this.initialValue);
  48870. }
  48871. if (this.count === 0) {
  48872. this.count = undefined;
  48873. this.emit('animationend');
  48874. return;
  48875. }
  48876. this.isRunning = false;
  48877. this.count--;
  48878. this.start();
  48879. }
  48880. },
  48881. start: {
  48882. value: function () {
  48883. var self = this;
  48884. // Postpone animation start until the entity has loaded
  48885. if (!this.el.hasLoaded) {
  48886. this.el.addEventListener('loaded', function () { self.start(); });
  48887. return;
  48888. }
  48889. if (this.isRunning || !this.el.isPlaying) { return; }
  48890. this.tween = this.getTween();
  48891. this.isRunning = true;
  48892. this.tween.start();
  48893. this.emit('animationstart');
  48894. },
  48895. writable: true
  48896. },
  48897. stop: {
  48898. value: function () {
  48899. var tween = this.tween;
  48900. if (!tween) { return; }
  48901. tween.stop();
  48902. this.isRunning = false;
  48903. if ([FILLS.backwards, FILLS.none].indexOf(this.data.fill) !== -1) {
  48904. this.partialSetAttribute(this.initialValue);
  48905. }
  48906. this.emit('animationstop');
  48907. },
  48908. writable: true
  48909. },
  48910. /**
  48911. * Handle alternating directions. Given the current direction, calculate the next one,
  48912. * and store the current one.
  48913. *
  48914. * @param {string} direction
  48915. * @returns {string} Direction that the next individual cycle of the animation will go
  48916. * towards.
  48917. */
  48918. getDirection: {
  48919. value: function (direction) {
  48920. if (direction === DIRECTIONS.alternate) {
  48921. this.prevDirection =
  48922. this.prevDirection === DIRECTIONS.normal ? DIRECTIONS.reverse : DIRECTIONS.normal;
  48923. return this.prevDirection;
  48924. }
  48925. if (direction === DIRECTIONS.alternateReverse) {
  48926. this.prevDirection =
  48927. this.prevDirection === DIRECTIONS.reverse ? DIRECTIONS.normal : DIRECTIONS.reverse;
  48928. return this.prevDirection;
  48929. }
  48930. return direction;
  48931. }
  48932. },
  48933. /**
  48934. * Preemptive binding to attach/detach event listeners (see `update`).
  48935. */
  48936. bindMethods: {
  48937. value: function () {
  48938. this.start = bind(this.start, this);
  48939. this.stop = bind(this.stop, this);
  48940. this.onStateAdded = bind(this.onStateAdded, this);
  48941. this.onStateRemoved = bind(this.onStateRemoved, this);
  48942. }
  48943. },
  48944. addEventListeners: {
  48945. value: function (evts) {
  48946. var el = this.el;
  48947. var self = this;
  48948. utils.splitString(evts.begin).forEach(function (evt) {
  48949. el.addEventListener(evt, self.start);
  48950. });
  48951. utils.splitString(evts.end).forEach(function (evt) {
  48952. el.addEventListener(evt, self.stop);
  48953. });
  48954. // If "begin" is an event name, wait. If it is not defined, start.
  48955. if (evts.begin === '') { el.addEventListener('play', this.start); }
  48956. el.addEventListener('pause', this.stop);
  48957. el.addEventListener('stateadded', this.onStateAdded);
  48958. el.addEventListener('stateremoved', this.onStateRemoved);
  48959. }
  48960. },
  48961. removeEventListeners: {
  48962. value: function (evts) {
  48963. var el = this.el;
  48964. var start = this.start;
  48965. var stop = this.stop;
  48966. utils.splitString(evts.begin).forEach(function (evt) {
  48967. el.removeEventListener(evt, start);
  48968. });
  48969. utils.splitString(evts.end).forEach(function (evt) {
  48970. el.removeEventListener(evt, stop);
  48971. });
  48972. el.removeEventListener('stateadded', this.onStateAdded);
  48973. el.removeEventListener('stateremoved', this.onStateRemoved);
  48974. }
  48975. },
  48976. onStateAdded: {
  48977. value: function (evt) {
  48978. if (evt.detail.state === this.data.begin) { this.start(); }
  48979. },
  48980. writable: true
  48981. },
  48982. onStateRemoved: {
  48983. value: function (evt) {
  48984. if (evt.detail.state === this.data.begin) { this.stop(); }
  48985. },
  48986. writable: true
  48987. },
  48988. /**
  48989. * Applies animation data from a mixin element.
  48990. * Works the same as component mixins but reimplemented because animations
  48991. * aren't components.
  48992. */
  48993. handleMixinUpdate: {
  48994. value: function () {
  48995. var data = {};
  48996. var elData;
  48997. var mixinData;
  48998. var mixinEl;
  48999. // Get mixin data.
  49000. mixinEl = document.querySelector('#' + this.getAttribute('mixin'));
  49001. mixinData = mixinEl ? utils.getElData(mixinEl, DEFAULTS) : {};
  49002. elData = utils.getElData(this, DEFAULTS);
  49003. utils.extend(data, DEFAULTS, mixinData, elData);
  49004. this.data = data;
  49005. }
  49006. }
  49007. })
  49008. });
  49009. function cloneValue (val) {
  49010. return utils.extend({}, val);
  49011. }
  49012. /**
  49013. * Deduces different animation values based on whether we are:
  49014. * - animating an inner attribute of a component.
  49015. * - animating a coordinate component.
  49016. * - animating a boolean.
  49017. * - animating a number.
  49018. *
  49019. * @param {Element} el
  49020. * @param {string} attribute - Tells what to animate based on whether it is dot-separated.
  49021. * @param {string} dataFrom - Data `from` value.
  49022. * @param {string} dataTo - Data `to` value.
  49023. * @param currentValue
  49024. * @returns {object}
  49025. * Object with keys [from, to, partialSetAttribute].
  49026. * `from` and `to`
  49027. * Objects where key is attribute being animated and value is value.
  49028. * `partialSetAttribute`
  49029. * Closured-function that tells tween how to update the component.
  49030. */
  49031. function getAnimationValues (el, attribute, dataFrom, dataTo, currentValue) {
  49032. var attributeSplit = attribute.split('.');
  49033. var schema;
  49034. var component;
  49035. var componentPropName;
  49036. var componentName;
  49037. var from = {};
  49038. var partialSetAttribute;
  49039. var to = {};
  49040. if (attributeSplit.length === 2) {
  49041. if (isColor()) {
  49042. getForColorComponent();
  49043. } else {
  49044. getForComponentAttribute();
  49045. }
  49046. } else if (dataTo && isCoordinates(dataTo)) {
  49047. getForCoordinateComponent();
  49048. } else if (['true', 'false'].indexOf(dataTo) !== -1) {
  49049. getForBoolean();
  49050. } else if (isNaN(dataTo)) {
  49051. getForColorComponent();
  49052. } else {
  49053. getForNumber();
  49054. }
  49055. return {
  49056. from: from,
  49057. partialSetAttribute: partialSetAttribute,
  49058. to: to
  49059. };
  49060. /**
  49061. * Match the schema type to color
  49062. * @return {bool} if the schema is of type color
  49063. */
  49064. function isColor () {
  49065. var componentName = attributeSplit[0];
  49066. var propertyName = attributeSplit[1];
  49067. var component = el.components[componentName];
  49068. var schema = component && component.schema;
  49069. return schema && schema[propertyName] && schema[propertyName].type === 'color';
  49070. }
  49071. /**
  49072. * Animating a component that has multiple attributes (e.g., geometry.width).
  49073. */
  49074. function getForComponentAttribute () {
  49075. componentName = attributeSplit[0];
  49076. componentPropName = attributeSplit[1];
  49077. component = el.components[componentName];
  49078. if (!component) {
  49079. el.setAttribute(componentName, '');
  49080. component = el.components[componentName];
  49081. }
  49082. schema = component.schema;
  49083. if (dataFrom === undefined) { // dataFrom can be 0.
  49084. from[attribute] = getComponentProperty(el, attribute);
  49085. } else {
  49086. from[attribute] = dataFrom;
  49087. }
  49088. from[attribute] = parseProperty(from[attribute], schema[componentPropName]);
  49089. to[attribute] = parseProperty(dataTo, schema[componentPropName]);
  49090. partialSetAttribute = function (value) {
  49091. if (!(attribute in value)) { return; }
  49092. el.setAttribute(componentName, componentPropName, value[attribute]);
  49093. };
  49094. }
  49095. /**
  49096. * Animating a component that is an XYZ coordinate (e.g., position).
  49097. * Will be tweening {x, y, z} all at once.
  49098. */
  49099. function getForCoordinateComponent () {
  49100. from = dataFrom ? coordinates.parse(dataFrom) : currentValue;
  49101. to = coordinates.parse(dataTo);
  49102. partialSetAttribute = function (value) {
  49103. el.setAttribute(attribute, value);
  49104. };
  49105. }
  49106. /**
  49107. * Animation a boolean (e.g., visible).
  49108. * Have to convert from boolean to an integer (0 is false, > 0 is true) for tween.
  49109. */
  49110. function getForBoolean () {
  49111. if (dataFrom === undefined) {
  49112. from[attribute] = false;
  49113. } else {
  49114. from[attribute] = strToBool(dataFrom);
  49115. }
  49116. from[attribute] = boolToNum(from[attribute]);
  49117. to[attribute] = boolToNum(strToBool(dataTo));
  49118. partialSetAttribute = function (value) {
  49119. el.setAttribute(attribute, !!value[attribute]);
  49120. };
  49121. }
  49122. /**
  49123. * Animating a color component
  49124. * Will convert a hex value to a THREE.Color
  49125. * Then converts to hex for the setAttribute
  49126. */
  49127. function getForColorComponent () {
  49128. from = new THREE.Color(dataFrom || el.getAttribute(attribute));
  49129. to = new THREE.Color(dataTo);
  49130. partialSetAttribute = function (value) {
  49131. if (attributeSplit.length > 1) {
  49132. el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));
  49133. }
  49134. el.setAttribute(attribute, rgbVectorToHex(value));
  49135. };
  49136. }
  49137. /**
  49138. * Animating a numbered attribute (e.g., opacity).
  49139. */
  49140. function getForNumber () {
  49141. if (dataFrom === undefined) { // dataFrom can be 0.
  49142. from[attribute] = parseFloat(el.getAttribute(attribute));
  49143. } else {
  49144. from[attribute] = parseFloat(dataFrom);
  49145. }
  49146. to[attribute] = parseFloat(dataTo);
  49147. partialSetAttribute = function (value) {
  49148. el.setAttribute(attribute, value[attribute]);
  49149. };
  49150. }
  49151. }
  49152. module.exports.getAnimationValues = getAnimationValues;
  49153. /**
  49154. * Converts string to bool.
  49155. *
  49156. * @param {string} str - `true` or `false`.
  49157. * @returns {bool}
  49158. */
  49159. function strToBool (str) {
  49160. if (str === 'true') { return true; }
  49161. return false;
  49162. }
  49163. /**
  49164. * Converts boolean to number.
  49165. *
  49166. * @param {bool}
  49167. * @returns {number}
  49168. */
  49169. function boolToNum (bool) {
  49170. return bool ? 1 : 0;
  49171. }
  49172. /**
  49173. * Converts a number 0-255 to hex
  49174. * @param {number} color number 0 - 255
  49175. * @returns {string} hex value of number bassed
  49176. */
  49177. function componentToHex (color) {
  49178. var hex = color.toString(16);
  49179. return hex.length === 1 ? '0' + hex : hex;
  49180. }
  49181. /**
  49182. * Clamps a number to 0-1
  49183. * Then converts that number to 0-255
  49184. * @param {number} color number 0 - 1
  49185. * @returns {number} color number 0 - 255
  49186. */
  49187. function convertToIntegerColor (color) {
  49188. return Math.floor(Math.min(Math.abs(color), 1) * 255);
  49189. }
  49190. /**
  49191. * Converts a rgb object into a hex string
  49192. * @param {object} color { r: 1, g: 1, b: 1 }
  49193. * @returns {string} hex value #ffffff
  49194. */
  49195. function rgbVectorToHex (color) {
  49196. return '#' + ['r', 'g', 'b'].map(function (prop) {
  49197. return componentToHex(convertToIntegerColor(color[prop]));
  49198. }).join('');
  49199. }
  49200. },{"../constants/animation":115,"../lib/three":173,"../utils/":195,"./a-node":123,"./a-register-element":124,"./schema":133,"@tweenjs/tween.js":1}],119:[function(_dereq_,module,exports){
  49201. var ANode = _dereq_('./a-node');
  49202. var bind = _dereq_('../utils/bind');
  49203. var debug = _dereq_('../utils/debug');
  49204. var registerElement = _dereq_('./a-register-element').registerElement;
  49205. var THREE = _dereq_('../lib/three');
  49206. var fileLoader = new THREE.FileLoader();
  49207. var warn = debug('core:a-assets:warn');
  49208. /**
  49209. * Asset management system. Handles blocking on asset loading.
  49210. */
  49211. module.exports = registerElement('a-assets', {
  49212. prototype: Object.create(ANode.prototype, {
  49213. createdCallback: {
  49214. value: function () {
  49215. this.isAssets = true;
  49216. this.fileLoader = fileLoader;
  49217. this.timeout = null;
  49218. }
  49219. },
  49220. attachedCallback: {
  49221. value: function () {
  49222. var self = this;
  49223. var i;
  49224. var loaded = [];
  49225. var mediaEl;
  49226. var mediaEls;
  49227. var imgEl;
  49228. var imgEls;
  49229. var timeout;
  49230. if (!this.parentNode.isScene) {
  49231. throw new Error('<a-assets> must be a child of a <a-scene>.');
  49232. }
  49233. // Wait for <img>s.
  49234. imgEls = this.querySelectorAll('img');
  49235. for (i = 0; i < imgEls.length; i++) {
  49236. imgEl = fixUpMediaElement(imgEls[i]);
  49237. loaded.push(new Promise(function (resolve, reject) {
  49238. // Set in cache because we won't be needing to call three.js loader if we have.
  49239. // a loaded media element.
  49240. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  49241. imgEl.onload = resolve;
  49242. imgEl.onerror = reject;
  49243. }));
  49244. }
  49245. // Wait for <audio>s and <video>s.
  49246. mediaEls = this.querySelectorAll('audio, video');
  49247. for (i = 0; i < mediaEls.length; i++) {
  49248. mediaEl = fixUpMediaElement(mediaEls[i]);
  49249. if (!mediaEl.src && !mediaEl.srcObject) {
  49250. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  49251. }
  49252. loaded.push(mediaElementLoaded(mediaEl));
  49253. }
  49254. // Trigger loaded for scene to start rendering.
  49255. Promise.all(loaded).then(bind(this.load, this));
  49256. // Timeout to start loading anyways.
  49257. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  49258. this.timeout = setTimeout(function () {
  49259. if (self.hasLoaded) { return; }
  49260. warn('Asset loading timed out in ', timeout, 'ms');
  49261. self.emit('timeout');
  49262. self.load();
  49263. }, timeout);
  49264. }
  49265. },
  49266. detachedCallback: {
  49267. value: function () {
  49268. if (this.timeout) { clearTimeout(this.timeout); }
  49269. }
  49270. },
  49271. load: {
  49272. value: function () {
  49273. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  49274. return el.isAssetItem && el.hasAttribute('src');
  49275. });
  49276. }
  49277. }
  49278. })
  49279. });
  49280. /**
  49281. * Preload using XHRLoader for any type of asset.
  49282. */
  49283. registerElement('a-asset-item', {
  49284. prototype: Object.create(ANode.prototype, {
  49285. createdCallback: {
  49286. value: function () {
  49287. this.data = null;
  49288. this.isAssetItem = true;
  49289. }
  49290. },
  49291. attachedCallback: {
  49292. value: function () {
  49293. var self = this;
  49294. var src = this.getAttribute('src');
  49295. fileLoader.setResponseType(
  49296. this.getAttribute('response-type') || inferResponseType(src));
  49297. fileLoader.load(src, function handleOnLoad (response) {
  49298. self.data = response;
  49299. /*
  49300. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  49301. previous one closes, the second request never finishes.
  49302. setTimeout finishes the first request and lets the logic triggered by load open
  49303. subsequent requests.
  49304. setTimeout can be removed once the fix for the bug below ships:
  49305. 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
  49306. */
  49307. setTimeout(function load () { ANode.prototype.load.call(self); });
  49308. }, function handleOnProgress (xhr) {
  49309. self.emit('progress', {
  49310. loadedBytes: xhr.loaded,
  49311. totalBytes: xhr.total,
  49312. xhr: xhr
  49313. });
  49314. }, function handleOnError (xhr) {
  49315. self.emit('error', {xhr: xhr});
  49316. });
  49317. }
  49318. }
  49319. })
  49320. });
  49321. /**
  49322. * Create a Promise that resolves once the media element has finished buffering.
  49323. *
  49324. * @param {Element} el - HTMLMediaElement.
  49325. * @returns {Promise}
  49326. */
  49327. function mediaElementLoaded (el) {
  49328. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  49329. return;
  49330. }
  49331. // If media specifies autoplay or preload, wait until media is completely buffered.
  49332. return new Promise(function (resolve, reject) {
  49333. if (el.readyState === 4) { return resolve(); } // Already loaded.
  49334. if (el.error) { return reject(); } // Error.
  49335. el.addEventListener('loadeddata', checkProgress, false);
  49336. el.addEventListener('progress', checkProgress, false);
  49337. el.addEventListener('error', reject, false);
  49338. function checkProgress () {
  49339. // Add up the seconds buffered.
  49340. var secondsBuffered = 0;
  49341. for (var i = 0; i < el.buffered.length; i++) {
  49342. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  49343. }
  49344. // Compare seconds buffered to media duration.
  49345. if (secondsBuffered >= el.duration) {
  49346. // Set in cache because we won't be needing to call three.js loader if we have.
  49347. // a loaded media element.
  49348. THREE.Cache.files[el.getAttribute('src')] = el;
  49349. resolve();
  49350. }
  49351. }
  49352. });
  49353. }
  49354. /**
  49355. * Automatically add attributes to media elements where convenient.
  49356. * crossorigin, playsinline.
  49357. */
  49358. function fixUpMediaElement (mediaEl) {
  49359. // Cross-origin.
  49360. var newMediaEl = setCrossOrigin(mediaEl);
  49361. // Plays inline for mobile.
  49362. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  49363. newMediaEl.setAttribute('playsinline', '');
  49364. newMediaEl.setAttribute('webkit-playsinline', '');
  49365. }
  49366. if (newMediaEl !== mediaEl) {
  49367. mediaEl.parentNode.appendChild(newMediaEl);
  49368. mediaEl.parentNode.removeChild(mediaEl);
  49369. }
  49370. return newMediaEl;
  49371. }
  49372. /**
  49373. * Automatically set `crossorigin` if not defined on the media element.
  49374. * If it is not defined, we must create and re-append a new media element <img> and
  49375. * have the browser re-request it with `crossorigin` set.
  49376. *
  49377. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  49378. * @returns {Element} Media element to be used to listen to for loaded events.
  49379. */
  49380. function setCrossOrigin (mediaEl) {
  49381. var newMediaEl;
  49382. var src;
  49383. // Already has crossorigin set.
  49384. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  49385. src = mediaEl.getAttribute('src');
  49386. if (src !== null) {
  49387. // Does not have protocol.
  49388. if (src.indexOf('://') === -1) { return mediaEl; }
  49389. // Determine if cross origin is actually needed.
  49390. if (extractDomain(src) === window.location.host) { return mediaEl; }
  49391. }
  49392. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  49393. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  49394. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  49395. mediaEl.crossOrigin = 'anonymous';
  49396. newMediaEl = mediaEl.cloneNode(true);
  49397. return newMediaEl;
  49398. }
  49399. /**
  49400. * Extract domain out of URL.
  49401. *
  49402. * @param {string} url
  49403. * @returns {string}
  49404. */
  49405. function extractDomain (url) {
  49406. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  49407. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  49408. // Find and remove port number.
  49409. return domain.split(':')[0];
  49410. }
  49411. /**
  49412. * Infer response-type attribute from src.
  49413. * Default is text(default XMLHttpRequest.responseType)
  49414. * but we use arraybuffer for .gltf and .glb files
  49415. * because of THREE.GLTFLoader specification.
  49416. *
  49417. * @param {string} src
  49418. * @returns {string}
  49419. */
  49420. function inferResponseType (src) {
  49421. var dotLastIndex = src.lastIndexOf('.');
  49422. if (dotLastIndex >= 0) {
  49423. var extension = src.slice(dotLastIndex, src.length);
  49424. if (extension === '.gltf' || extension === '.glb') {
  49425. return 'arraybuffer';
  49426. }
  49427. }
  49428. return 'text';
  49429. }
  49430. module.exports.inferResponseType = inferResponseType;
  49431. },{"../lib/three":173,"../utils/bind":189,"../utils/debug":191,"./a-node":123,"./a-register-element":124}],120:[function(_dereq_,module,exports){
  49432. var debug = _dereq_('../utils/debug');
  49433. var registerElement = _dereq_('./a-register-element').registerElement;
  49434. var warn = debug('core:cubemap:warn');
  49435. /**
  49436. * Cubemap element that handles validation and exposes list of URLs.
  49437. * Does not listen to updates.
  49438. */
  49439. module.exports = registerElement('a-cubemap', {
  49440. prototype: Object.create(window.HTMLElement.prototype, {
  49441. /**
  49442. * Calculates this.srcs.
  49443. */
  49444. attachedCallback: {
  49445. value: function () {
  49446. this.srcs = this.validate();
  49447. },
  49448. writable: window.debug
  49449. },
  49450. /**
  49451. * Checks for exactly six elements with [src].
  49452. * Does not check explicitly for <img>s in case user does not want
  49453. * prefetching.
  49454. *
  49455. * @returns {Array|null} - six URLs if valid, else null.
  49456. */
  49457. validate: {
  49458. value: function () {
  49459. var elements = this.querySelectorAll('[src]');
  49460. var i;
  49461. var srcs = [];
  49462. if (elements.length === 6) {
  49463. for (i = 0; i < elements.length; i++) {
  49464. srcs.push(elements[i].getAttribute('src'));
  49465. }
  49466. return srcs;
  49467. }
  49468. // Else if there are not six elements, throw a warning.
  49469. warn(
  49470. '<a-cubemap> did not contain exactly six elements each with a ' +
  49471. '`src` attribute.');
  49472. },
  49473. writable: window.debug
  49474. }
  49475. })
  49476. });
  49477. },{"../utils/debug":191,"./a-register-element":124}],121:[function(_dereq_,module,exports){
  49478. var ANode = _dereq_('./a-node');
  49479. var COMPONENTS = _dereq_('./component').components;
  49480. var registerElement = _dereq_('./a-register-element').registerElement;
  49481. var THREE = _dereq_('../lib/three');
  49482. var utils = _dereq_('../utils/');
  49483. var AEntity;
  49484. var debug = utils.debug('core:a-entity:debug');
  49485. var warn = utils.debug('core:a-entity:warn');
  49486. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49487. /**
  49488. * Entity is a container object that components are plugged into to comprise everything in
  49489. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  49490. *
  49491. * To be able to take components, the scene element inherits from the entity definition.
  49492. *
  49493. * @member {object} components - entity's currently initialized components.
  49494. * @member {object} object3D - three.js object.
  49495. * @member {array} states
  49496. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  49497. */
  49498. var proto = Object.create(ANode.prototype, {
  49499. defaultComponents: {
  49500. value: {
  49501. position: '',
  49502. rotation: '',
  49503. scale: '',
  49504. visible: ''
  49505. }
  49506. },
  49507. createdCallback: {
  49508. value: function () {
  49509. this.components = {};
  49510. // To avoid double initializations and infinite loops.
  49511. this.initializingComponents = {};
  49512. this.isEntity = true;
  49513. this.isPlaying = false;
  49514. this.object3D = new THREE.Group();
  49515. this.object3D.el = this;
  49516. this.object3DMap = {};
  49517. this.parentEl = null;
  49518. this.states = [];
  49519. }
  49520. },
  49521. /**
  49522. * Handle changes coming from the browser DOM inspector.
  49523. */
  49524. attributeChangedCallback: {
  49525. value: function (attr, oldVal, newVal) {
  49526. var component = this.components[attr];
  49527. // If the empty string is passed by the component initialization
  49528. // logic we ignore the component update.
  49529. if (component && component.justInitialized && newVal === '') {
  49530. delete component.justInitialized;
  49531. return;
  49532. }
  49533. // When a component is removed after calling el.removeAttribute('material')
  49534. if (!component && newVal === null) { return; }
  49535. this.setEntityAttribute(attr, oldVal, newVal);
  49536. }
  49537. },
  49538. /**
  49539. * Add to parent, load, play.
  49540. */
  49541. attachedCallback: {
  49542. value: function () {
  49543. var assetsEl; // Asset management system element.
  49544. var sceneEl = this.sceneEl;
  49545. var self = this; // Component.
  49546. this.addToParent();
  49547. // Don't .load() scene on attachedCallback.
  49548. if (this.isScene) { return; }
  49549. // Gracefully not error when outside of <a-scene> (e.g., tests).
  49550. if (!sceneEl) {
  49551. this.load();
  49552. return;
  49553. }
  49554. // Wait for asset management system to finish before loading.
  49555. assetsEl = sceneEl.querySelector('a-assets');
  49556. if (assetsEl && !assetsEl.hasLoaded) {
  49557. assetsEl.addEventListener('loaded', function () { self.load(); });
  49558. return;
  49559. }
  49560. this.load();
  49561. }
  49562. },
  49563. /**
  49564. * Tell parent to remove this element's object3D from its object3D.
  49565. * Do not call on scene element because that will cause a call to document.body.remove().
  49566. */
  49567. detachedCallback: {
  49568. value: function () {
  49569. var componentName;
  49570. if (!this.parentEl) { return; }
  49571. // Remove components.
  49572. for (componentName in this.components) { this.removeComponent(componentName); }
  49573. if (this.isScene) { return; }
  49574. this.removeFromParent();
  49575. ANode.prototype.detachedCallback.call(this);
  49576. // Remove cyclic reference.
  49577. this.object3D.el = null;
  49578. }
  49579. },
  49580. /**
  49581. * Apply mixin to component.
  49582. */
  49583. handleMixinUpdate: {
  49584. value: function (attrName) {
  49585. if (!attrName) {
  49586. this.updateComponents();
  49587. return;
  49588. }
  49589. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  49590. }
  49591. },
  49592. getObject3D: {
  49593. value: function (type) {
  49594. return this.object3DMap[type];
  49595. }
  49596. },
  49597. /**
  49598. * Set a THREE.Object3D into the map.
  49599. *
  49600. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  49601. * @param {object} obj - A THREE.Object3D.
  49602. */
  49603. setObject3D: {
  49604. value: function (type, obj) {
  49605. var oldObj;
  49606. var self = this;
  49607. if (!(obj instanceof THREE.Object3D)) {
  49608. throw new Error(
  49609. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  49610. 'THREE.Object3D.'
  49611. );
  49612. }
  49613. // Remove existing object of the type.
  49614. oldObj = this.getObject3D(type);
  49615. if (oldObj) { this.object3D.remove(oldObj); }
  49616. // Set references to A-Frame entity.
  49617. obj.el = this;
  49618. if (obj.children.length) {
  49619. obj.traverse(function bindEl (child) {
  49620. child.el = self;
  49621. });
  49622. }
  49623. // Add.
  49624. this.object3D.add(obj);
  49625. this.object3DMap[type] = obj;
  49626. this.emit('object3dset', {object: obj, type: type});
  49627. }
  49628. },
  49629. /**
  49630. * Remove object from scene and entity object3D map.
  49631. */
  49632. removeObject3D: {
  49633. value: function (type) {
  49634. var obj = this.getObject3D(type);
  49635. if (!obj) {
  49636. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  49637. return;
  49638. }
  49639. this.object3D.remove(obj);
  49640. delete this.object3DMap[type];
  49641. this.emit('object3dremove', {type: type});
  49642. }
  49643. },
  49644. /**
  49645. * Gets or creates an object3D of a given type.
  49646. *
  49647. * @param {string} type - Type of the object3D.
  49648. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  49649. * @returns {object}
  49650. */
  49651. getOrCreateObject3D: {
  49652. value: function (type, Constructor) {
  49653. var object3D = this.getObject3D(type);
  49654. if (!object3D && Constructor) {
  49655. object3D = new Constructor();
  49656. this.setObject3D(type, object3D);
  49657. }
  49658. return object3D;
  49659. }
  49660. },
  49661. /**
  49662. * Add child entity.
  49663. *
  49664. * @param {Element} el - Child entity.
  49665. */
  49666. add: {
  49667. value: function (el) {
  49668. if (!el.object3D) {
  49669. throw new Error("Trying to add an element that doesn't have an `object3D`");
  49670. }
  49671. this.object3D.add(el.object3D);
  49672. this.emit('child-attached', {el: el});
  49673. }
  49674. },
  49675. /**
  49676. * Tell parentNode to add this entity to itself.
  49677. */
  49678. addToParent: {
  49679. value: function () {
  49680. var parentNode = this.parentEl = this.parentNode;
  49681. // `!parentNode` check primarily for unit tests.
  49682. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  49683. parentNode.add(this);
  49684. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  49685. }
  49686. },
  49687. /**
  49688. * Tell parentNode to remove this entity from itself.
  49689. */
  49690. removeFromParent: {
  49691. value: function () {
  49692. var parentEl = this.parentEl;
  49693. this.parentEl.remove(this);
  49694. this.attachedToParent = false;
  49695. this.parentEl = this.parentNode = null;
  49696. parentEl.emit('child-detached', {el: this});
  49697. }
  49698. },
  49699. load: {
  49700. value: function () {
  49701. var self = this;
  49702. if (this.hasLoaded || !this.parentEl) { return; }
  49703. ANode.prototype.load.call(this, function entityLoadCallback () {
  49704. // Check if entity was detached while it was waiting to load.
  49705. if (!self.parentEl) { return; }
  49706. self.updateComponents();
  49707. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  49708. });
  49709. },
  49710. writable: window.debug
  49711. },
  49712. /**
  49713. * Remove child entity.
  49714. *
  49715. * @param {Element} el - Child entity.
  49716. */
  49717. remove: {
  49718. value: function (el) {
  49719. this.object3D.remove(el.object3D);
  49720. }
  49721. },
  49722. /**
  49723. * @returns {array} Direct children that are entities.
  49724. */
  49725. getChildEntities: {
  49726. value: function () {
  49727. var children = this.children;
  49728. var childEntities = [];
  49729. for (var i = 0; i < children.length; i++) {
  49730. var child = children[i];
  49731. if (child instanceof AEntity) {
  49732. childEntities.push(child);
  49733. }
  49734. }
  49735. return childEntities;
  49736. }
  49737. },
  49738. /**
  49739. * Initialize component.
  49740. *
  49741. * @param {string} attrName - Attribute name asociated to the component.
  49742. * @param {object} data - Component data
  49743. * @param {boolean} isDependency - True if the component is a dependency.
  49744. */
  49745. initComponent: {
  49746. value: function (attrName, data, isDependency) {
  49747. var component;
  49748. var componentInfo = attrName.split(MULTIPLE_COMPONENT_DELIMITER);
  49749. var componentId = componentInfo[1];
  49750. var componentName = componentInfo[0];
  49751. var isComponentDefined = checkComponentDefined(this, attrName) || data !== undefined;
  49752. // Not a registered component.
  49753. if (!COMPONENTS[componentName]) { return; }
  49754. // Component is not a dependency and is undefined.
  49755. // If a component is a dependency, then it is okay to have no data.
  49756. if (!isComponentDefined && !isDependency) { return; }
  49757. // Component already initialized.
  49758. if (attrName in this.components) { return; }
  49759. // Initialize dependencies first
  49760. this.initComponentDependencies(componentName);
  49761. // If component name has an id we check component type multiplic
  49762. if (componentId && !COMPONENTS[componentName].multiple) {
  49763. throw new Error('Trying to initialize multiple ' +
  49764. 'components of type `' + componentName +
  49765. '`. There can only be one component of this type per entity.');
  49766. }
  49767. component = new COMPONENTS[componentName].Component(this, data, componentId);
  49768. if (this.isPlaying) { component.play(); }
  49769. // Components are reflected in the DOM as attributes but the state is not shown
  49770. // hence we set the attribute to empty string.
  49771. // The flag justInitialized is for attributeChangedCallback to not overwrite
  49772. // the component with the empty string.
  49773. if (!this.hasAttribute(attrName)) {
  49774. component.justInitialized = true;
  49775. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  49776. }
  49777. debug('Component initialized: %s', attrName);
  49778. },
  49779. writable: window.debug
  49780. },
  49781. /**
  49782. * Initialize dependencies of a component.
  49783. *
  49784. * @param {string} name - Root component name.
  49785. */
  49786. initComponentDependencies: {
  49787. value: function (name) {
  49788. var self = this;
  49789. var component = COMPONENTS[name];
  49790. var dependencies;
  49791. var i;
  49792. // Not a component.
  49793. if (!component) { return; }
  49794. // No dependencies.
  49795. dependencies = COMPONENTS[name].dependencies;
  49796. if (!dependencies) { return; }
  49797. // Initialize dependencies.
  49798. for (i = 0; i < dependencies.length; i++) {
  49799. // Call getAttribute to initialize the data from the DOM.
  49800. self.initComponent(
  49801. dependencies[i],
  49802. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  49803. true
  49804. );
  49805. }
  49806. }
  49807. },
  49808. removeComponent: {
  49809. value: function (name) {
  49810. var component;
  49811. var isDefault;
  49812. var isMixedIn;
  49813. // Don't remove default or mixed-in components.
  49814. isDefault = name in this.defaultComponents;
  49815. isMixedIn = isComponentMixedIn(name, this.mixinEls);
  49816. if (isDefault || isMixedIn) { return; }
  49817. component = this.components[name];
  49818. if (!component) { return; }
  49819. // Wait for component to initialize.
  49820. if (!component.initialized) {
  49821. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  49822. if (evt.detail.name !== name) { return; }
  49823. this.removeComponent(name);
  49824. this.removeEventListener('componentinitialized', tryRemoveLater);
  49825. });
  49826. return;
  49827. }
  49828. component.pause();
  49829. component.remove();
  49830. delete this.components[name];
  49831. this.emit('componentremoved', component.evtDetail);
  49832. },
  49833. writable: window.debug
  49834. },
  49835. /**
  49836. * Initialize or update all components.
  49837. * Build data using initial components, defined attributes, mixins, and defaults.
  49838. * Update default components before the rest.
  49839. *
  49840. * @member {function} getExtraComponents - Can be implemented to include component data
  49841. * from other sources (e.g., implemented by primitives).
  49842. */
  49843. updateComponents: {
  49844. value: (function () {
  49845. var componentsToUpdate = {};
  49846. return function () {
  49847. var data;
  49848. var extraComponents;
  49849. var i;
  49850. var name;
  49851. if (!this.hasLoaded) { return; }
  49852. // Gather mixin-defined components.
  49853. for (i = 0; i < this.mixinEls.length; i++) {
  49854. for (name in this.mixinEls[i].componentCache) {
  49855. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49856. }
  49857. }
  49858. // Gather from extra initial component data if defined (e.g., primitives).
  49859. if (this.getExtraComponents) {
  49860. extraComponents = this.getExtraComponents();
  49861. for (name in extraComponents) {
  49862. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49863. }
  49864. }
  49865. // Gather entity-defined components.
  49866. for (i = 0; i < this.attributes.length; ++i) {
  49867. name = this.attributes[i].name;
  49868. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49869. }
  49870. // Initialze or update default components first.
  49871. for (name in this.defaultComponents) {
  49872. data = mergeComponentData(this.getDOMAttribute(name),
  49873. extraComponents && extraComponents[name]);
  49874. this.updateComponent(name, data);
  49875. delete componentsToUpdate[name];
  49876. }
  49877. // Initialize or update rest of components.
  49878. for (name in componentsToUpdate) {
  49879. data = mergeComponentData(this.getDOMAttribute(name),
  49880. extraComponents && extraComponents[name]);
  49881. this.updateComponent(name, data);
  49882. delete componentsToUpdate[name];
  49883. }
  49884. };
  49885. })(),
  49886. writable: window.debug
  49887. },
  49888. /**
  49889. * Initialize, update, or remove a single component.
  49890. *
  49891. * When initializing, we set the component on `this.components`.
  49892. *
  49893. * @param {string} attr - Component name.
  49894. * @param {object} attrValue - Value of the DOM attribute.
  49895. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  49896. */
  49897. updateComponent: {
  49898. value: function (attr, attrValue, clobber) {
  49899. var component = this.components[attr];
  49900. var isDefault = attr in this.defaultComponents;
  49901. if (component) {
  49902. // Remove component.
  49903. if (attrValue === null && !isDefault) {
  49904. this.removeComponent(attr);
  49905. return;
  49906. }
  49907. // Component already initialized. Update component.
  49908. component.updateProperties(attrValue, clobber);
  49909. return;
  49910. }
  49911. // Component not yet initialized. Initialize component.
  49912. this.initComponent(attr, attrValue, false);
  49913. }
  49914. },
  49915. /**
  49916. * If `attr` is a component name, detach the component from the entity.
  49917. *
  49918. * If `propertyName` is given, reset the component property value to its default.
  49919. *
  49920. * @param {string} attr - Attribute name, which could also be a component name.
  49921. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  49922. */
  49923. removeAttribute: {
  49924. value: function (attr, propertyName) {
  49925. var component = this.components[attr];
  49926. // Remove component.
  49927. if (component && propertyName === undefined) {
  49928. this.setEntityAttribute(attr, undefined, null);
  49929. // Do not remove the component from the DOM if default component.
  49930. if (this.components[attr]) { return; }
  49931. }
  49932. // Reset component property value.
  49933. if (component && propertyName !== undefined) {
  49934. component.resetProperty(propertyName);
  49935. return;
  49936. }
  49937. // Remove mixins.
  49938. if (attr === 'mixin') {
  49939. this.mixinUpdate('');
  49940. }
  49941. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  49942. }
  49943. },
  49944. /**
  49945. * Start dynamic behavior associated with entity such as dynamic components and animations.
  49946. * Tell all children entities to also play.
  49947. */
  49948. play: {
  49949. value: function () {
  49950. var entities;
  49951. var i;
  49952. var key;
  49953. // Already playing.
  49954. if (this.isPlaying || !this.hasLoaded) { return; }
  49955. this.isPlaying = true;
  49956. // Wake up all components.
  49957. for (key in this.components) { this.components[key].play(); }
  49958. // Tell all child entities to play.
  49959. entities = this.getChildEntities();
  49960. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  49961. this.emit('play');
  49962. },
  49963. writable: true
  49964. },
  49965. /**
  49966. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  49967. * Tell all children entities to also pause.
  49968. */
  49969. pause: {
  49970. value: function () {
  49971. var entities;
  49972. var i;
  49973. var key;
  49974. if (!this.isPlaying) { return; }
  49975. this.isPlaying = false;
  49976. // Sleep all components.
  49977. for (key in this.components) { this.components[key].pause(); }
  49978. // Tell all child entities to pause.
  49979. entities = this.getChildEntities();
  49980. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  49981. this.emit('pause');
  49982. },
  49983. writable: true
  49984. },
  49985. /**
  49986. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  49987. *
  49988. * @param {string} attr
  49989. * @param {string} oldVal
  49990. * @param {string|object} newVal
  49991. */
  49992. setEntityAttribute: {
  49993. value: function (attr, oldVal, newVal) {
  49994. if (COMPONENTS[attr] || this.components[attr]) {
  49995. this.updateComponent(attr, newVal);
  49996. return;
  49997. }
  49998. if (attr === 'mixin') {
  49999. this.mixinUpdate(newVal, oldVal);
  50000. return;
  50001. }
  50002. }
  50003. },
  50004. mixinUpdate: {
  50005. value: function (newMixins, oldMixins) {
  50006. oldMixins = oldMixins || this.getAttribute('mixin');
  50007. this.updateMixins(newMixins, oldMixins);
  50008. this.updateComponents();
  50009. }
  50010. },
  50011. /**
  50012. * setAttribute can:
  50013. *
  50014. * 1. Set a single property of a multi-property component.
  50015. * 2. Set multiple properties of a multi-property component.
  50016. * 3. Replace properties of a multi-property component.
  50017. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  50018. *
  50019. * @param {string} attrName - Component or attribute name.
  50020. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  50021. * object of properties.
  50022. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  50023. * it is a boolean indicating whether to clobber previous values (defaults to false).
  50024. */
  50025. setAttribute: {
  50026. value: function (attrName, arg1, arg2) {
  50027. var newAttrValue;
  50028. var clobber;
  50029. var componentName;
  50030. var delimiterIndex;
  50031. var isDebugMode;
  50032. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  50033. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  50034. // Not a component. Normal set attribute.
  50035. if (!COMPONENTS[componentName]) {
  50036. ANode.prototype.setAttribute.call(this, attrName, arg1);
  50037. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  50038. return;
  50039. }
  50040. // Initialize component first if not yet initialized.
  50041. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  50042. this.updateComponent(attrName,
  50043. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  50044. }
  50045. // Determine new attributes from the arguments
  50046. if (typeof arg2 !== 'undefined' &&
  50047. typeof arg1 === 'string' &&
  50048. arg1.length > 0 &&
  50049. typeof utils.styleParser.parse(arg1) === 'string') {
  50050. // Update a single property of a multi-property component
  50051. newAttrValue = {};
  50052. newAttrValue[arg1] = arg2;
  50053. clobber = false;
  50054. } else {
  50055. // Update with a value, object, or CSS-style property string, with the possiblity
  50056. // of clobbering previous values.
  50057. newAttrValue = arg1;
  50058. clobber = (arg2 === true);
  50059. }
  50060. // Update component
  50061. this.updateComponent(attrName, newAttrValue, clobber);
  50062. // In debug mode, write component data up to the DOM.
  50063. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  50064. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  50065. },
  50066. writable: window.debug
  50067. },
  50068. /**
  50069. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  50070. *
  50071. * @param {bool} recursive - Also flushToDOM on the children.
  50072. **/
  50073. flushToDOM: {
  50074. value: function (recursive) {
  50075. var components = this.components;
  50076. var defaultComponents = this.defaultComponents;
  50077. var child;
  50078. var children = this.children;
  50079. var i;
  50080. var key;
  50081. // Flush entity's components to DOM.
  50082. for (key in components) {
  50083. components[key].flushToDOM(key in defaultComponents);
  50084. }
  50085. // Recurse.
  50086. if (!recursive) { return; }
  50087. for (i = 0; i < children.length; ++i) {
  50088. child = children[i];
  50089. if (!child.flushToDOM) { continue; }
  50090. child.flushToDOM(recursive);
  50091. }
  50092. }
  50093. },
  50094. /**
  50095. * If `attr` is a component, returns ALL component data including applied mixins and
  50096. * defaults.
  50097. *
  50098. * If `attr` is not a component, fall back to HTML getAttribute.
  50099. *
  50100. * @param {string} attr
  50101. * @returns {object|string} Object if component, else string.
  50102. */
  50103. getAttribute: {
  50104. value: function (attr) {
  50105. // If component, return component data.
  50106. var component = this.components[attr];
  50107. if (component) { return component.data; }
  50108. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  50109. },
  50110. writable: window.debug
  50111. },
  50112. /**
  50113. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  50114. * what `getAttribute` is now. Now legacy code.
  50115. *
  50116. * @param {string} attr
  50117. * @returns {object|string} Object if component, else string.
  50118. */
  50119. getComputedAttribute: {
  50120. value: function (attr) {
  50121. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  50122. return this.getAttribute(attr);
  50123. }
  50124. },
  50125. /**
  50126. * If `attr` is a component, returns JUST the component data defined on the entity.
  50127. * Like a partial version of `getComputedAttribute` as returned component data
  50128. * does not include applied mixins or defaults.
  50129. *
  50130. * If `attr` is not a component, fall back to HTML getAttribute.
  50131. *
  50132. * @param {string} attr
  50133. * @returns {object|string} Object if component, else string.
  50134. */
  50135. getDOMAttribute: {
  50136. value: function (attr) {
  50137. // If cached value exists, return partial component data.
  50138. var component = this.components[attr];
  50139. if (component) { return component.attrValue; }
  50140. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  50141. },
  50142. writable: window.debug
  50143. },
  50144. addState: {
  50145. value: function (state) {
  50146. if (this.is(state)) { return; }
  50147. this.states.push(state);
  50148. this.emit('stateadded', state);
  50149. }
  50150. },
  50151. removeState: {
  50152. value: function (state) {
  50153. var stateIndex = this.states.indexOf(state);
  50154. if (stateIndex === -1) { return; }
  50155. this.states.splice(stateIndex, 1);
  50156. this.emit('stateremoved', state);
  50157. }
  50158. },
  50159. /**
  50160. * Checks if the element is in a given state. e.g. el.is('alive');
  50161. * @type {string} state - Name of the state we want to check
  50162. */
  50163. is: {
  50164. value: function (state) {
  50165. return this.states.indexOf(state) !== -1;
  50166. }
  50167. }
  50168. });
  50169. /**
  50170. * Check if a component is *defined* for an entity, including defaults and mixins.
  50171. * Does not check whether the component has been *initialized* for an entity.
  50172. *
  50173. * @param {string} el - Entity.
  50174. * @param {string} name - Component name.
  50175. * @returns {boolean}
  50176. */
  50177. function checkComponentDefined (el, name) {
  50178. // Check if default components contain the component.
  50179. if (el.defaultComponents[name] !== undefined) { return true; }
  50180. // Check if element contains the component.
  50181. if (el.components[name] && el.components[name].attrValue) { return true; }
  50182. return isComponentMixedIn(name, el.mixinEls);
  50183. }
  50184. /**
  50185. * Check if any mixins contains a component.
  50186. *
  50187. * @param {string} name - Component name.
  50188. * @param {array} mixinEls - Array of <a-mixin>s.
  50189. */
  50190. function isComponentMixedIn (name, mixinEls) {
  50191. var i;
  50192. var inMixin = false;
  50193. for (i = 0; i < mixinEls.length; ++i) {
  50194. inMixin = mixinEls[i].hasAttribute(name);
  50195. if (inMixin) { break; }
  50196. }
  50197. return inMixin;
  50198. }
  50199. /**
  50200. * Given entity defined value, merge in extra data if necessary.
  50201. * Handle both single and multi-property components.
  50202. *
  50203. * @param {string} attrValue - Entity data.
  50204. * @param extraData - Entity data from another source to merge in.
  50205. */
  50206. function mergeComponentData (attrValue, extraData) {
  50207. // Extra data not defined, just return attrValue.
  50208. if (!extraData) { return attrValue; }
  50209. // Merge multi-property data.
  50210. if (extraData.constructor === Object) {
  50211. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  50212. }
  50213. // Return data, precendence to the defined value.
  50214. return attrValue || extraData;
  50215. }
  50216. function isComponent (componentName) {
  50217. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  50218. componentName = componentName.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  50219. }
  50220. if (!COMPONENTS[componentName]) { return false; }
  50221. return true;
  50222. }
  50223. AEntity = registerElement('a-entity', {prototype: proto});
  50224. module.exports = AEntity;
  50225. },{"../lib/three":173,"../utils/":195,"./a-node":123,"./a-register-element":124,"./component":125}],122:[function(_dereq_,module,exports){
  50226. var ANode = _dereq_('./a-node');
  50227. var registerElement = _dereq_('./a-register-element').registerElement;
  50228. var components = _dereq_('./component').components;
  50229. var MULTIPLE_COMPONENT_DELIMITER = '__';
  50230. /**
  50231. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  50232. * are component names and the values are already parsed by the component.
  50233. */
  50234. module.exports = registerElement('a-mixin', {
  50235. prototype: Object.create(ANode.prototype, {
  50236. createdCallback: {
  50237. value: function () {
  50238. this.componentCache = {};
  50239. this.id = this.getAttribute('id');
  50240. }
  50241. },
  50242. attributeChangedCallback: {
  50243. value: function (attr, oldVal, newVal) {
  50244. this.cacheAttribute(attr, newVal);
  50245. }
  50246. },
  50247. attachedCallback: {
  50248. value: function () {
  50249. this.sceneEl = this.closestScene();
  50250. this.cacheAttributes();
  50251. this.updateEntities();
  50252. this.load();
  50253. }
  50254. },
  50255. /**
  50256. * setAttribute that parses and caches component values.
  50257. */
  50258. setAttribute: {
  50259. value: function (attr, value) {
  50260. this.cacheAttribute(attr, value);
  50261. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  50262. }
  50263. },
  50264. /**
  50265. * If `attr` is a component, then parse the value using the schema and store it.
  50266. */
  50267. cacheAttribute: {
  50268. value: function (attr, value) {
  50269. var componentName = attr.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  50270. var component = components[componentName];
  50271. if (!component) { return; }
  50272. if (value === undefined) {
  50273. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  50274. }
  50275. this.componentCache[attr] = component.parseAttrValueForCache(value);
  50276. }
  50277. },
  50278. /**
  50279. * If `attr` is a component, then grab pre-parsed value from the cache.
  50280. * Else do a normal getAttribute.
  50281. */
  50282. getAttribute: {
  50283. value: function (attr) {
  50284. return this.componentCache[attr] ||
  50285. window.HTMLElement.prototype.getAttribute.call(this, attr);
  50286. }
  50287. },
  50288. /**
  50289. * Parse and cache every component defined on the mixin.
  50290. */
  50291. cacheAttributes: {
  50292. value: function () {
  50293. var attributes = this.attributes;
  50294. var attrName;
  50295. var i;
  50296. for (i = 0; i < attributes.length; i++) {
  50297. attrName = attributes[i].name;
  50298. this.cacheAttribute(attrName);
  50299. }
  50300. }
  50301. },
  50302. /**
  50303. * For entities that already have been loaded by the time the mixin was attached, tell
  50304. * those entities to register the mixin and refresh their component data.
  50305. */
  50306. updateEntities: {
  50307. value: function () {
  50308. if (!this.sceneEl) { return; }
  50309. var entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  50310. for (var i = 0; i < entities.length; i++) {
  50311. var entity = entities[i];
  50312. if (!entity.hasLoaded) { continue; }
  50313. entity.registerMixin(this.id);
  50314. Object.keys(this.componentCache).forEach(function updateComponent (componentName) {
  50315. entity.updateComponent(componentName);
  50316. });
  50317. }
  50318. }
  50319. }
  50320. })
  50321. });
  50322. },{"./a-node":123,"./a-register-element":124,"./component":125}],123:[function(_dereq_,module,exports){
  50323. /* global MutationObserver */
  50324. var registerElement = _dereq_('./a-register-element').registerElement;
  50325. var isNode = _dereq_('./a-register-element').isNode;
  50326. var utils = _dereq_('../utils/');
  50327. var bind = utils.bind;
  50328. var warn = utils.debug('core:a-node:warn');
  50329. /**
  50330. * Base class for A-Frame that manages loading of objects.
  50331. *
  50332. * Nodes can be modified using mixins.
  50333. * Nodes emit a `loaded` event when they and their children have initialized.
  50334. */
  50335. module.exports = registerElement('a-node', {
  50336. prototype: Object.create(window.HTMLElement.prototype, {
  50337. createdCallback: {
  50338. value: function () {
  50339. this.hasLoaded = false;
  50340. this.isNode = true;
  50341. this.mixinEls = [];
  50342. this.mixinObservers = {};
  50343. },
  50344. writable: window.debug
  50345. },
  50346. attachedCallback: {
  50347. value: function () {
  50348. var mixins;
  50349. this.sceneEl = this.closestScene();
  50350. if (!this.sceneEl) {
  50351. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  50352. 'scene. Append this element to `<a-scene>` instead.');
  50353. }
  50354. this.hasLoaded = false;
  50355. this.emit('nodeready', {}, false);
  50356. mixins = this.getAttribute('mixin');
  50357. if (mixins) { this.updateMixins(mixins); }
  50358. },
  50359. writable: window.debug
  50360. },
  50361. attributeChangedCallback: {
  50362. value: function (attr, oldVal, newVal) {
  50363. if (attr === 'mixin') { this.updateMixins(newVal, oldVal); }
  50364. }
  50365. },
  50366. /**
  50367. * Returns the first scene by traversing up the tree starting from and
  50368. * including receiver element.
  50369. */
  50370. closestScene: {
  50371. value: function closest () {
  50372. var element = this;
  50373. while (element) {
  50374. if (element.isScene) { break; }
  50375. element = element.parentElement;
  50376. }
  50377. return element;
  50378. }
  50379. },
  50380. /**
  50381. * Returns first element matching a selector by traversing up the tree starting
  50382. * from and including receiver element.
  50383. *
  50384. * @param {string} selector - Selector of element to find.
  50385. */
  50386. closest: {
  50387. value: function closest (selector) {
  50388. var matches = this.matches || this.mozMatchesSelector ||
  50389. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  50390. var element = this;
  50391. while (element) {
  50392. if (matches.call(element, selector)) { break; }
  50393. element = element.parentElement;
  50394. }
  50395. return element;
  50396. }
  50397. },
  50398. detachedCallback: {
  50399. value: function () {
  50400. this.hasLoaded = false;
  50401. }
  50402. },
  50403. /**
  50404. * Wait for children to load, if any.
  50405. * Then emit `loaded` event and set `hasLoaded`.
  50406. */
  50407. load: {
  50408. value: function (cb, childFilter) {
  50409. var children;
  50410. var childrenLoaded;
  50411. var self = this;
  50412. if (this.hasLoaded) { return; }
  50413. // Default to waiting for all nodes.
  50414. childFilter = childFilter || isNode;
  50415. // Wait for children to load (if any), then load.
  50416. children = this.getChildren();
  50417. childrenLoaded = children.filter(childFilter).map(function (child) {
  50418. return new Promise(function waitForLoaded (resolve) {
  50419. if (child.hasLoaded) { return resolve(); }
  50420. child.addEventListener('loaded', resolve);
  50421. });
  50422. });
  50423. Promise.all(childrenLoaded).then(function emitLoaded () {
  50424. self.hasLoaded = true;
  50425. if (cb) { cb(); }
  50426. self.emit('loaded', undefined, false);
  50427. });
  50428. },
  50429. writable: true
  50430. },
  50431. getChildren: {
  50432. value: function () {
  50433. return Array.prototype.slice.call(this.children, 0);
  50434. }
  50435. },
  50436. /**
  50437. * Remove old mixins and mixin listeners.
  50438. * Add new mixins and mixin listeners.
  50439. */
  50440. updateMixins: {
  50441. value: function (newMixins, oldMixins) {
  50442. var newMixinIds = newMixins ? newMixins.trim().split(/\s+/) : [];
  50443. var oldMixinIds = oldMixins ? oldMixins.trim().split(/\s+/) : [];
  50444. // Unregister old mixins.
  50445. oldMixinIds.filter(function (i) {
  50446. return newMixinIds.indexOf(i) < 0;
  50447. }).forEach(bind(this.unregisterMixin, this));
  50448. // Register new mixins.
  50449. this.mixinEls = [];
  50450. newMixinIds.forEach(bind(this.registerMixin, this));
  50451. }
  50452. },
  50453. registerMixin: {
  50454. value: function (mixinId) {
  50455. if (!this.sceneEl) { return; }
  50456. var mixinEl = this.sceneEl.querySelector('a-mixin#' + mixinId);
  50457. if (!mixinEl) { return; }
  50458. this.attachMixinListener(mixinEl);
  50459. this.mixinEls.push(mixinEl);
  50460. }
  50461. },
  50462. setAttribute: {
  50463. value: function (attr, newValue) {
  50464. if (attr === 'mixin') { this.updateMixins(newValue); }
  50465. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  50466. }
  50467. },
  50468. unregisterMixin: {
  50469. value: function (mixinId) {
  50470. var mixinEls = this.mixinEls;
  50471. var mixinEl;
  50472. var i;
  50473. for (i = 0; i < mixinEls.length; ++i) {
  50474. mixinEl = mixinEls[i];
  50475. if (mixinId === mixinEl.id) {
  50476. mixinEls.splice(i, 1);
  50477. break;
  50478. }
  50479. }
  50480. this.removeMixinListener(mixinId);
  50481. }
  50482. },
  50483. removeMixinListener: {
  50484. value: function (mixinId) {
  50485. var observer = this.mixinObservers[mixinId];
  50486. if (!observer) { return; }
  50487. observer.disconnect();
  50488. this.mixinObservers[mixinId] = null;
  50489. }
  50490. },
  50491. attachMixinListener: {
  50492. value: function (mixinEl) {
  50493. var self = this;
  50494. var mixinId = mixinEl.id;
  50495. var currentObserver = this.mixinObservers[mixinId];
  50496. if (!mixinEl) { return; }
  50497. if (currentObserver) { return; }
  50498. var observer = new MutationObserver(function (mutations) {
  50499. var attr = mutations[0].attributeName;
  50500. self.handleMixinUpdate(attr);
  50501. });
  50502. var config = { attributes: true };
  50503. observer.observe(mixinEl, config);
  50504. this.mixinObservers[mixinId] = observer;
  50505. }
  50506. },
  50507. handleMixinUpdate: {
  50508. value: function () { /* no-op */ }
  50509. },
  50510. /**
  50511. * Emit a DOM event.
  50512. *
  50513. * @param {string} name - Name of event.
  50514. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  50515. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  50516. * @param {object} [extraData] - Extra data to pass to the event, if any.
  50517. */
  50518. emit: {
  50519. value: function (name, detail, bubbles, extraData) {
  50520. var data;
  50521. var self = this;
  50522. if (bubbles === undefined) { bubbles = true; }
  50523. data = {bubbles: !!bubbles, detail: detail};
  50524. if (extraData) { utils.extend(data, extraData); }
  50525. return utils.fireEvent(self, name, data);
  50526. },
  50527. writable: window.debug
  50528. },
  50529. /**
  50530. * Return a closure that emits a DOM event.
  50531. *
  50532. * @param {String} name
  50533. * Name of event (use a space-delimited string for multiple events).
  50534. * @param {Object} detail
  50535. * Custom data (optional) to pass as `detail` if the event is to
  50536. * be a `CustomEvent`.
  50537. * @param {Boolean} bubbles
  50538. * Whether the event should be bubble.
  50539. */
  50540. emitter: {
  50541. value: function (name, detail, bubbles) {
  50542. var self = this;
  50543. return function () {
  50544. self.emit(name, detail, bubbles);
  50545. };
  50546. }
  50547. }
  50548. })
  50549. });
  50550. },{"../utils/":195,"./a-register-element":124}],124:[function(_dereq_,module,exports){
  50551. /*
  50552. ------------------------------------------------------------
  50553. ------------- WARNING WARNING WARNING WARNING --------------
  50554. ------------------------------------------------------------
  50555. This module wraps registerElement to deal with components that inherit from
  50556. `ANode` and `AEntity`. It's a pass through in any other case.
  50557. It wraps some of the prototype methods of the created element to make sure
  50558. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  50559. are also invoked. The method in the base prototype is always called before the one
  50560. in the derived prototype.
  50561. */
  50562. // Polyfill `document.registerElement`.
  50563. _dereq_('document-register-element');
  50564. var ANode; // Must declare before AEntity. Initialized at the bottom.
  50565. var AEntity;
  50566. var knownTags = module.exports.knownTags = {};
  50567. function addTagName (tagName) {
  50568. knownTags[tagName.toLowerCase()] = true;
  50569. }
  50570. /**
  50571. * Return whether the element type is one of our known registered ones.
  50572. *
  50573. * @param {string} node - The name of the tag to register.
  50574. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  50575. */
  50576. module.exports.isNode = function (node) {
  50577. return node.tagName.toLowerCase() in knownTags || node.isNode;
  50578. };
  50579. /**
  50580. * @param {string} tagName - The name of the tag to register.
  50581. * @param {object} obj - The prototype of the new element.
  50582. * @returns {object} The prototype of the new element.
  50583. */
  50584. module.exports.registerElement = function (tagName, obj) {
  50585. var proto = Object.getPrototypeOf(obj.prototype);
  50586. var newObj = obj;
  50587. var isANode = ANode && proto === ANode.prototype;
  50588. var isAEntity = AEntity && proto === AEntity.prototype;
  50589. if (isANode || isAEntity) { addTagName(tagName); }
  50590. // Wrap if element inherits from `ANode`.
  50591. if (isANode) {
  50592. newObj = wrapANodeMethods(obj.prototype);
  50593. newObj = {prototype: Object.create(proto, newObj)};
  50594. }
  50595. // Wrap if element inherits from `AEntity`.
  50596. if (isAEntity) {
  50597. newObj = wrapAEntityMethods(obj.prototype);
  50598. newObj = {prototype: Object.create(proto, newObj)};
  50599. }
  50600. return document.registerElement(tagName, newObj);
  50601. };
  50602. /**
  50603. * Wrap some obj methods to call those on `ANode` base prototype.
  50604. *
  50605. * @param {object} obj - Object that contains the methods that will be wrapped.
  50606. * @return {object} An object with the same properties as the input parameter but
  50607. * with some of methods wrapped.
  50608. */
  50609. function wrapANodeMethods (obj) {
  50610. var newObj = {};
  50611. var ANodeMethods = [
  50612. 'attachedCallback',
  50613. 'attributeChangedCallback',
  50614. 'createdCallback'
  50615. ];
  50616. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50617. copyProperties(obj, newObj);
  50618. return newObj;
  50619. }
  50620. /**
  50621. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  50622. *
  50623. * @param {object} obj - The objects that contains the methods that will be wrapped.
  50624. * @return {object} - An object with the same properties as the input parameter but
  50625. * with some of methods wrapped.
  50626. */
  50627. function wrapAEntityMethods (obj) {
  50628. var newObj = {};
  50629. var ANodeMethods = [
  50630. 'attachedCallback',
  50631. 'attributeChangedCallback',
  50632. 'createdCallback'
  50633. ];
  50634. var AEntityMethods = [
  50635. 'attachedCallback',
  50636. 'attributeChangedCallback',
  50637. 'createdCallback',
  50638. 'detachedCallback'
  50639. ];
  50640. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50641. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  50642. // Copies the remaining properties into the new object.
  50643. copyProperties(obj, newObj);
  50644. return newObj;
  50645. }
  50646. /**
  50647. * Wrap a list a methods to ensure that those in the base prototype are called
  50648. * before the derived one.
  50649. *
  50650. * @param {object} targetObj - Object that will contain the wrapped methods.
  50651. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  50652. * @param {object} derivedObject - Object that inherits from the baseObj.
  50653. * @param {object} baseObj - Object that derivedObj inherits from.
  50654. */
  50655. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  50656. methodList.forEach(function (methodName) {
  50657. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  50658. });
  50659. }
  50660. module.exports.wrapMethods = wrapMethods;
  50661. /**
  50662. * Wrap one method to ensure that the one in the base prototype is called before
  50663. * the one in the derived one.
  50664. *
  50665. * @param {object} obj - Object that will contain the wrapped method.
  50666. * @param {string} methodName - The name of the method that will be wrapped.
  50667. * @param {object} derivedObject - Object that inherits from the baseObj.
  50668. * @param {object} baseObj - Object that derivedObj inherits from.
  50669. */
  50670. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  50671. var derivedMethod = derivedObj[methodName];
  50672. var baseMethod = baseObj[methodName];
  50673. // Derived prototype does not define method, no need to wrap.
  50674. if (!derivedMethod || !baseMethod) { return; }
  50675. // Derived prototype doesn't override the one in the base one, no need to wrap.
  50676. if (derivedMethod === baseMethod) { return; }
  50677. // Wrap to ensure the base method is called before the one in the derived prototype.
  50678. obj[methodName] = {
  50679. value: function wrappedMethod () {
  50680. baseMethod.apply(this, arguments);
  50681. return derivedMethod.apply(this, arguments);
  50682. },
  50683. writable: window.debug
  50684. };
  50685. }
  50686. /**
  50687. * It copies the properties from source to destination object if they don't
  50688. * exist already.
  50689. *
  50690. * @param {object} source - The object where properties are copied from.
  50691. * @param {type} destination - The object where properties are copied to.
  50692. */
  50693. function copyProperties (source, destination) {
  50694. var props = Object.getOwnPropertyNames(source);
  50695. props.forEach(function (prop) {
  50696. var desc;
  50697. if (!destination[prop]) {
  50698. desc = Object.getOwnPropertyDescriptor(source, prop);
  50699. destination[prop] = {value: source[prop], writable: desc.writable};
  50700. }
  50701. });
  50702. }
  50703. ANode = _dereq_('./a-node');
  50704. AEntity = _dereq_('./a-entity');
  50705. },{"./a-entity":121,"./a-node":123,"document-register-element":11}],125:[function(_dereq_,module,exports){
  50706. /* global Node */
  50707. var schema = _dereq_('./schema');
  50708. var scenes = _dereq_('./scene/scenes');
  50709. var systems = _dereq_('./system');
  50710. var utils = _dereq_('../utils/');
  50711. var components = module.exports.components = {}; // Keep track of registered components.
  50712. var parseProperties = schema.parseProperties;
  50713. var parseProperty = schema.parseProperty;
  50714. var processSchema = schema.process;
  50715. var isSingleProp = schema.isSingleProperty;
  50716. var stringifyProperties = schema.stringifyProperties;
  50717. var stringifyProperty = schema.stringifyProperty;
  50718. var styleParser = utils.styleParser;
  50719. var warn = utils.debug('core:component:warn');
  50720. var aframeScript = document.currentScript;
  50721. var upperCaseRegExp = new RegExp('[A-Z]+');
  50722. /**
  50723. * Component class definition.
  50724. *
  50725. * Components configure appearance, modify behavior, or add functionality to
  50726. * entities. The behavior and appearance of an entity can be changed at runtime
  50727. * by adding, removing, or updating components. Entities do not share instances
  50728. * of components.
  50729. *
  50730. * @member {object} el - Reference to the entity element.
  50731. * @member {string} attrValue - Value of the corresponding HTML attribute.
  50732. * @member {object} data - Component data populated by parsing the
  50733. * mapped attribute of the component plus applying defaults and mixins.
  50734. */
  50735. var Component = module.exports.Component = function (el, attrValue, id) {
  50736. var self = this;
  50737. this.el = el;
  50738. this.id = id;
  50739. this.attrName = this.name + (id ? '__' + id : '');
  50740. this.evtDetail = {id: this.id, name: this.name};
  50741. this.initialized = false;
  50742. this.el.components[this.attrName] = this;
  50743. // Store component data from previous update call.
  50744. this.oldData = undefined;
  50745. // Last value passed to updateProperties.
  50746. this.previousAttrValue = undefined;
  50747. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  50748. el.emit('componentchanged', self.evtDetail, false);
  50749. }, 200);
  50750. this.updateProperties(attrValue);
  50751. };
  50752. Component.prototype = {
  50753. /**
  50754. * Contains the type schema and defaults for the data values.
  50755. * Data is coerced into the types of the values of the defaults.
  50756. */
  50757. schema: {},
  50758. /**
  50759. * Init handler. Similar to attachedCallback.
  50760. * Called during component initialization and is only run once.
  50761. * Components can use this to set initial state.
  50762. */
  50763. init: function () { /* no-op */ },
  50764. /**
  50765. * Update handler. Similar to attributeChangedCallback.
  50766. * Called whenever component's data changes.
  50767. * Also called on component initialization when the component receives initial data.
  50768. *
  50769. * @param {object} prevData - Previous attributes of the component.
  50770. */
  50771. update: function (prevData) { /* no-op */ },
  50772. updateSchema: undefined,
  50773. /**
  50774. * Tick handler.
  50775. * Called on each tick of the scene render loop.
  50776. * Affected by play and pause.
  50777. *
  50778. * @param {number} time - Scene tick time.
  50779. * @param {number} timeDelta - Difference in current render time and previous render time.
  50780. */
  50781. tick: undefined,
  50782. /**
  50783. * Tock handler.
  50784. * Called on each tock of the scene render loop.
  50785. * Affected by play and pause.
  50786. *
  50787. * @param {number} time - Scene tick time.
  50788. * @param {number} timeDelta - Difference in current render time and previous render time.
  50789. */
  50790. tock: undefined,
  50791. /**
  50792. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  50793. */
  50794. play: function () { /* no-op */ },
  50795. /**
  50796. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  50797. */
  50798. pause: function () { /* no-op */ },
  50799. /**
  50800. * Remove handler. Similar to detachedCallback.
  50801. * Called whenever component is removed from the entity (i.e., removeAttribute).
  50802. * Components can use this to reset behavior on the entity.
  50803. */
  50804. remove: function () { /* no-op */ },
  50805. /**
  50806. * Parses each property based on property type.
  50807. * If component is single-property, then parses the single property value.
  50808. *
  50809. * @param {string} value - HTML attribute value.
  50810. * @param {boolean} silent - Suppress warning messages.
  50811. * @returns {object} Component data.
  50812. */
  50813. parse: function (value, silent) {
  50814. var schema = this.schema;
  50815. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  50816. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  50817. },
  50818. /**
  50819. * Stringify properties if necessary.
  50820. *
  50821. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  50822. * value (e.g., selector, vec3 property types).
  50823. *
  50824. * @param {object} data - Complete component data.
  50825. * @returns {string}
  50826. */
  50827. stringify: function (data) {
  50828. var schema = this.schema;
  50829. if (typeof data === 'string') { return data; }
  50830. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  50831. data = stringifyProperties(data, schema);
  50832. return styleParser.stringify(data);
  50833. },
  50834. /**
  50835. * Update the cache of the pre-parsed attribute value.
  50836. *
  50837. * @param {string} value - New data.
  50838. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  50839. */
  50840. updateCachedAttrValue: function (value, clobber) {
  50841. var attrValue = this.parseAttrValueForCache(value);
  50842. var isSinglePropSchema = isSingleProp(this.schema);
  50843. var property;
  50844. if (value === undefined) { return; }
  50845. // Merge new data with previous `attrValue` if updating and not clobbering.
  50846. if (!isSinglePropSchema && !clobber) {
  50847. this.attrValue = this.attrValue ? cloneData(this.attrValue) : {};
  50848. for (property in attrValue) {
  50849. this.attrValue[property] = attrValue[property];
  50850. }
  50851. return;
  50852. }
  50853. // If single-prop schema or clobber.
  50854. this.attrValue = attrValue;
  50855. },
  50856. /**
  50857. * Given an HTML attribute value parses the string
  50858. * based on the component schema. To avoid double parsings of
  50859. * strings into strings we store the original instead
  50860. * of the parsed one
  50861. *
  50862. * @param {string} value - HTML attribute value
  50863. */
  50864. parseAttrValueForCache: function (value) {
  50865. var parsedValue;
  50866. if (typeof value !== 'string') { return value; }
  50867. if (isSingleProp(this.schema)) {
  50868. parsedValue = this.schema.parse(value);
  50869. /**
  50870. * To avoid bogus double parsings. Cached values will be parsed when building
  50871. * component data. For instance when parsing a src id to its url, we want to cache
  50872. * original string and not the parsed one (#monster -> models/monster.dae)
  50873. * so when building data we parse the expected value.
  50874. */
  50875. if (typeof parsedValue === 'string') { parsedValue = value; }
  50876. } else {
  50877. // Parse using the style parser to avoid double parsing of individual properties.
  50878. parsedValue = styleParser.parse(value);
  50879. }
  50880. return parsedValue;
  50881. },
  50882. /**
  50883. * Write cached attribute data to the entity DOM element.
  50884. *
  50885. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  50886. * default components.
  50887. */
  50888. flushToDOM: function (isDefault) {
  50889. var attrValue = isDefault ? this.data : this.attrValue;
  50890. if (!attrValue) { return; }
  50891. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  50892. this.stringify(attrValue));
  50893. },
  50894. /**
  50895. * Apply new component data if data has changed.
  50896. *
  50897. * @param {string} attrValue - HTML attribute value.
  50898. * If undefined, use the cached attribute value and continue updating properties.
  50899. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  50900. */
  50901. updateProperties: function (attrValue, clobber) {
  50902. var el = this.el;
  50903. var isSinglePropSchema;
  50904. var key;
  50905. var skipTypeChecking;
  50906. var oldData = this.oldData;
  50907. // Just cache the attribute if the entity has not loaded
  50908. // Components are not initialized until the entity has loaded
  50909. if (!el.hasLoaded) {
  50910. this.updateCachedAttrValue(attrValue);
  50911. return;
  50912. }
  50913. isSinglePropSchema = isSingleProp(this.schema);
  50914. // Disable type checking if the passed attribute is an object and has not changed.
  50915. skipTypeChecking = attrValue !== null && typeof this.previousAttrValue === 'object' &&
  50916. attrValue === this.previousAttrValue;
  50917. if (skipTypeChecking) {
  50918. for (key in this.attrValue) {
  50919. if (!(key in attrValue)) {
  50920. skipTypeChecking = false;
  50921. break;
  50922. }
  50923. }
  50924. for (key in attrValue) {
  50925. if (!(key in this.attrValue)) {
  50926. skipTypeChecking = false;
  50927. break;
  50928. }
  50929. }
  50930. }
  50931. // Cache previously passed attribute to decide if we skip type checking.
  50932. this.previousAttrValue = attrValue;
  50933. attrValue = this.parseAttrValueForCache(attrValue);
  50934. if (this.updateSchema) { this.updateSchema(this.buildData(attrValue, false, true)); }
  50935. this.data = this.buildData(attrValue, clobber, false, skipTypeChecking);
  50936. // Cache current attrValue for future updates.
  50937. this.updateCachedAttrValue(attrValue, clobber);
  50938. if (!this.initialized) {
  50939. // Component is being already initialized.
  50940. if (el.initializingComponents[this.name]) { return; }
  50941. // Prevent infinite loop in case of init method setting same component on the entity.
  50942. el.initializingComponents[this.name] = true;
  50943. // Initialize component.
  50944. this.init();
  50945. this.initialized = true;
  50946. delete el.initializingComponents[this.name];
  50947. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  50948. // Pass undefined to rest of types.
  50949. oldData = (!isSinglePropSchema ||
  50950. typeof parseProperty(undefined, this.schema) === 'object') ? {} : undefined;
  50951. // Store current data as previous data for future updates.
  50952. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  50953. this.update(oldData);
  50954. // Play the component if the entity is playing.
  50955. if (el.isPlaying) { this.play(); }
  50956. el.emit('componentinitialized', this.evtDetail, false);
  50957. } else {
  50958. // Don't update if properties haven't changed
  50959. if (utils.deepEqual(this.oldData, this.data)) { return; }
  50960. // Store current data as previous data for future updates.
  50961. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  50962. // Update component.
  50963. this.update(oldData);
  50964. this.throttledEmitComponentChanged();
  50965. }
  50966. },
  50967. /**
  50968. * Reset value of a property to the property's default value.
  50969. * If single-prop component, reset value to component's default value.
  50970. *
  50971. * @param {string} propertyName - Name of property to reset.
  50972. */
  50973. resetProperty: function (propertyName) {
  50974. if (isSingleProp(this.schema)) {
  50975. this.attrValue = undefined;
  50976. } else {
  50977. if (!(propertyName in this.attrValue)) { return; }
  50978. delete this.attrValue[propertyName];
  50979. }
  50980. this.updateProperties(this.attrValue);
  50981. },
  50982. /**
  50983. * Extend schema of component given a partial schema.
  50984. *
  50985. * Some components might want to mutate their schema based on certain properties.
  50986. * e.g., Material component changes its schema based on `shader` to account for different
  50987. * uniforms
  50988. *
  50989. * @param {object} schemaAddon - Schema chunk that extend base schema.
  50990. */
  50991. extendSchema: function (schemaAddon) {
  50992. // Clone base schema.
  50993. var extendedSchema = utils.extend({}, components[this.name].schema);
  50994. // Extend base schema with new schema chunk.
  50995. utils.extend(extendedSchema, schemaAddon);
  50996. this.schema = processSchema(extendedSchema);
  50997. this.el.emit('schemachanged', {component: this.name});
  50998. },
  50999. /**
  51000. * Builds component data from the current state of the entity, ultimately
  51001. * updating this.data.
  51002. *
  51003. * If the component was detached completely, set data to null.
  51004. *
  51005. * Precedence:
  51006. * 1. Defaults data
  51007. * 2. Mixin data.
  51008. * 3. Attribute data.
  51009. *
  51010. * Finally coerce the data to the types of the defaults.
  51011. *
  51012. * @param {object} newData - Element new data.
  51013. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  51014. * @param {boolean} silent - Suppress warning messages.
  51015. * @param {boolean} skipTypeChecking - Skip type checking and cohercion.
  51016. * @return {object} The component data
  51017. */
  51018. buildData: function (newData, clobber, silent, skipTypeChecking) {
  51019. var componentDefined;
  51020. var data;
  51021. var defaultValue;
  51022. var keys;
  51023. var keysLength;
  51024. var mixinData;
  51025. var schema = this.schema;
  51026. var i;
  51027. var isSinglePropSchema = isSingleProp(schema);
  51028. var mixinEls = this.el.mixinEls;
  51029. var previousData;
  51030. // Whether component has a defined value. For arrays, treat empty as not defined.
  51031. componentDefined = newData && newData.constructor === Array
  51032. ? newData.length
  51033. : newData !== undefined && newData !== null;
  51034. // 1. Default values (lowest precendence).
  51035. if (isSinglePropSchema) {
  51036. // Clone default value if plain object so components don't share the same object
  51037. // that might be modified by the user.
  51038. data = isObjectOrArray(schema.default) ? utils.clone(schema.default) : schema.default;
  51039. } else {
  51040. // Preserve previously set properties if clobber not enabled.
  51041. previousData = !clobber && this.attrValue;
  51042. // Clone previous data to prevent sharing references with attrValue that might be
  51043. // modified by the user.
  51044. data = typeof previousData === 'object' ? cloneData(previousData) : {};
  51045. // Apply defaults.
  51046. for (i = 0, keys = Object.keys(schema), keysLength = keys.length; i < keysLength; i++) {
  51047. defaultValue = schema[keys[i]].default;
  51048. if (data[keys[i]] !== undefined) { continue; }
  51049. // Clone default value if object so components don't share object
  51050. data[keys[i]] = isObjectOrArray(defaultValue) ? utils.clone(defaultValue) : defaultValue;
  51051. }
  51052. }
  51053. // 2. Mixin values.
  51054. for (i = 0; i < mixinEls.length; i++) {
  51055. mixinData = mixinEls[i].getAttribute(this.attrName);
  51056. if (mixinData) {
  51057. data = extendProperties(data, mixinData, isSinglePropSchema);
  51058. }
  51059. }
  51060. // 3. Attribute values (highest precendence).
  51061. if (componentDefined) {
  51062. if (isSinglePropSchema) {
  51063. if (skipTypeChecking === true) { return newData; }
  51064. return parseProperty(newData, schema);
  51065. }
  51066. data = extendProperties(data, newData, isSinglePropSchema);
  51067. } else {
  51068. if (skipTypeChecking === true) { return data; }
  51069. // Parse and coerce using the schema.
  51070. if (isSinglePropSchema) { return parseProperty(data, schema); }
  51071. }
  51072. if (skipTypeChecking === true) { return data; }
  51073. return parseProperties(data, schema, undefined, this.name, silent);
  51074. }
  51075. };
  51076. // For testing.
  51077. if (window.debug) {
  51078. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  51079. }
  51080. /**
  51081. * Registers a component to A-Frame.
  51082. *
  51083. * @param {string} name - Component name.
  51084. * @param {object} definition - Component schema and lifecycle method handlers.
  51085. * @returns {object} Component.
  51086. */
  51087. module.exports.registerComponent = function (name, definition) {
  51088. var NewComponent;
  51089. var proto = {};
  51090. // Warning if component is statically registered after the scene.
  51091. if (document.currentScript && document.currentScript !== aframeScript) {
  51092. scenes.forEach(function checkPosition (sceneEl) {
  51093. // Okay to register component after the scene at runtime.
  51094. if (sceneEl.hasLoaded) { return; }
  51095. // Check that component is declared before the scene.
  51096. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  51097. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  51098. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  51099. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  51100. 'such that the component is available to entities during scene initialization.');
  51101. // For testing.
  51102. if (window.debug) { registrationOrderWarnings[name] = true; }
  51103. });
  51104. }
  51105. if (upperCaseRegExp.test(name) === true) {
  51106. warn('The component name `' + name + '` contains uppercase characters, but ' +
  51107. 'HTML will ignore the capitalization of attribute names. ' +
  51108. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  51109. }
  51110. if (name.indexOf('__') !== -1) {
  51111. throw new Error('The component name `' + name + '` is not allowed. ' +
  51112. 'The sequence __ (double underscore) is reserved to specify an id' +
  51113. ' for multiple components of the same type');
  51114. }
  51115. // Format definition object to prototype object.
  51116. Object.keys(definition).forEach(function (key) {
  51117. proto[key] = {
  51118. value: definition[key],
  51119. writable: true
  51120. };
  51121. });
  51122. if (components[name]) {
  51123. throw new Error('The component `' + name + '` has been already registered. ' +
  51124. 'Check that you are not loading two versions of the same component ' +
  51125. 'or two different components of the same name.');
  51126. }
  51127. NewComponent = function (el, attr, id) {
  51128. Component.call(this, el, attr, id);
  51129. };
  51130. NewComponent.prototype = Object.create(Component.prototype, proto);
  51131. NewComponent.prototype.name = name;
  51132. NewComponent.prototype.constructor = NewComponent;
  51133. NewComponent.prototype.system = systems && systems.systems[name];
  51134. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  51135. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  51136. components[name] = {
  51137. Component: NewComponent,
  51138. dependencies: NewComponent.prototype.dependencies,
  51139. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  51140. multiple: NewComponent.prototype.multiple,
  51141. parse: NewComponent.prototype.parse,
  51142. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  51143. schema: utils.extend(processSchema(NewComponent.prototype.schema, NewComponent.prototype.name)),
  51144. stringify: NewComponent.prototype.stringify,
  51145. type: NewComponent.prototype.type
  51146. };
  51147. return NewComponent;
  51148. };
  51149. /**
  51150. * Clone component data.
  51151. * Clone only the properties that are plain objects while keeping a reference for the rest.
  51152. *
  51153. * @param data - Component data to clone.
  51154. * @returns Cloned data.
  51155. */
  51156. function cloneData (data) {
  51157. var clone = {};
  51158. var parsedProperty;
  51159. var key;
  51160. for (key in data) {
  51161. parsedProperty = data[key];
  51162. clone[key] = isObjectOrArray(parsedProperty) ? utils.clone(parsedProperty) : parsedProperty;
  51163. }
  51164. return clone;
  51165. }
  51166. /**
  51167. * Object extending with checking for single-property schema.
  51168. *
  51169. * @param dest - Destination object or value.
  51170. * @param source - Source object or value
  51171. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  51172. * @returns Overridden object or value.
  51173. */
  51174. function extendProperties (dest, source, isSinglePropSchema) {
  51175. if (isSinglePropSchema && (source === null || typeof source !== 'object')) { return source; }
  51176. return utils.extend(dest, source);
  51177. }
  51178. /**
  51179. * Checks if a component has defined a method that needs to run every frame.
  51180. */
  51181. function hasBehavior (component) {
  51182. return component.tick || component.tock;
  51183. }
  51184. /**
  51185. * Wrapper for user defined pause method
  51186. * Pause component by removing tick behavior and calling user's pause method.
  51187. *
  51188. * @param pauseMethod {function} - user defined pause method
  51189. */
  51190. function wrapPause (pauseMethod) {
  51191. return function pause () {
  51192. var sceneEl = this.el.sceneEl;
  51193. if (!this.isPlaying) { return; }
  51194. pauseMethod.call(this);
  51195. this.isPlaying = false;
  51196. // Remove tick behavior.
  51197. if (!hasBehavior(this)) { return; }
  51198. sceneEl.removeBehavior(this);
  51199. };
  51200. }
  51201. /**
  51202. * Wrapper for user defined play method
  51203. * Play component by adding tick behavior and calling user's play method.
  51204. *
  51205. * @param playMethod {function} - user defined play method
  51206. *
  51207. */
  51208. function wrapPlay (playMethod) {
  51209. return function play () {
  51210. var sceneEl = this.el.sceneEl;
  51211. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  51212. if (!this.initialized || !shouldPlay) { return; }
  51213. playMethod.call(this);
  51214. this.isPlaying = true;
  51215. // Add tick behavior.
  51216. if (!hasBehavior(this)) { return; }
  51217. sceneEl.addBehavior(this);
  51218. };
  51219. }
  51220. function isObjectOrArray (value) {
  51221. return value && (value.constructor === Object || value.constructor === Array);
  51222. }
  51223. },{"../utils/":195,"./scene/scenes":131,"./schema":133,"./system":135}],126:[function(_dereq_,module,exports){
  51224. var schema = _dereq_('./schema');
  51225. var processSchema = schema.process;
  51226. var geometries = module.exports.geometries = {}; // Registered geometries.
  51227. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  51228. var THREE = _dereq_('../lib/three');
  51229. /**
  51230. * Geometry class definition.
  51231. *
  51232. * Geometries extend the geometry component API to create and register geometry types.
  51233. */
  51234. var Geometry = module.exports.Geometry = function () {};
  51235. Geometry.prototype = {
  51236. /**
  51237. * Contains the type schema and defaults for the data values.
  51238. * Data is coerced into the types of the values of the defaults.
  51239. */
  51240. schema: {},
  51241. /**
  51242. * Init handler. Similar to attachedCallback.
  51243. * Called during shader initialization and is only run once.
  51244. */
  51245. init: function (data) {
  51246. this.geometry = new THREE.Geometry();
  51247. return this.geometry;
  51248. },
  51249. /**
  51250. * Update handler. Similar to attributeChangedCallback.
  51251. * Called whenever the associated geometry data changes.
  51252. *
  51253. * @param {object} data - New geometry data.
  51254. */
  51255. update: function (data) { /* no-op */ }
  51256. };
  51257. /**
  51258. * Registers a geometry to A-Frame.
  51259. *
  51260. * @param {string} name - Geometry name.
  51261. * @param {object} definition - Geometry property and methods.
  51262. * @returns {object} Geometry.
  51263. */
  51264. module.exports.registerGeometry = function (name, definition) {
  51265. var NewGeometry;
  51266. var proto = {};
  51267. // Format definition object to prototype object.
  51268. Object.keys(definition).forEach(function expandDefinition (key) {
  51269. proto[key] = {
  51270. value: definition[key],
  51271. writable: true
  51272. };
  51273. });
  51274. if (geometries[name]) {
  51275. throw new Error('The geometry `' + name + '` has been already registered');
  51276. }
  51277. NewGeometry = function () { Geometry.call(this); };
  51278. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  51279. NewGeometry.prototype.name = name;
  51280. NewGeometry.prototype.constructor = NewGeometry;
  51281. geometries[name] = {
  51282. Geometry: NewGeometry,
  51283. schema: processSchema(NewGeometry.prototype.schema)
  51284. };
  51285. geometryNames.push(name);
  51286. return NewGeometry;
  51287. };
  51288. },{"../lib/three":173,"./schema":133}],127:[function(_dereq_,module,exports){
  51289. var coordinates = _dereq_('../utils/coordinates');
  51290. var debug = _dereq_('debug');
  51291. var error = debug('core:propertyTypes:warn');
  51292. var warn = debug('core:propertyTypes:warn');
  51293. var propertyTypes = module.exports.propertyTypes = {};
  51294. var nonCharRegex = /[,> .[\]:]/;
  51295. // Built-in property types.
  51296. registerPropertyType('audio', '', assetParse);
  51297. registerPropertyType('array', [], arrayParse, arrayStringify);
  51298. registerPropertyType('asset', '', assetParse);
  51299. registerPropertyType('boolean', false, boolParse);
  51300. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  51301. registerPropertyType('int', 0, intParse);
  51302. registerPropertyType('number', 0, numberParse);
  51303. registerPropertyType('map', '', assetParse);
  51304. registerPropertyType('model', '', assetParse);
  51305. registerPropertyType('selector', null, selectorParse, selectorStringify);
  51306. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  51307. registerPropertyType('src', '', srcParse);
  51308. registerPropertyType('string', '', defaultParse, defaultStringify);
  51309. registerPropertyType('time', 0, intParse);
  51310. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  51311. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  51312. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 0}, vecParse, coordinates.stringify);
  51313. /**
  51314. * Register a parser for re-use such that when someone uses `type` in the schema,
  51315. * `schema.process` will set the property `parse` and `stringify`.
  51316. *
  51317. * @param {string} type - Type name.
  51318. * @param [defaultValue=null] -
  51319. * Default value to use if component does not define default value.
  51320. * @param {function} [parse=defaultParse] - Parse string function.
  51321. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  51322. */
  51323. function registerPropertyType (type, defaultValue, parse, stringify) {
  51324. if ('type' in propertyTypes) {
  51325. error('Property type ' + type + ' is already registered.');
  51326. return;
  51327. }
  51328. propertyTypes[type] = {
  51329. default: defaultValue,
  51330. parse: parse || defaultParse,
  51331. stringify: stringify || defaultStringify
  51332. };
  51333. }
  51334. module.exports.registerPropertyType = registerPropertyType;
  51335. function arrayParse (value) {
  51336. if (Array.isArray(value)) { return value; }
  51337. if (!value || typeof value !== 'string') { return []; }
  51338. return value.split(',').map(trim);
  51339. function trim (str) { return str.trim(); }
  51340. }
  51341. function arrayStringify (value) {
  51342. return value.join(', ');
  51343. }
  51344. /**
  51345. * For general assets.
  51346. *
  51347. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  51348. * just string.
  51349. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  51350. * just string.
  51351. */
  51352. function assetParse (value) {
  51353. var el;
  51354. var parsedUrl;
  51355. // If an element was provided (e.g. canvas or video), just return it.
  51356. if (typeof value !== 'string') { return value; }
  51357. // Wrapped `url()` in case of data URI.
  51358. parsedUrl = value.match(/\url\((.+)\)/);
  51359. if (parsedUrl) { return parsedUrl[1]; }
  51360. // ID.
  51361. if (value.charAt(0) === '#') {
  51362. el = document.getElementById(value.substring(1));
  51363. if (el) {
  51364. // Pass through media elements. If we have the elements, we don't have to call
  51365. // three.js loaders which would re-request the assets.
  51366. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  51367. return el;
  51368. }
  51369. return el.getAttribute('src');
  51370. }
  51371. warn('"' + value + '" asset not found.');
  51372. return;
  51373. }
  51374. // Non-wrapped url().
  51375. return value;
  51376. }
  51377. function defaultParse (value) {
  51378. return value;
  51379. }
  51380. function defaultStringify (value) {
  51381. if (value === null) { return 'null'; }
  51382. return value.toString();
  51383. }
  51384. function boolParse (value) {
  51385. return value !== 'false' && value !== false;
  51386. }
  51387. function intParse (value) {
  51388. return parseInt(value, 10);
  51389. }
  51390. function numberParse (value) {
  51391. return parseFloat(value, 10);
  51392. }
  51393. function selectorParse (value) {
  51394. if (!value) { return null; }
  51395. if (typeof value !== 'string') { return value; }
  51396. if (value[0] === '#' && !nonCharRegex.test(value)) {
  51397. // When selecting element by ID only, use getElementById for better performance.
  51398. // Don't match like #myId .child.
  51399. return document.getElementById(value.substring(1));
  51400. }
  51401. return document.querySelector(value);
  51402. }
  51403. function selectorAllParse (value) {
  51404. if (!value) { return null; }
  51405. if (typeof value !== 'string') { return value; }
  51406. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  51407. }
  51408. function selectorStringify (value) {
  51409. if (value.getAttribute) {
  51410. return '#' + value.getAttribute('id');
  51411. }
  51412. return defaultStringify(value);
  51413. }
  51414. function selectorAllStringify (value) {
  51415. if (value instanceof Array) {
  51416. return value.map(function (element) {
  51417. return '#' + element.getAttribute('id');
  51418. }).join(', ');
  51419. }
  51420. return defaultStringify(value);
  51421. }
  51422. function srcParse (value) {
  51423. warn('`src` property type is deprecated. Use `asset` instead.');
  51424. return assetParse(value);
  51425. }
  51426. function vecParse (value) {
  51427. return coordinates.parse(value, this.default);
  51428. }
  51429. /**
  51430. * Validate the default values in a schema to match their type.
  51431. *
  51432. * @param {string} type - Property type name.
  51433. * @param defaultVal - Property type default value.
  51434. * @returns {boolean} Whether default value is accurate given the type.
  51435. */
  51436. function isValidDefaultValue (type, defaultVal) {
  51437. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  51438. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  51439. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  51440. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  51441. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  51442. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  51443. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  51444. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  51445. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  51446. if (type === 'selector' && typeof defaultVal !== 'string' &&
  51447. defaultVal !== null) { return false; }
  51448. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  51449. defaultVal !== null) { return false; }
  51450. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  51451. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  51452. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  51453. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  51454. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  51455. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  51456. return true;
  51457. }
  51458. module.exports.isValidDefaultValue = isValidDefaultValue;
  51459. /**
  51460. * Checks if default coordinates are valid.
  51461. *
  51462. * @param possibleCoordinates
  51463. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  51464. * @returns {boolean} Whether coordinates are parsed correctly.
  51465. */
  51466. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  51467. if (possibleCoordinates === null) { return true; }
  51468. if (typeof possibleCoordinates !== 'object') { return false; }
  51469. if (Object.keys(possibleCoordinates).length !== dimensions) {
  51470. return false;
  51471. } else {
  51472. var x = possibleCoordinates.x;
  51473. var y = possibleCoordinates.y;
  51474. var z = possibleCoordinates.z;
  51475. var w = possibleCoordinates.w;
  51476. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  51477. if (dimensions > 2 && typeof z !== 'number') { return false; }
  51478. if (dimensions > 3 && typeof w !== 'number') { return false; }
  51479. }
  51480. return true;
  51481. }
  51482. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  51483. },{"../utils/coordinates":190,"debug":8}],128:[function(_dereq_,module,exports){
  51484. /* global Promise, screen */
  51485. var initMetaTags = _dereq_('./metaTags').inject;
  51486. var initWakelock = _dereq_('./wakelock');
  51487. var re = _dereq_('../a-register-element');
  51488. var scenes = _dereq_('./scenes');
  51489. var systems = _dereq_('../system').systems;
  51490. var THREE = _dereq_('../../lib/three');
  51491. var TWEEN = _dereq_('@tweenjs/tween.js');
  51492. var utils = _dereq_('../../utils/');
  51493. // Require after.
  51494. var AEntity = _dereq_('../a-entity');
  51495. var ANode = _dereq_('../a-node');
  51496. var initPostMessageAPI = _dereq_('./postMessage');
  51497. var bind = utils.bind;
  51498. var isIOS = utils.device.isIOS();
  51499. var isMobile = utils.device.isMobile();
  51500. var registerElement = re.registerElement;
  51501. var warn = utils.debug('core:a-scene:warn');
  51502. /**
  51503. * Scene element, holds all entities.
  51504. *
  51505. * @member {number} animationFrameID
  51506. * @member {array} behaviors - Component instances that have registered themselves to be
  51507. updated on every tick.
  51508. * @member {object} camera - three.js Camera object.
  51509. * @member {object} canvas
  51510. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  51511. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  51512. * @member {object} object3D - Root three.js Scene object.
  51513. * @member {object} renderer
  51514. * @member {bool} renderStarted
  51515. * @member {object} effect - three.js VREffect
  51516. * @member {object} systems - Registered instantiated systems.
  51517. * @member {number} time
  51518. */
  51519. module.exports.AScene = registerElement('a-scene', {
  51520. prototype: Object.create(AEntity.prototype, {
  51521. defaultComponents: {
  51522. value: {
  51523. 'inspector': '',
  51524. 'keyboard-shortcuts': '',
  51525. 'screenshot': '',
  51526. 'vr-mode-ui': ''
  51527. }
  51528. },
  51529. createdCallback: {
  51530. value: function () {
  51531. this.isIOS = isIOS;
  51532. this.isMobile = isMobile;
  51533. this.isScene = true;
  51534. this.object3D = new THREE.Scene();
  51535. this.render = bind(this.render, this);
  51536. this.systems = {};
  51537. this.systemNames = [];
  51538. this.time = 0;
  51539. this.init();
  51540. }
  51541. },
  51542. init: {
  51543. value: function () {
  51544. this.behaviors = {tick: [], tock: []};
  51545. this.hasLoaded = false;
  51546. this.isPlaying = false;
  51547. this.originalHTML = this.innerHTML;
  51548. this.renderTarget = null;
  51549. setupCanvas(this);
  51550. this.setupRenderer();
  51551. this.resize();
  51552. this.addFullScreenStyles();
  51553. initPostMessageAPI(this);
  51554. },
  51555. writable: true
  51556. },
  51557. addFullScreenStyles: {
  51558. value: function () {
  51559. var htmlEl = document.documentElement;
  51560. htmlEl.classList.add('a-html');
  51561. document.body.classList.add('a-body');
  51562. this.classList.add('fullscreen');
  51563. }
  51564. },
  51565. removeFullScreenStyles: {
  51566. value: function () {
  51567. var htmlEl = document.documentElement;
  51568. htmlEl.classList.remove('a-html');
  51569. document.body.classList.remove('a-body');
  51570. this.classList.remove('fullscreen');
  51571. }
  51572. },
  51573. attachedCallback: {
  51574. value: function () {
  51575. var resize;
  51576. var self = this;
  51577. initMetaTags(this);
  51578. initWakelock(this);
  51579. this.initSystems();
  51580. resize = bind(this.resize, this);
  51581. window.addEventListener('load', resize);
  51582. window.addEventListener('resize', resize);
  51583. this.play();
  51584. // Add to scene index.
  51585. scenes.push(this);
  51586. // Handler to exit VR (e.g., Oculus Browser back button).
  51587. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  51588. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  51589. // bind functions
  51590. this.enterVRBound = function () { self.enterVR(); };
  51591. this.exitVRBound = function () { self.exitVR(); };
  51592. this.exitVRTrueBound = function () { self.exitVR(true); };
  51593. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  51594. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  51595. // Enter VR on `vrdisplayactivate` (e.g. putting on Rift headset).
  51596. window.addEventListener('vrdisplayactivate', this.enterVRBound);
  51597. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  51598. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  51599. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  51600. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  51601. // Register for mouse restricted events while in VR
  51602. // (e.g. mouse no longer available on desktop 2D view)
  51603. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  51604. // Register for mouse unrestricted events while in VR
  51605. // (e.g. mouse once again available on desktop 2D view)
  51606. window.addEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  51607. },
  51608. writable: window.debug
  51609. },
  51610. /**
  51611. * Initialize all systems.
  51612. */
  51613. initSystems: {
  51614. value: function () {
  51615. Object.keys(systems).forEach(bind(this.initSystem, this));
  51616. }
  51617. },
  51618. /**
  51619. * Initialize a system.
  51620. */
  51621. initSystem: {
  51622. value: function (name) {
  51623. if (this.systems[name]) { return; }
  51624. this.systems[name] = new systems[name](this);
  51625. this.systemNames.push(name);
  51626. }
  51627. },
  51628. /**
  51629. * Shut down scene on detach.
  51630. */
  51631. detachedCallback: {
  51632. value: function () {
  51633. var sceneIndex;
  51634. if (this.effect && this.effect.cancelAnimationFrame) {
  51635. this.effect.cancelAnimationFrame(this.animationFrameID);
  51636. } else {
  51637. window.cancelAnimationFrame(this.animationFrameID);
  51638. }
  51639. this.animationFrameID = null;
  51640. // Remove from scene index.
  51641. sceneIndex = scenes.indexOf(this);
  51642. scenes.splice(sceneIndex, 1);
  51643. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  51644. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  51645. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  51646. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  51647. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  51648. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  51649. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  51650. }
  51651. },
  51652. /**
  51653. * Add ticks and tocks.
  51654. *
  51655. * @param {object} behavior - Generally a component. Must implement a .update() method
  51656. * to be called on every tick.
  51657. */
  51658. addBehavior: {
  51659. value: function (behavior) {
  51660. var self = this;
  51661. var behaviors = this.behaviors;
  51662. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  51663. Object.keys(behaviors).forEach(function (behaviorType) {
  51664. if (!behavior[behaviorType]) { return; }
  51665. var behaviorArr = self.behaviors[behaviorType];
  51666. if (behaviorArr.indexOf(behavior) === -1) {
  51667. behaviorArr.push(behavior);
  51668. }
  51669. });
  51670. }
  51671. },
  51672. /**
  51673. * For tests.
  51674. */
  51675. getPointerLockElement: {
  51676. value: function () {
  51677. return document.pointerLockElement;
  51678. },
  51679. writable: window.debug
  51680. },
  51681. /**
  51682. * For tests.
  51683. */
  51684. checkHeadsetConnected: {
  51685. value: utils.device.checkHeadsetConnected,
  51686. writable: window.debug
  51687. },
  51688. /**
  51689. * Call `requestPresent` if WebVR or WebVR polyfill.
  51690. * Call `requestFullscreen` on desktop.
  51691. * Handle events, states, fullscreen styles.
  51692. *
  51693. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  51694. * manually calling requestPresent via WebVR API directly).
  51695. * @returns {Promise}
  51696. */
  51697. enterVR: {
  51698. value: function (fromExternal) {
  51699. var self = this;
  51700. var effect = this.effect;
  51701. // Don't enter VR if already in VR.
  51702. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  51703. // Enter VR via WebVR API.
  51704. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  51705. return effect && effect.requestPresent().then(enterVRSuccess, enterVRFailure) || Promise.reject(new Error('VREffect not initialized'));
  51706. }
  51707. // Either entered VR already via WebVR API or VR not supported.
  51708. enterVRSuccess();
  51709. return Promise.resolve();
  51710. function enterVRSuccess () {
  51711. self.addState('vr-mode');
  51712. self.emit('enter-vr', {target: self});
  51713. // Lock to landscape orientation on mobile.
  51714. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  51715. screen.orientation.lock('landscape');
  51716. }
  51717. self.addFullScreenStyles();
  51718. // On mobile, the polyfill handles fullscreen.
  51719. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  51720. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  51721. // connected.
  51722. if (!self.isMobile && !self.checkHeadsetConnected()) {
  51723. requestFullscreen(self.canvas);
  51724. }
  51725. self.resize();
  51726. }
  51727. function enterVRFailure (err) {
  51728. if (err && err.message) {
  51729. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  51730. } else {
  51731. throw new Error('Failed to enter VR mode (`requestPresent`).');
  51732. }
  51733. }
  51734. },
  51735. writable: window.debug
  51736. },
  51737. /**
  51738. * Call `exitPresent` if WebVR or WebVR polyfill.
  51739. * Handle events, states, fullscreen styles.
  51740. *
  51741. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  51742. * Oculus Browser GearVR back button).
  51743. * @returns {Promise}
  51744. */
  51745. exitVR: {
  51746. value: function (fromExternal) {
  51747. var self = this;
  51748. // Don't exit VR if not in VR.
  51749. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  51750. exitFullscreen();
  51751. // Handle exiting VR if not yet already and in a headset or polyfill.
  51752. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  51753. return this.effect.exitPresent().then(exitVRSuccess, exitVRFailure);
  51754. }
  51755. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  51756. exitVRSuccess();
  51757. return Promise.resolve();
  51758. function exitVRSuccess () {
  51759. self.removeState('vr-mode');
  51760. // Lock to landscape orientation on mobile.
  51761. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  51762. screen.orientation.unlock();
  51763. }
  51764. // Exiting VR in embedded mode, no longer need fullscreen styles.
  51765. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  51766. self.resize();
  51767. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(this.canvas); }
  51768. self.emit('exit-vr', {target: self});
  51769. }
  51770. function exitVRFailure (err) {
  51771. if (err && err.message) {
  51772. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  51773. } else {
  51774. throw new Error('Failed to exit VR mode (`exitPresent`).');
  51775. }
  51776. }
  51777. },
  51778. writable: window.debug
  51779. },
  51780. pointerRestricted: {
  51781. value: function () {
  51782. if (this.canvas) {
  51783. var pointerLockElement = this.getPointerLockElement();
  51784. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  51785. // Recreate pointer lock on the canvas, if taken on another element.
  51786. document.exitPointerLock();
  51787. }
  51788. if (this.canvas.requestPointerLock) {
  51789. this.canvas.requestPointerLock();
  51790. }
  51791. }
  51792. }
  51793. },
  51794. pointerUnrestricted: {
  51795. value: function () {
  51796. var pointerLockElement = this.getPointerLockElement();
  51797. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  51798. document.exitPointerLock();
  51799. }
  51800. }
  51801. },
  51802. /**
  51803. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  51804. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  51805. */
  51806. onVRPresentChange: {
  51807. value: function (evt) {
  51808. // Polyfill places display inside the detail property
  51809. var display = evt.display || evt.detail.display;
  51810. // Entering VR.
  51811. if (display.isPresenting) {
  51812. this.enterVR(true);
  51813. return;
  51814. }
  51815. // Exiting VR.
  51816. this.exitVR(true);
  51817. }
  51818. },
  51819. /**
  51820. * Wraps Entity.getAttribute to take into account for systems.
  51821. * If system exists, then return system data rather than possible component data.
  51822. */
  51823. getAttribute: {
  51824. value: function (attr) {
  51825. var system = this.systems[attr];
  51826. if (system) { return system.data; }
  51827. return AEntity.prototype.getAttribute.call(this, attr);
  51828. }
  51829. },
  51830. /**
  51831. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  51832. * what `getAttribute` is now. Now legacy code.
  51833. */
  51834. getComputedAttribute: {
  51835. value: function (attr) {
  51836. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  51837. this.getAttribute(attr);
  51838. }
  51839. },
  51840. /**
  51841. * Wraps Entity.getDOMAttribute to take into account for systems.
  51842. * If system exists, then return system data rather than possible component data.
  51843. */
  51844. getDOMAttribute: {
  51845. value: function (attr) {
  51846. var system = this.systems[attr];
  51847. if (system) { return system.data; }
  51848. return AEntity.prototype.getDOMAttribute.call(this, attr);
  51849. }
  51850. },
  51851. /**
  51852. * Wrap Entity.setAttribute to take into account for systems.
  51853. * If system exists, then skip component initialization checks and do a normal
  51854. * setAttribute.
  51855. */
  51856. setAttribute: {
  51857. value: function (attr, value, componentPropValue) {
  51858. var system = this.systems[attr];
  51859. if (system) {
  51860. ANode.prototype.setAttribute.call(this, attr, value);
  51861. system.updateProperties(value);
  51862. return;
  51863. }
  51864. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  51865. }
  51866. },
  51867. /**
  51868. * @param {object} behavior - Generally a component. Has registered itself to behaviors.
  51869. */
  51870. removeBehavior: {
  51871. value: function (behavior) {
  51872. var self = this;
  51873. var behaviors = this.behaviors;
  51874. // Check if behavior has tick and/or tock and remove the behavior from the appropriate array.
  51875. Object.keys(behaviors).forEach(function (behaviorType) {
  51876. if (!behavior[behaviorType]) { return; }
  51877. var behaviorArr = self.behaviors[behaviorType];
  51878. var index = behaviorArr.indexOf(behavior);
  51879. if (index !== -1) {
  51880. behaviorArr.splice(index, 1);
  51881. }
  51882. });
  51883. }
  51884. },
  51885. resize: {
  51886. value: function () {
  51887. var camera = this.camera;
  51888. var canvas = this.canvas;
  51889. var embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  51890. var size;
  51891. var isEffectPresenting = this.effect && this.effect.isPresenting;
  51892. // Do not update renderer, if a camera or a canvas have not been injected.
  51893. // In VR mode, VREffect handles canvas resize based on the dimensions returned by
  51894. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  51895. // the window size, therefore should not be overwritten with the window's width and height,
  51896. // except when in fullscreen mode.
  51897. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isEffectPresenting))) { return; }
  51898. // Update camera.
  51899. size = getCanvasSize(canvas, embedded);
  51900. camera.aspect = size.width / size.height;
  51901. camera.updateProjectionMatrix();
  51902. // Notify renderer of size change.
  51903. this.renderer.setSize(size.width, size.height);
  51904. },
  51905. writable: window.debug
  51906. },
  51907. setupRenderer: {
  51908. value: function () {
  51909. var renderer;
  51910. renderer = this.renderer = new THREE.WebGLRenderer({
  51911. canvas: this.canvas,
  51912. antialias: shouldAntiAlias(this),
  51913. alpha: true
  51914. });
  51915. renderer.setPixelRatio(window.devicePixelRatio);
  51916. renderer.sortObjects = false;
  51917. this.effect = new THREE.VREffect(renderer);
  51918. this.effect.autoSubmitFrame = false;
  51919. },
  51920. writable: window.debug
  51921. },
  51922. /**
  51923. * Handler attached to elements to help scene know when to kick off.
  51924. * Scene waits for all entities to load.
  51925. */
  51926. play: {
  51927. value: function () {
  51928. var self = this;
  51929. if (this.renderStarted) {
  51930. AEntity.prototype.play.call(this);
  51931. return;
  51932. }
  51933. this.addEventListener('loaded', function () {
  51934. AEntity.prototype.play.call(this); // .play() *before* render.
  51935. // Wait for camera if necessary before rendering.
  51936. if (this.camera) {
  51937. startRender(this);
  51938. return;
  51939. }
  51940. this.addEventListener('camera-set-active', function () { startRender(this); });
  51941. function startRender (sceneEl) {
  51942. if (sceneEl.renderStarted) { return; }
  51943. sceneEl.resize();
  51944. // Kick off render loop.
  51945. if (sceneEl.renderer) {
  51946. if (window.performance) {
  51947. window.performance.mark('render-started');
  51948. }
  51949. sceneEl.clock = new THREE.Clock();
  51950. sceneEl.render();
  51951. sceneEl.renderStarted = true;
  51952. sceneEl.emit('renderstart');
  51953. }
  51954. }
  51955. });
  51956. // setTimeout to wait for all nodes to attach and run their callbacks.
  51957. setTimeout(function () {
  51958. AEntity.prototype.load.call(self);
  51959. });
  51960. }
  51961. },
  51962. /**
  51963. * Wrap `updateComponent` to not initialize the component if the component has a system
  51964. * (aframevr/aframe#2365).
  51965. */
  51966. updateComponent: {
  51967. value: function (componentName) {
  51968. if (componentName in systems) { return; }
  51969. AEntity.prototype.updateComponent.apply(this, arguments);
  51970. }
  51971. },
  51972. /**
  51973. * Behavior-updater meant to be called from scene render.
  51974. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  51975. * needing to render.
  51976. */
  51977. tick: {
  51978. value: function (time, timeDelta) {
  51979. var i;
  51980. var systems = this.systems;
  51981. // Animations.
  51982. TWEEN.update();
  51983. // Components.
  51984. for (i = 0; i < this.behaviors.tick.length; i++) {
  51985. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  51986. this.behaviors.tick[i].tick(time, timeDelta);
  51987. }
  51988. // Systems.
  51989. for (i = 0; i < this.systemNames.length; i++) {
  51990. if (!systems[this.systemNames[i]].tick) { continue; }
  51991. systems[this.systemNames[i]].tick(time, timeDelta);
  51992. }
  51993. }
  51994. },
  51995. /**
  51996. * Behavior-updater meant to be called after scene render for post processing purposes.
  51997. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  51998. * needing to render.
  51999. */
  52000. tock: {
  52001. value: function (time, timeDelta) {
  52002. var i;
  52003. var systems = this.systems;
  52004. // Components.
  52005. for (i = 0; i < this.behaviors.tock.length; i++) {
  52006. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  52007. this.behaviors.tock[i].tock(time, timeDelta);
  52008. }
  52009. // Systems.
  52010. for (i = 0; i < this.systemNames.length; i++) {
  52011. if (!systems[this.systemNames[i]].tock) { continue; }
  52012. systems[this.systemNames[i]].tock(time, timeDelta);
  52013. }
  52014. }
  52015. },
  52016. /**
  52017. * The render loop.
  52018. *
  52019. * Updates animations.
  52020. * Updates behaviors.
  52021. * Renders with request animation frame.
  52022. */
  52023. render: {
  52024. value: function () {
  52025. var effect = this.effect;
  52026. var delta = this.clock.getDelta() * 1000;
  52027. this.time = this.clock.elapsedTime * 1000;
  52028. if (this.isPlaying) { this.tick(this.time, delta); }
  52029. this.animationFrameID = effect.requestAnimationFrame(this.render);
  52030. effect.render(this.object3D, this.camera, this.renderTarget);
  52031. if (this.isPlaying) { this.tock(this.time, delta); }
  52032. this.effect.submitFrame();
  52033. },
  52034. writable: true
  52035. }
  52036. })
  52037. });
  52038. /**
  52039. * Return the canvas size where the scene will be rendered
  52040. * It will be always the window size except when the scene
  52041. * is embedded. The parent size will be returned in that case
  52042. *
  52043. * @param {object} canvasEl - the canvas element
  52044. * @param {boolean} embedded - Is the scene embedded?
  52045. */
  52046. function getCanvasSize (canvasEl, embedded) {
  52047. if (embedded) {
  52048. return {
  52049. height: canvasEl.parentElement.offsetHeight,
  52050. width: canvasEl.parentElement.offsetWidth
  52051. };
  52052. }
  52053. return {
  52054. height: window.innerHeight,
  52055. width: window.innerWidth
  52056. };
  52057. }
  52058. function requestFullscreen (canvas) {
  52059. var requestFullscreen =
  52060. canvas.requestFullscreen ||
  52061. canvas.webkitRequestFullscreen ||
  52062. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  52063. canvas.msRequestFullscreen;
  52064. requestFullscreen.apply(canvas);
  52065. }
  52066. function exitFullscreen () {
  52067. if (document.exitFullscreen) {
  52068. document.exitFullscreen();
  52069. } else if (document.mozCancelFullScreen) {
  52070. document.mozCancelFullScreen();
  52071. } else if (document.webkitExitFullscreen) {
  52072. document.webkitExitFullscreen();
  52073. }
  52074. }
  52075. /**
  52076. * Determines if renderer anti-aliasing should be enabled.
  52077. * Enabled by default if has native WebVR or is desktop.
  52078. *
  52079. * @returns {bool}
  52080. */
  52081. function shouldAntiAlias (sceneEl) {
  52082. // Explicitly set.
  52083. if (sceneEl.getAttribute('antialias') !== null) {
  52084. return sceneEl.getAttribute('antialias') === 'true';
  52085. }
  52086. // Default not AA for mobile.
  52087. return !sceneEl.isMobile;
  52088. }
  52089. module.exports.shouldAntiAlias = shouldAntiAlias; // For testing.
  52090. function setupCanvas (sceneEl) {
  52091. var canvasEl;
  52092. canvasEl = document.createElement('canvas');
  52093. canvasEl.classList.add('a-canvas');
  52094. // Mark canvas as provided/injected by A-Frame.
  52095. canvasEl.dataset.aframeCanvas = true;
  52096. sceneEl.appendChild(canvasEl);
  52097. document.addEventListener('fullscreenchange', onFullScreenChange);
  52098. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  52099. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  52100. // Prevent overscroll on mobile.
  52101. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  52102. // Set canvas on scene.
  52103. sceneEl.canvas = canvasEl;
  52104. sceneEl.emit('render-target-loaded', {target: canvasEl});
  52105. // For unknown reasons a synchronous resize does not work on desktop when
  52106. // entering/exiting fullscreen.
  52107. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  52108. function onFullScreenChange () {
  52109. var fullscreenEl =
  52110. document.fullscreenElement ||
  52111. document.mozFullScreenElement ||
  52112. document.webkitFullscreenElement;
  52113. // No fullscren element === exit fullscreen
  52114. if (!fullscreenEl) { sceneEl.exitVR(); }
  52115. document.activeElement.blur();
  52116. document.body.focus();
  52117. }
  52118. }
  52119. module.exports.setupCanvas = setupCanvas; // For testing.
  52120. },{"../../lib/three":173,"../../utils/":195,"../a-entity":121,"../a-node":123,"../a-register-element":124,"../system":135,"./metaTags":129,"./postMessage":130,"./scenes":131,"./wakelock":132,"@tweenjs/tween.js":1}],129:[function(_dereq_,module,exports){
  52121. var constants = _dereq_('../../constants/');
  52122. var extend = _dereq_('../../utils').extend;
  52123. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  52124. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  52125. // W3C-standardised meta tags.
  52126. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  52127. Meta({name: 'theme-color', content: 'black'})
  52128. ];
  52129. var MOBILE_IOS_HEAD_TAGS = [
  52130. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  52131. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  52132. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  52133. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  52134. ];
  52135. function Meta (attrs) {
  52136. return {
  52137. tagName: 'meta',
  52138. attributes: attrs,
  52139. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  52140. };
  52141. }
  52142. function Link (attrs) {
  52143. return {
  52144. tagName: 'link',
  52145. attributes: attrs,
  52146. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  52147. };
  52148. }
  52149. /**
  52150. * Injects the necessary metatags in the document for mobile support:
  52151. * 1. Prevent the user to zoom in the document.
  52152. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  52153. * values and the canvas is properly scaled.
  52154. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  52155. * iOS.
  52156. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  52157. *
  52158. * @param {object} scene - Scene element
  52159. * @returns {Array}
  52160. */
  52161. module.exports.inject = function injectHeadTags (scene) {
  52162. var headEl = document.head;
  52163. var headScriptEl = headEl.querySelector('script');
  52164. var tag;
  52165. var headTags = [];
  52166. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  52167. if (scene.isIOS) {
  52168. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  52169. }
  52170. return headTags;
  52171. function createAndInjectTag (tagObj) {
  52172. if (!tagObj || tagObj.exists()) { return; }
  52173. tag = createTag(tagObj);
  52174. if (!tag) { return; }
  52175. if (headScriptEl) {
  52176. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  52177. } else {
  52178. headEl.appendChild(tag);
  52179. }
  52180. headTags.push(tag);
  52181. }
  52182. };
  52183. function createTag (tagObj) {
  52184. if (!tagObj || !tagObj.tagName) { return; }
  52185. var meta = document.createElement(tagObj.tagName);
  52186. meta.setAttribute(constants.AFRAME_INJECTED, '');
  52187. return extend(meta, tagObj.attributes);
  52188. }
  52189. },{"../../constants/":116,"../../utils":195}],130:[function(_dereq_,module,exports){
  52190. var bind = _dereq_('../../utils/bind');
  52191. var isIframed = _dereq_('../../utils/').isIframed;
  52192. /**
  52193. * Provides a post message API for scenes contained
  52194. * in an iframe.
  52195. */
  52196. module.exports = function initPostMessageAPI (scene) {
  52197. // Handles fullscreen behavior when inside an iframe.
  52198. if (!isIframed()) { return; }
  52199. // postMessage API handler
  52200. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  52201. };
  52202. function postMessageAPIHandler (event) {
  52203. var scene = this;
  52204. if (!event.data) { return; }
  52205. switch (event.data.type) {
  52206. case 'vr': {
  52207. switch (event.data.data) {
  52208. case 'enter':
  52209. scene.enterVR();
  52210. break;
  52211. case 'exit':
  52212. scene.exitVR();
  52213. break;
  52214. }
  52215. }
  52216. }
  52217. }
  52218. },{"../../utils/":195,"../../utils/bind":189}],131:[function(_dereq_,module,exports){
  52219. /*
  52220. Scene index for keeping track of created scenes.
  52221. */
  52222. module.exports = [];
  52223. },{}],132:[function(_dereq_,module,exports){
  52224. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  52225. module.exports = function initWakelock (scene) {
  52226. if (!scene.isMobile) { return; }
  52227. var wakelock = scene.wakelock = new Wakelock();
  52228. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  52229. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  52230. };
  52231. },{"../../../vendor/wakelock/wakelock":206}],133:[function(_dereq_,module,exports){
  52232. var utils = _dereq_('../utils/');
  52233. var PropertyTypes = _dereq_('./propertyTypes');
  52234. var debug = utils.debug;
  52235. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  52236. var propertyTypes = PropertyTypes.propertyTypes;
  52237. var warn = debug('core:schema:warn');
  52238. /**
  52239. * A schema is classified as a schema for a single property if:
  52240. * - `type` is defined on the schema as a string.
  52241. * - OR `default` is defined on the schema, as a reserved keyword.
  52242. * - OR schema is empty.
  52243. */
  52244. function isSingleProperty (schema) {
  52245. if ('type' in schema) {
  52246. return typeof schema.type === 'string';
  52247. }
  52248. return 'default' in schema;
  52249. }
  52250. module.exports.isSingleProperty = isSingleProperty;
  52251. /**
  52252. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  52253. *
  52254. * @param {object} schema
  52255. * @param {string} componentName
  52256. * @returns {object} Schema.
  52257. */
  52258. module.exports.process = function (schema, componentName) {
  52259. var propName;
  52260. // For single property schema, run processPropDefinition over the whole schema.
  52261. if (isSingleProperty(schema)) {
  52262. return processPropertyDefinition(schema, componentName);
  52263. }
  52264. // For multi-property schema, run processPropDefinition over each property definition.
  52265. for (propName in schema) {
  52266. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  52267. }
  52268. return schema;
  52269. };
  52270. /**
  52271. * Inject default value, parser, stringifier for single property.
  52272. *
  52273. * @param {object} propDefinition
  52274. * @param {string} componentName
  52275. */
  52276. function processPropertyDefinition (propDefinition, componentName) {
  52277. var defaultVal = propDefinition.default;
  52278. var isCustomType;
  52279. var propType;
  52280. var typeName = propDefinition.type;
  52281. // Type inference.
  52282. if (!propDefinition.type) {
  52283. if (defaultVal !== undefined &&
  52284. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  52285. // Type inference.
  52286. typeName = typeof defaultVal;
  52287. } else if (Array.isArray(defaultVal)) {
  52288. typeName = 'array';
  52289. } else {
  52290. // Fall back to string.
  52291. typeName = 'string';
  52292. }
  52293. } else if (propDefinition.type === 'bool') {
  52294. typeName = 'boolean';
  52295. } else if (propDefinition.type === 'float') {
  52296. typeName = 'number';
  52297. }
  52298. propType = propertyTypes[typeName];
  52299. if (!propType) {
  52300. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  52301. }
  52302. // Fill in parse and stringify using property types.
  52303. isCustomType = !!propDefinition.parse;
  52304. propDefinition.parse = propDefinition.parse || propType.parse;
  52305. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  52306. // Fill in type name.
  52307. propDefinition.type = typeName;
  52308. // Check that default value exists.
  52309. if ('default' in propDefinition) {
  52310. // Check that default values are valid.
  52311. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  52312. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  52313. '` in component `' + componentName + '`');
  52314. }
  52315. } else {
  52316. // Fill in default value.
  52317. propDefinition.default = propType.default;
  52318. }
  52319. return propDefinition;
  52320. }
  52321. module.exports.processPropertyDefinition = processPropertyDefinition;
  52322. /**
  52323. * Parse propData using schema. Use default values if not existing in propData.
  52324. *
  52325. * @param {object} propData - Unparsed properties.
  52326. * @param {object} schema - Property types definition.
  52327. * @param {boolean} getPartialData - Whether to return full component data or just the data
  52328. * with keys in `propData`.
  52329. * @param {string } componentName - Name of the component, used for the property warning.
  52330. * @param {boolean} silent - Suppress warning messages.
  52331. */
  52332. module.exports.parseProperties = (function () {
  52333. var propNames = [];
  52334. return function (propData, schema, getPartialData, componentName, silent) {
  52335. var i;
  52336. var propName;
  52337. var propDefinition;
  52338. var propValue;
  52339. propNames.length = 0;
  52340. for (propName in (getPartialData ? propData : schema)) { propNames.push(propName); }
  52341. if (propData === null || typeof propData !== 'object') { return propData; }
  52342. // Validation errors.
  52343. for (propName in propData) {
  52344. if (!schema[propName] && !silent) {
  52345. warn('Unknown property `' + propName +
  52346. '` for component/system `' + componentName + '`.');
  52347. }
  52348. }
  52349. for (i = 0; i < propNames.length; i++) {
  52350. propName = propNames[i];
  52351. propDefinition = schema[propName];
  52352. propValue = propData[propName];
  52353. if (!(schema[propName])) { return; }
  52354. propData[propName] = parseProperty(propValue, propDefinition);
  52355. }
  52356. return propData;
  52357. };
  52358. })();
  52359. /**
  52360. * Deserialize a single property.
  52361. */
  52362. function parseProperty (value, propDefinition) {
  52363. // Use default value if value is falsy.
  52364. if (value === undefined || value === null || value === '') {
  52365. value = propDefinition.default;
  52366. if (Array.isArray(value)) { value = value.slice(); }
  52367. }
  52368. // Invoke property type parser.
  52369. return propDefinition.parse(value, propDefinition.default);
  52370. }
  52371. module.exports.parseProperty = parseProperty;
  52372. /**
  52373. * Serialize a group of properties.
  52374. */
  52375. module.exports.stringifyProperties = function (propData, schema) {
  52376. var propName;
  52377. var propDefinition;
  52378. var propValue;
  52379. var stringifiedData = {};
  52380. var value;
  52381. for (propName in propData) {
  52382. propDefinition = schema[propName];
  52383. propValue = propData[propName];
  52384. value = propValue;
  52385. if (typeof value === 'object') {
  52386. value = stringifyProperty(propValue, propDefinition);
  52387. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  52388. }
  52389. stringifiedData[propName] = value;
  52390. }
  52391. return stringifiedData;
  52392. };
  52393. /**
  52394. * Serialize a single property.
  52395. */
  52396. function stringifyProperty (value, propDefinition) {
  52397. // This function stringifies but it's used in a context where
  52398. // there's always second stringification pass. By returning the original
  52399. // value when it's not an object we save one unnecessary call
  52400. // to JSON.stringify.
  52401. if (typeof value !== 'object') { return value; }
  52402. // if there's no schema for the property we use standar JSON stringify
  52403. if (!propDefinition || value === null) { return JSON.stringify(value); }
  52404. return propDefinition.stringify(value);
  52405. }
  52406. module.exports.stringifyProperty = stringifyProperty;
  52407. },{"../utils/":195,"./propertyTypes":127}],134:[function(_dereq_,module,exports){
  52408. var schema = _dereq_('./schema');
  52409. var processSchema = schema.process;
  52410. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  52411. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  52412. var THREE = _dereq_('../lib/three');
  52413. var utils = _dereq_('../utils');
  52414. // A-Frame properties to three.js uniform types.
  52415. var propertyToThreeMapping = {
  52416. array: 'v3',
  52417. color: 'v3',
  52418. int: 'i',
  52419. number: 'f',
  52420. map: 't',
  52421. time: 'f',
  52422. vec2: 'v2',
  52423. vec3: 'v3',
  52424. vec4: 'v4'
  52425. };
  52426. /**
  52427. * Shader class definition.
  52428. *
  52429. * Shaders extend the material component API so you can create your own library
  52430. * of customized materials
  52431. *
  52432. */
  52433. var Shader = module.exports.Shader = function () {};
  52434. Shader.prototype = {
  52435. /**
  52436. * Contains the type schema and defaults for the data values.
  52437. * Data is coerced into the types of the values of the defaults.
  52438. */
  52439. schema: {},
  52440. vertexShader:
  52441. 'void main() {' +
  52442. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  52443. '}',
  52444. fragmentShader:
  52445. 'void main() {' +
  52446. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  52447. '}',
  52448. /**
  52449. * Init handler. Similar to attachedCallback.
  52450. * Called during shader initialization and is only run once.
  52451. */
  52452. init: function (data) {
  52453. this.attributes = this.initVariables(data, 'attribute');
  52454. this.uniforms = this.initVariables(data, 'uniform');
  52455. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  52456. // attributes: this.attributes,
  52457. uniforms: this.uniforms,
  52458. vertexShader: this.vertexShader,
  52459. fragmentShader: this.fragmentShader
  52460. });
  52461. return this.material;
  52462. },
  52463. initVariables: function (data, type) {
  52464. var variables = {};
  52465. var schema = this.schema;
  52466. Object.keys(schema).forEach(function processSchema (key) {
  52467. if (schema[key].is !== type) { return; }
  52468. var varType = propertyToThreeMapping[schema[key].type];
  52469. variables[key] = {
  52470. type: varType,
  52471. value: undefined // Let updateVariables handle setting these.
  52472. };
  52473. });
  52474. return variables;
  52475. },
  52476. /**
  52477. * Update handler. Similar to attributeChangedCallback.
  52478. * Called whenever the associated material data changes.
  52479. *
  52480. * @param {object} data - New material data.
  52481. */
  52482. update: function (data) {
  52483. this.updateVariables(data, 'attribute');
  52484. this.updateVariables(data, 'uniform');
  52485. },
  52486. updateVariables: function (data, type) {
  52487. var self = this;
  52488. var variables = type === 'uniform' ? this.uniforms : this.attributes;
  52489. var schema = this.schema;
  52490. Object.keys(data).forEach(function processData (key) {
  52491. var materialKey;
  52492. if (!schema[key] || schema[key].is !== type) { return; }
  52493. if (schema[key].type === 'map') {
  52494. // If data unchanged, get out early.
  52495. if (!variables[key] || variables[key].value === data[key]) { return; }
  52496. // Special handling is needed for textures.
  52497. materialKey = '_texture_' + key;
  52498. // We can't actually set the variable correctly until we've loaded the texture.
  52499. self.el.addEventListener('materialtextureloaded', function () {
  52500. variables[key].value = self.material[materialKey];
  52501. variables[key].needsUpdate = true;
  52502. });
  52503. // Kick off the texture update now that handler is added.
  52504. utils.material.updateMapMaterialFromData(materialKey, key, self, data);
  52505. return;
  52506. }
  52507. variables[key].value = self.parseValue(schema[key].type, data[key]);
  52508. variables[key].needsUpdate = true;
  52509. });
  52510. },
  52511. parseValue: function (type, value) {
  52512. var color;
  52513. switch (type) {
  52514. case 'vec2': {
  52515. return new THREE.Vector2(value.x, value.y);
  52516. }
  52517. case 'vec3': {
  52518. return new THREE.Vector3(value.x, value.y, value.z);
  52519. }
  52520. case 'vec4': {
  52521. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  52522. }
  52523. case 'color': {
  52524. color = new THREE.Color(value);
  52525. return new THREE.Vector3(color.r, color.g, color.b);
  52526. }
  52527. case 'map': {
  52528. return THREE.ImageUtils.loadTexture(value);
  52529. }
  52530. default: {
  52531. return value;
  52532. }
  52533. }
  52534. }
  52535. };
  52536. /**
  52537. * Registers a shader to A-Frame.
  52538. *
  52539. * @param {string} name - shader name.
  52540. * @param {object} definition - shader property and methods.
  52541. * @returns {object} Shader.
  52542. */
  52543. module.exports.registerShader = function (name, definition) {
  52544. var NewShader;
  52545. var proto = {};
  52546. // Format definition object to prototype object.
  52547. Object.keys(definition).forEach(function (key) {
  52548. proto[key] = {
  52549. value: definition[key],
  52550. writable: true
  52551. };
  52552. });
  52553. if (shaders[name]) {
  52554. throw new Error('The shader ' + name + ' has been already registered');
  52555. }
  52556. NewShader = function () { Shader.call(this); };
  52557. NewShader.prototype = Object.create(Shader.prototype, proto);
  52558. NewShader.prototype.name = name;
  52559. NewShader.prototype.constructor = NewShader;
  52560. shaders[name] = {
  52561. Shader: NewShader,
  52562. schema: processSchema(NewShader.prototype.schema)
  52563. };
  52564. shaderNames.push(name);
  52565. return NewShader;
  52566. };
  52567. },{"../lib/three":173,"../utils":195,"./schema":133}],135:[function(_dereq_,module,exports){
  52568. var components = _dereq_('./component');
  52569. var schema = _dereq_('./schema');
  52570. var utils = _dereq_('../utils/');
  52571. var parseProperties = schema.parseProperties;
  52572. var parseProperty = schema.parseProperty;
  52573. var processSchema = schema.process;
  52574. var isSingleProp = schema.isSingleProperty;
  52575. var styleParser = utils.styleParser;
  52576. var systems = module.exports.systems = {}; // Keep track of registered systems.
  52577. /**
  52578. * System class definition.
  52579. *
  52580. * Systems provide global scope and services to a group of instantiated components of the
  52581. * same class. They can also help abstract logic away from components such that components
  52582. * only have to worry about data.
  52583. *
  52584. * For example, a physics component that creates a physics world that oversees
  52585. * all entities with a physics or rigid body component.
  52586. *
  52587. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  52588. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  52589. * setAttribute behavior).
  52590. *
  52591. * @member {string} name - Name that system is registered under.
  52592. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  52593. */
  52594. var System = module.exports.System = function (sceneEl) {
  52595. var component = components && components.components[this.name];
  52596. // Set reference to scene.
  52597. this.el = sceneEl;
  52598. this.sceneEl = sceneEl;
  52599. // Set reference to matching component (if exists).
  52600. if (component) { component.Component.prototype.system = this; }
  52601. // Process system configuration.
  52602. this.buildData();
  52603. this.init();
  52604. this.update({});
  52605. };
  52606. System.prototype = {
  52607. /**
  52608. * Schema to configure system.
  52609. */
  52610. schema: {},
  52611. /**
  52612. * Init handler. Called during scene initialization and is only run once.
  52613. * Systems can use this to set initial state.
  52614. */
  52615. init: function () { /* no-op */ },
  52616. /**
  52617. * Update handler. Called during scene attribute updates.
  52618. * Systems can use this to dynamically update their state.
  52619. */
  52620. update: function (oldData) { /* no-op */ },
  52621. /**
  52622. * Build data and call update handler.
  52623. *
  52624. * @private
  52625. */
  52626. updateProperties: function (rawData) {
  52627. var oldData = this.data;
  52628. if (!Object.keys(schema).length) { return; }
  52629. this.buildData(rawData);
  52630. this.update(oldData);
  52631. },
  52632. /**
  52633. * Parse data.
  52634. */
  52635. buildData: function (rawData) {
  52636. var schema = this.schema;
  52637. if (!Object.keys(schema).length) { return; }
  52638. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  52639. if (isSingleProp(schema)) {
  52640. this.data = parseProperty(rawData, schema);
  52641. } else {
  52642. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  52643. }
  52644. },
  52645. /**
  52646. * Tick handler.
  52647. * Called on each tick of the scene render loop.
  52648. * Affected by play and pause.
  52649. *
  52650. * @param {number} time - Scene tick time.
  52651. * @param {number} timeDelta - Difference in current render time and previous render time.
  52652. */
  52653. tick: undefined,
  52654. /**
  52655. * Tock handler.
  52656. * Called on each tock of the scene render loop.
  52657. * Affected by play and pause.
  52658. *
  52659. * @param {number} time - Scene tick time.
  52660. * @param {number} timeDelta - Difference in current render time and previous render time.
  52661. */
  52662. tock: undefined,
  52663. /**
  52664. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  52665. */
  52666. play: function () { /* no-op */ },
  52667. /**
  52668. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  52669. */
  52670. pause: function () { /* no-op */ }
  52671. };
  52672. /**
  52673. * Registers a system to A-Frame.
  52674. *
  52675. * @param {string} name - Component name.
  52676. * @param {object} definition - Component property and methods.
  52677. * @returns {object} Component.
  52678. */
  52679. module.exports.registerSystem = function (name, definition) {
  52680. var i;
  52681. var NewSystem;
  52682. var proto = {};
  52683. var scenes = utils.findAllScenes(document);
  52684. // Format definition object to prototype object.
  52685. Object.keys(definition).forEach(function (key) {
  52686. proto[key] = {
  52687. value: definition[key],
  52688. writable: true
  52689. };
  52690. });
  52691. if (systems[name]) {
  52692. throw new Error('The system `' + name + '` has been already registered. ' +
  52693. 'Check that you are not loading two versions of the same system ' +
  52694. 'or two different systems of the same name.');
  52695. }
  52696. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  52697. NewSystem.prototype = Object.create(System.prototype, proto);
  52698. NewSystem.prototype.name = name;
  52699. NewSystem.prototype.constructor = NewSystem;
  52700. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  52701. systems[name] = NewSystem;
  52702. // Initialize systems for existing scenes
  52703. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  52704. };
  52705. },{"../utils/":195,"./component":125,"./schema":133}],136:[function(_dereq_,module,exports){
  52706. _dereq_('./pivot');
  52707. },{"./pivot":137}],137:[function(_dereq_,module,exports){
  52708. var registerComponent = _dereq_('../../core/component').registerComponent;
  52709. var THREE = _dereq_('../../lib/three');
  52710. var originalPosition = new THREE.Vector3();
  52711. var originalRotation = new THREE.Vector3();
  52712. /**
  52713. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  52714. */
  52715. registerComponent('pivot', {
  52716. dependencies: ['position'],
  52717. schema: {type: 'vec3'},
  52718. init: function () {
  52719. var data = this.data;
  52720. var el = this.el;
  52721. var originalParent = el.object3D.parent;
  52722. var originalGroup = el.object3D;
  52723. var outerGroup = new THREE.Group();
  52724. originalPosition.copy(originalGroup.position);
  52725. originalRotation.copy(originalGroup.rotation);
  52726. // Detach current group from parent.
  52727. originalParent.remove(originalGroup);
  52728. outerGroup.add(originalGroup);
  52729. // Set new group as the outer group.
  52730. originalParent.add(outerGroup);
  52731. // Set outer group as new object3D.
  52732. el.object3D = outerGroup;
  52733. // Apply pivot to original group.
  52734. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  52735. // Offset the pivot so that world position not affected.
  52736. // And restore position onto outer group.
  52737. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  52738. data.z + originalPosition.z);
  52739. // Transfer rotation to outer group.
  52740. outerGroup.rotation.copy(originalGroup.rotation);
  52741. originalGroup.rotation.set(0, 0, 0);
  52742. }
  52743. });
  52744. },{"../../core/component":125,"../../lib/three":173}],138:[function(_dereq_,module,exports){
  52745. /**
  52746. * Common mesh defaults, mappings, and transforms.
  52747. */
  52748. var components = _dereq_('../../core/component').components;
  52749. var shaders = _dereq_('../../core/shader').shaders;
  52750. var utils = _dereq_('../../utils/');
  52751. var materialMappings = {};
  52752. Object.keys(components.material.schema).forEach(addMapping);
  52753. Object.keys(shaders.standard.schema).forEach(addMapping);
  52754. function addMapping (prop) {
  52755. // To hyphenated.
  52756. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52757. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  52758. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  52759. materialMappings[htmlAttrName] = 'material.' + prop;
  52760. }
  52761. module.exports = function getMeshMixin () {
  52762. return {
  52763. defaultComponents: {material: {}},
  52764. mappings: utils.extend({}, materialMappings)
  52765. };
  52766. };
  52767. },{"../../core/component":125,"../../core/shader":134,"../../utils/":195}],139:[function(_dereq_,module,exports){
  52768. _dereq_('./primitives/a-camera');
  52769. _dereq_('./primitives/a-collada-model');
  52770. _dereq_('./primitives/a-cursor');
  52771. _dereq_('./primitives/a-curvedimage');
  52772. _dereq_('./primitives/a-gltf-model');
  52773. _dereq_('./primitives/a-image');
  52774. _dereq_('./primitives/a-light');
  52775. _dereq_('./primitives/a-link');
  52776. _dereq_('./primitives/a-obj-model');
  52777. _dereq_('./primitives/a-sky');
  52778. _dereq_('./primitives/a-sound');
  52779. _dereq_('./primitives/a-text');
  52780. _dereq_('./primitives/a-video');
  52781. _dereq_('./primitives/a-videosphere');
  52782. _dereq_('./primitives/meshPrimitives');
  52783. },{"./primitives/a-camera":141,"./primitives/a-collada-model":142,"./primitives/a-cursor":143,"./primitives/a-curvedimage":144,"./primitives/a-gltf-model":145,"./primitives/a-image":146,"./primitives/a-light":147,"./primitives/a-link":148,"./primitives/a-obj-model":149,"./primitives/a-sky":150,"./primitives/a-sound":151,"./primitives/a-text":152,"./primitives/a-video":153,"./primitives/a-videosphere":154,"./primitives/meshPrimitives":155}],140:[function(_dereq_,module,exports){
  52784. var AEntity = _dereq_('../../core/a-entity');
  52785. var components = _dereq_('../../core/component').components;
  52786. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  52787. var utils = _dereq_('../../utils/');
  52788. var debug = utils.debug;
  52789. var setComponentProperty = utils.entity.setComponentProperty;
  52790. var log = debug('extras:primitives:debug');
  52791. var warn = debug('extras:primitives:warn');
  52792. var primitives = module.exports.primitives = {};
  52793. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  52794. name = name.toLowerCase();
  52795. log('Registering <%s>', name);
  52796. // Deprecation warning for defaultAttributes usage.
  52797. if (definition.defaultAttributes) {
  52798. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  52799. }
  52800. var primitive = registerElement(name, {
  52801. prototype: Object.create(AEntity.prototype, {
  52802. defaultComponentsFromPrimitive: {
  52803. value: definition.defaultComponents || definition.defaultAttributes || {}
  52804. },
  52805. deprecated: {value: definition.deprecated || null},
  52806. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  52807. mappings: {value: definition.mappings || {}},
  52808. createdCallback: {
  52809. value: function () {
  52810. if (definition.deprecated) { console.warn(definition.deprecated); }
  52811. this.resolveMappingCollisions();
  52812. }
  52813. },
  52814. /**
  52815. * If a mapping collides with a registered component name
  52816. * it renames the mapping to componentname-property
  52817. */
  52818. resolveMappingCollisions: {
  52819. value: function () {
  52820. var mappings = this.mappings;
  52821. var self = this;
  52822. Object.keys(mappings).forEach(function resolveCollision (key) {
  52823. var newAttribute;
  52824. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  52825. if (components[key]) {
  52826. newAttribute = mappings[key].replace('.', '-');
  52827. mappings[newAttribute] = mappings[key];
  52828. delete mappings[key];
  52829. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  52830. 'The attribute ' + key + ' has the same name as a registered component and' +
  52831. ' has been renamed to ' + newAttribute);
  52832. }
  52833. });
  52834. }
  52835. },
  52836. getExtraComponents: {
  52837. value: function () {
  52838. var attr;
  52839. var data;
  52840. var i;
  52841. var mapping;
  52842. var mixins;
  52843. var path;
  52844. var self = this;
  52845. // Gather component data from default components.
  52846. data = utils.clone(this.defaultComponentsFromPrimitive);
  52847. // Factor in mixins to overwrite default components.
  52848. mixins = this.getAttribute('mixin');
  52849. if (mixins) {
  52850. mixins = mixins.trim().split(' ');
  52851. mixins.forEach(function applyMixin (mixinId) {
  52852. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  52853. Object.keys(mixinComponents).forEach(function setComponent (name) {
  52854. data[name] = extend(data[name], mixinComponents[name]);
  52855. });
  52856. });
  52857. }
  52858. // Gather component data from mappings.
  52859. for (i = 0; i < this.attributes.length; i++) {
  52860. attr = this.attributes[i];
  52861. mapping = this.mappings[attr.name];
  52862. if (mapping) {
  52863. path = utils.entity.getComponentPropertyPath(mapping);
  52864. if (path.constructor === Array) {
  52865. data[path[0]] = data[path[0]] || {};
  52866. data[path[0]][path[1]] = attr.value.trim();
  52867. } else {
  52868. data[path] = attr.value.trim();
  52869. }
  52870. continue;
  52871. }
  52872. }
  52873. return data;
  52874. /**
  52875. * For the base to be extensible, both objects must be pure JavaScript objects.
  52876. * The function assumes that base is undefined, or null or a pure object.
  52877. */
  52878. function extend (base, extension) {
  52879. if (isUndefined(base)) {
  52880. return copy(extension);
  52881. }
  52882. if (isUndefined(extension)) {
  52883. return copy(base);
  52884. }
  52885. if (isPureObject(base) && isPureObject(extension)) {
  52886. return utils.extendDeep(base, extension);
  52887. }
  52888. return copy(extension);
  52889. }
  52890. function isUndefined (value) {
  52891. return typeof value === 'undefined';
  52892. }
  52893. function copy (value) {
  52894. if (isPureObject(value)) {
  52895. return utils.extendDeep({}, value);
  52896. }
  52897. return value;
  52898. }
  52899. function isPureObject (value) {
  52900. return value !== null && value.constructor === Object;
  52901. }
  52902. }
  52903. },
  52904. /**
  52905. * Sync to attribute to component property whenever mapped attribute changes.
  52906. * If attribute is mapped to a component property, set the component property using
  52907. * the attribute value.
  52908. */
  52909. attributeChangedCallback: {
  52910. value: function (attr, oldVal, value) {
  52911. var componentName = this.mappings[attr];
  52912. if (attr in this.deprecatedMappings) {
  52913. console.warn(this.deprecatedMappings[attr]);
  52914. }
  52915. if (!attr || !componentName) { return; }
  52916. // Set value.
  52917. setComponentProperty(this, componentName, value);
  52918. }
  52919. }
  52920. })
  52921. });
  52922. // Store.
  52923. primitives[name] = primitive;
  52924. return primitive;
  52925. };
  52926. /**
  52927. * Add component mappings using schema.
  52928. */
  52929. function addComponentMapping (componentName, mappings) {
  52930. var schema = components[componentName].schema;
  52931. Object.keys(schema).map(function (prop) {
  52932. // Hyphenate where there is camelCase.
  52933. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52934. // If there is a mapping collision, prefix with component name and hyphen.
  52935. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  52936. mappings[attrName] = componentName + '.' + prop;
  52937. });
  52938. }
  52939. /**
  52940. * Helper to define a primitive, building mappings using a component schema.
  52941. */
  52942. function definePrimitive (tagName, defaultComponents, mappings) {
  52943. // If no initial mappings provided, start from empty map.
  52944. mappings = mappings || {};
  52945. // From the default components, add mapping automagically.
  52946. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  52947. addComponentMapping(componentName, mappings);
  52948. });
  52949. // Register the primitive.
  52950. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  52951. defaultComponents: defaultComponents,
  52952. mappings: mappings
  52953. }));
  52954. }
  52955. module.exports.definePrimitive = definePrimitive;
  52956. },{"../../core/a-entity":121,"../../core/a-register-element":124,"../../core/component":125,"../../utils/":195}],141:[function(_dereq_,module,exports){
  52957. var DEFAULT_CAMERA_HEIGHT = _dereq_('../../../constants/').DEFAULT_CAMERA_HEIGHT;
  52958. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52959. registerPrimitive('a-camera', {
  52960. defaultComponents: {
  52961. camera: {
  52962. userHeight: DEFAULT_CAMERA_HEIGHT
  52963. },
  52964. 'look-controls': {},
  52965. 'wasd-controls': {}
  52966. },
  52967. mappings: {
  52968. active: 'camera.active',
  52969. far: 'camera.far',
  52970. fov: 'camera.fov',
  52971. 'look-controls-enabled': 'look-controls.enabled',
  52972. near: 'camera.near',
  52973. 'wasd-controls-enabled': 'wasd-controls.enabled',
  52974. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  52975. 'user-height': 'camera.userHeight',
  52976. zoom: 'camera.zoom'
  52977. },
  52978. deprecatedMappings: {
  52979. 'cursor-color': 'a-camera[cursor-color] has been removed. Use a-cursor[color] instead.',
  52980. 'cursor-maxdistance': 'a-camera[cursor-maxdistance] has been removed. Use a-cursor[max-distance] instead.',
  52981. 'cursor-offset': 'a-camera[cursor-offset] has been removed. Use a-cursor[position] instead.',
  52982. 'cursor-opacity': 'a-camera[cursor-offset] has been removed. Use a-cursor[opacity] instead.',
  52983. 'cursor-scale': 'a-camera[cursor-scale] has been removed. Use a-cursor[scale] instead.',
  52984. 'cursor-visible': 'a-camera[cursor-visible] has been removed. Use a-cursor[visible] instead.'
  52985. }
  52986. });
  52987. },{"../../../constants/":116,"../primitives":140}],142:[function(_dereq_,module,exports){
  52988. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52989. registerPrimitive('a-collada-model', {
  52990. mappings: {
  52991. src: 'collada-model'
  52992. }
  52993. });
  52994. },{"../primitives":140}],143:[function(_dereq_,module,exports){
  52995. var getMeshMixin = _dereq_('../getMeshMixin');
  52996. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52997. var utils = _dereq_('../../../utils/');
  52998. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  52999. defaultComponents: {
  53000. cursor: {},
  53001. geometry: {
  53002. primitive: 'ring',
  53003. radiusOuter: 0.016,
  53004. radiusInner: 0.01,
  53005. segmentsTheta: 32
  53006. },
  53007. material: {
  53008. color: '#000',
  53009. shader: 'flat',
  53010. opacity: 0.8
  53011. },
  53012. position: {
  53013. x: 0,
  53014. y: 0,
  53015. z: -1
  53016. }
  53017. },
  53018. mappings: {
  53019. far: 'raycaster.far',
  53020. fuse: 'cursor.fuse',
  53021. 'fuse-timeout': 'cursor.fuseTimeout',
  53022. interval: 'raycaster.interval',
  53023. objects: 'raycaster.objects'
  53024. }
  53025. }));
  53026. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],144:[function(_dereq_,module,exports){
  53027. var getMeshMixin = _dereq_('../getMeshMixin');
  53028. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53029. var utils = _dereq_('../../../utils/');
  53030. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  53031. defaultComponents: {
  53032. geometry: {
  53033. height: 1,
  53034. primitive: 'cylinder',
  53035. radius: 2,
  53036. segmentsRadial: 48,
  53037. thetaLength: 270,
  53038. openEnded: true,
  53039. thetaStart: 0
  53040. },
  53041. material: {
  53042. color: '#FFF',
  53043. shader: 'flat',
  53044. side: 'double',
  53045. transparent: true,
  53046. repeat: '-1 1'
  53047. }
  53048. },
  53049. mappings: {
  53050. height: 'geometry.height',
  53051. 'open-ended': 'geometry.openEnded',
  53052. radius: 'geometry.radius',
  53053. segments: 'geometry.segmentsRadial',
  53054. start: 'geometry.thetaStart',
  53055. 'theta-length': 'geometry.thetaLength',
  53056. 'theta-start': 'geometry.thetaStart',
  53057. 'width': 'geometry.thetaLength'
  53058. }
  53059. }));
  53060. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],145:[function(_dereq_,module,exports){
  53061. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53062. registerPrimitive('a-gltf-model', {
  53063. mappings: {
  53064. src: 'gltf-model'
  53065. }
  53066. });
  53067. },{"../primitives":140}],146:[function(_dereq_,module,exports){
  53068. var getMeshMixin = _dereq_('../getMeshMixin');
  53069. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53070. var utils = _dereq_('../../../utils/');
  53071. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  53072. defaultComponents: {
  53073. geometry: {
  53074. primitive: 'plane'
  53075. },
  53076. material: {
  53077. color: '#FFF',
  53078. shader: 'flat',
  53079. side: 'double',
  53080. transparent: true
  53081. }
  53082. },
  53083. mappings: {
  53084. height: 'geometry.height',
  53085. width: 'geometry.width'
  53086. }
  53087. }));
  53088. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],147:[function(_dereq_,module,exports){
  53089. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53090. registerPrimitive('a-light', {
  53091. defaultComponents: {
  53092. light: {}
  53093. },
  53094. mappings: {
  53095. angle: 'light.angle',
  53096. color: 'light.color',
  53097. 'ground-color': 'light.groundColor',
  53098. decay: 'light.decay',
  53099. distance: 'light.distance',
  53100. intensity: 'light.intensity',
  53101. penumbra: 'light.penumbra',
  53102. type: 'light.type',
  53103. target: 'light.target'
  53104. }
  53105. });
  53106. },{"../primitives":140}],148:[function(_dereq_,module,exports){
  53107. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53108. registerPrimitive('a-link', {
  53109. defaultComponents: {},
  53110. mappings: {
  53111. href: 'link.href',
  53112. image: 'link.image',
  53113. title: 'link.title'
  53114. }
  53115. });
  53116. },{"../primitives":140}],149:[function(_dereq_,module,exports){
  53117. var meshMixin = _dereq_('../getMeshMixin')();
  53118. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53119. var utils = _dereq_('../../../utils/');
  53120. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  53121. defaultComponents: {
  53122. 'obj-model': {}
  53123. },
  53124. mappings: {
  53125. src: 'obj-model.obj',
  53126. mtl: 'obj-model.mtl'
  53127. }
  53128. }));
  53129. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],150:[function(_dereq_,module,exports){
  53130. var getMeshMixin = _dereq_('../getMeshMixin');
  53131. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53132. var utils = _dereq_('../../../utils/');
  53133. var meshPrimitives = _dereq_('./meshPrimitives');
  53134. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  53135. defaultComponents: {
  53136. geometry: {
  53137. primitive: 'sphere',
  53138. radius: 5000,
  53139. segmentsWidth: 64,
  53140. segmentsHeight: 32
  53141. },
  53142. material: {
  53143. color: '#FFF',
  53144. shader: 'flat',
  53145. npot: true
  53146. },
  53147. scale: '-1 1 1'
  53148. },
  53149. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  53150. }));
  53151. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140,"./meshPrimitives":155}],151:[function(_dereq_,module,exports){
  53152. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53153. registerPrimitive('a-sound', {
  53154. defaultComponents: {
  53155. sound: {}
  53156. },
  53157. mappings: {
  53158. src: 'sound.src',
  53159. on: 'sound.on',
  53160. autoplay: 'sound.autoplay',
  53161. loop: 'sound.loop',
  53162. volume: 'sound.volume'
  53163. }
  53164. });
  53165. },{"../primitives":140}],152:[function(_dereq_,module,exports){
  53166. // <a-text> using `definePrimitive` helper.
  53167. var definePrimitive = _dereq_('../primitives').definePrimitive;
  53168. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  53169. },{"../primitives":140}],153:[function(_dereq_,module,exports){
  53170. var getMeshMixin = _dereq_('../getMeshMixin');
  53171. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53172. var utils = _dereq_('../../../utils/');
  53173. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  53174. defaultComponents: {
  53175. geometry: {
  53176. primitive: 'plane'
  53177. },
  53178. material: {
  53179. color: '#FFF',
  53180. shader: 'flat',
  53181. side: 'double',
  53182. transparent: true
  53183. }
  53184. },
  53185. mappings: {
  53186. height: 'geometry.height',
  53187. width: 'geometry.width'
  53188. }
  53189. }));
  53190. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],154:[function(_dereq_,module,exports){
  53191. var getMeshMixin = _dereq_('../getMeshMixin');
  53192. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53193. var utils = _dereq_('../../../utils/');
  53194. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  53195. defaultComponents: {
  53196. geometry: {
  53197. primitive: 'sphere',
  53198. radius: 5000,
  53199. segmentsWidth: 64,
  53200. segmentsHeight: 32
  53201. },
  53202. material: {
  53203. color: '#FFF',
  53204. shader: 'flat',
  53205. npot: true
  53206. },
  53207. scale: '-1 1 1'
  53208. },
  53209. mappings: {
  53210. radius: 'geometry.radius',
  53211. 'segments-height': 'geometry.segmentsHeight',
  53212. 'segments-width': 'geometry.segmentsWidth'
  53213. }
  53214. }));
  53215. },{"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],155:[function(_dereq_,module,exports){
  53216. /**
  53217. * Automated mesh primitive registration.
  53218. */
  53219. var getMeshMixin = _dereq_('../getMeshMixin');
  53220. var geometries = _dereq_('../../../core/geometry').geometries;
  53221. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  53222. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53223. var utils = _dereq_('../../../utils/');
  53224. // For testing.
  53225. var meshPrimitives = module.exports = {};
  53226. // Generate primitive for each geometry type.
  53227. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  53228. var geometry = geometries[geometryName];
  53229. var geometryHyphened = unCamelCase(geometryName);
  53230. // Generate mappings.
  53231. var mappings = {};
  53232. Object.keys(geometry.schema).forEach(function createMapping (property) {
  53233. mappings[unCamelCase(property)] = 'geometry.' + property;
  53234. });
  53235. // Register.
  53236. var tagName = 'a-' + geometryHyphened;
  53237. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  53238. defaultComponents: {geometry: {primitive: geometryName}},
  53239. mappings: mappings
  53240. }));
  53241. meshPrimitives[tagName] = primitive;
  53242. });
  53243. /**
  53244. * camelCase to hyphened-string.
  53245. */
  53246. function unCamelCase (str) {
  53247. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53248. }
  53249. },{"../../../core/geometry":126,"../../../utils/":195,"../getMeshMixin":138,"../primitives":140}],156:[function(_dereq_,module,exports){
  53250. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53251. var THREE = _dereq_('../lib/three');
  53252. registerGeometry('box', {
  53253. schema: {
  53254. depth: {default: 1, min: 0},
  53255. height: {default: 1, min: 0},
  53256. width: {default: 1, min: 0},
  53257. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  53258. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  53259. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  53260. },
  53261. init: function (data) {
  53262. this.geometry = new THREE.BoxGeometry(
  53263. data.width, data.height, data.depth,
  53264. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  53265. }
  53266. });
  53267. },{"../core/geometry":126,"../lib/three":173}],157:[function(_dereq_,module,exports){
  53268. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53269. var THREE = _dereq_('../lib/three');
  53270. var degToRad = THREE.Math.degToRad;
  53271. registerGeometry('circle', {
  53272. schema: {
  53273. radius: {default: 1, min: 0},
  53274. segments: {default: 32, min: 3, type: 'int'},
  53275. thetaLength: {default: 360, min: 0},
  53276. thetaStart: {default: 0}
  53277. },
  53278. init: function (data) {
  53279. this.geometry = new THREE.CircleGeometry(
  53280. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  53281. }
  53282. });
  53283. },{"../core/geometry":126,"../lib/three":173}],158:[function(_dereq_,module,exports){
  53284. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53285. var THREE = _dereq_('../lib/three');
  53286. var degToRad = THREE.Math.degToRad;
  53287. registerGeometry('cone', {
  53288. schema: {
  53289. height: {default: 1, min: 0},
  53290. openEnded: {default: false},
  53291. radiusBottom: {default: 1, min: 0},
  53292. radiusTop: {default: 0.01, min: 0},
  53293. segmentsHeight: {default: 18, min: 1, type: 'int'},
  53294. segmentsRadial: {default: 36, min: 3, type: 'int'},
  53295. thetaLength: {default: 360, min: 0},
  53296. thetaStart: {default: 0}
  53297. },
  53298. init: function (data) {
  53299. this.geometry = new THREE.CylinderGeometry(
  53300. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  53301. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  53302. degToRad(data.thetaLength));
  53303. }
  53304. });
  53305. },{"../core/geometry":126,"../lib/three":173}],159:[function(_dereq_,module,exports){
  53306. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53307. var THREE = _dereq_('../lib/three');
  53308. var degToRad = THREE.Math.degToRad;
  53309. registerGeometry('cylinder', {
  53310. schema: {
  53311. height: {default: 1, min: 0},
  53312. openEnded: {default: false},
  53313. radius: {default: 1, min: 0},
  53314. segmentsHeight: {default: 18, min: 1, type: 'int'},
  53315. segmentsRadial: {default: 36, min: 3, type: 'int'},
  53316. thetaLength: {default: 360, min: 0},
  53317. thetaStart: {default: 0}
  53318. },
  53319. init: function (data) {
  53320. this.geometry = new THREE.CylinderGeometry(
  53321. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  53322. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  53323. }
  53324. });
  53325. },{"../core/geometry":126,"../lib/three":173}],160:[function(_dereq_,module,exports){
  53326. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53327. var THREE = _dereq_('../lib/three');
  53328. registerGeometry('dodecahedron', {
  53329. schema: {
  53330. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53331. radius: {default: 1, min: 0}
  53332. },
  53333. init: function (data) {
  53334. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  53335. }
  53336. });
  53337. },{"../core/geometry":126,"../lib/three":173}],161:[function(_dereq_,module,exports){
  53338. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53339. var THREE = _dereq_('../lib/three');
  53340. registerGeometry('icosahedron', {
  53341. schema: {
  53342. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53343. radius: {default: 1, min: 0}
  53344. },
  53345. init: function (data) {
  53346. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  53347. }
  53348. });
  53349. },{"../core/geometry":126,"../lib/three":173}],162:[function(_dereq_,module,exports){
  53350. _dereq_('./box.js');
  53351. _dereq_('./circle.js');
  53352. _dereq_('./cone.js');
  53353. _dereq_('./cylinder.js');
  53354. _dereq_('./dodecahedron.js');
  53355. _dereq_('./icosahedron.js');
  53356. _dereq_('./octahedron.js');
  53357. _dereq_('./plane.js');
  53358. _dereq_('./ring.js');
  53359. _dereq_('./sphere.js');
  53360. _dereq_('./tetrahedron.js');
  53361. _dereq_('./torus.js');
  53362. _dereq_('./torusKnot.js');
  53363. _dereq_('./triangle.js');
  53364. },{"./box.js":156,"./circle.js":157,"./cone.js":158,"./cylinder.js":159,"./dodecahedron.js":160,"./icosahedron.js":161,"./octahedron.js":163,"./plane.js":164,"./ring.js":165,"./sphere.js":166,"./tetrahedron.js":167,"./torus.js":168,"./torusKnot.js":169,"./triangle.js":170}],163:[function(_dereq_,module,exports){
  53365. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53366. var THREE = _dereq_('../lib/three');
  53367. registerGeometry('octahedron', {
  53368. schema: {
  53369. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53370. radius: {default: 1, min: 0}
  53371. },
  53372. init: function (data) {
  53373. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  53374. }
  53375. });
  53376. },{"../core/geometry":126,"../lib/three":173}],164:[function(_dereq_,module,exports){
  53377. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53378. var THREE = _dereq_('../lib/three');
  53379. registerGeometry('plane', {
  53380. schema: {
  53381. height: {default: 1, min: 0},
  53382. width: {default: 1, min: 0},
  53383. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  53384. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  53385. },
  53386. init: function (data) {
  53387. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  53388. }
  53389. });
  53390. },{"../core/geometry":126,"../lib/three":173}],165:[function(_dereq_,module,exports){
  53391. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53392. var THREE = _dereq_('../lib/three');
  53393. var degToRad = THREE.Math.degToRad;
  53394. registerGeometry('ring', {
  53395. schema: {
  53396. radiusInner: {default: 0.8, min: 0},
  53397. radiusOuter: {default: 1.2, min: 0},
  53398. segmentsPhi: {default: 10, min: 1, type: 'int'},
  53399. segmentsTheta: {default: 32, min: 3, type: 'int'},
  53400. thetaLength: {default: 360, min: 0},
  53401. thetaStart: {default: 0}
  53402. },
  53403. init: function (data) {
  53404. this.geometry = new THREE.RingGeometry(
  53405. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  53406. degToRad(data.thetaStart), degToRad(data.thetaLength));
  53407. }
  53408. });
  53409. },{"../core/geometry":126,"../lib/three":173}],166:[function(_dereq_,module,exports){
  53410. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53411. var THREE = _dereq_('../lib/three');
  53412. var degToRad = THREE.Math.degToRad;
  53413. registerGeometry('sphere', {
  53414. schema: {
  53415. radius: {default: 1, min: 0},
  53416. phiLength: {default: 360},
  53417. phiStart: {default: 0, min: 0},
  53418. thetaLength: {default: 180, min: 0},
  53419. thetaStart: {default: 0},
  53420. segmentsHeight: {default: 18, min: 2, type: 'int'},
  53421. segmentsWidth: {default: 36, min: 3, type: 'int'}
  53422. },
  53423. init: function (data) {
  53424. this.geometry = new THREE.SphereGeometry(
  53425. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  53426. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  53427. }
  53428. });
  53429. },{"../core/geometry":126,"../lib/three":173}],167:[function(_dereq_,module,exports){
  53430. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53431. var THREE = _dereq_('../lib/three');
  53432. registerGeometry('tetrahedron', {
  53433. schema: {
  53434. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53435. radius: {default: 1, min: 0}
  53436. },
  53437. init: function (data) {
  53438. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  53439. }
  53440. });
  53441. },{"../core/geometry":126,"../lib/three":173}],168:[function(_dereq_,module,exports){
  53442. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53443. var THREE = _dereq_('../lib/three');
  53444. var degToRad = THREE.Math.degToRad;
  53445. registerGeometry('torus', {
  53446. schema: {
  53447. arc: {default: 360},
  53448. radius: {default: 1, min: 0},
  53449. radiusTubular: {default: 0.2, min: 0},
  53450. segmentsRadial: {default: 36, min: 2, type: 'int'},
  53451. segmentsTubular: {default: 32, min: 3, type: 'int'}
  53452. },
  53453. init: function (data) {
  53454. this.geometry = new THREE.TorusGeometry(
  53455. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  53456. degToRad(data.arc));
  53457. }
  53458. });
  53459. },{"../core/geometry":126,"../lib/three":173}],169:[function(_dereq_,module,exports){
  53460. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53461. var THREE = _dereq_('../lib/three');
  53462. registerGeometry('torusKnot', {
  53463. schema: {
  53464. p: {default: 2, min: 1},
  53465. q: {default: 3, min: 1},
  53466. radius: {default: 1, min: 0},
  53467. radiusTubular: {default: 0.2, min: 0},
  53468. segmentsRadial: {default: 8, min: 3, type: 'int'},
  53469. segmentsTubular: {default: 100, min: 3, type: 'int'}
  53470. },
  53471. init: function (data) {
  53472. this.geometry = new THREE.TorusKnotGeometry(
  53473. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  53474. data.p, data.q);
  53475. }
  53476. });
  53477. },{"../core/geometry":126,"../lib/three":173}],170:[function(_dereq_,module,exports){
  53478. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53479. var THREE = _dereq_('../lib/three');
  53480. var quaternion = new THREE.Quaternion();
  53481. var rotateVector = new THREE.Vector3(0, 0, 1);
  53482. var uvMinVector = new THREE.Vector2();
  53483. var uvMaxVector = new THREE.Vector2();
  53484. var uvScaleVector = new THREE.Vector2();
  53485. registerGeometry('triangle', {
  53486. schema: {
  53487. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  53488. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  53489. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  53490. },
  53491. init: function (data) {
  53492. var geometry;
  53493. var normal;
  53494. var triangle;
  53495. var uvA;
  53496. var uvB;
  53497. var uvC;
  53498. triangle = new THREE.Triangle();
  53499. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  53500. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  53501. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  53502. normal = triangle.normal();
  53503. // Rotate the 3D triangle to be parallel to XY plane.
  53504. quaternion.setFromUnitVectors(normal, rotateVector);
  53505. uvA = triangle.a.clone().applyQuaternion(quaternion);
  53506. uvB = triangle.b.clone().applyQuaternion(quaternion);
  53507. uvC = triangle.c.clone().applyQuaternion(quaternion);
  53508. // Compute UVs.
  53509. // Normalize x/y values of UV so they are within 0 to 1.
  53510. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  53511. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  53512. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  53513. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  53514. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  53515. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  53516. geometry = this.geometry = new THREE.Geometry();
  53517. geometry.vertices.push(triangle.a);
  53518. geometry.vertices.push(triangle.b);
  53519. geometry.vertices.push(triangle.c);
  53520. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  53521. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  53522. }
  53523. });
  53524. },{"../core/geometry":126,"../lib/three":173}],171:[function(_dereq_,module,exports){
  53525. var utils = _dereq_('./utils/');
  53526. var debug = utils.debug;
  53527. var error = debug('A-Frame:error');
  53528. var warn = debug('A-Frame:warn');
  53529. if (window.document.currentScript && window.document.currentScript.parentNode !==
  53530. window.document.head && !window.debug) {
  53531. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  53532. 'ensure everything for A-Frame is properly registered before they are used from ' +
  53533. 'HTML.');
  53534. }
  53535. // Error if not using a server.
  53536. if (window.location.protocol === 'file:') {
  53537. error(
  53538. 'This HTML file is currently being served via the file:// protocol. ' +
  53539. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  53540. 'Please use a local or hosted server: ' +
  53541. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  53542. }
  53543. // Polyfill `Promise`.
  53544. window.Promise = window.Promise || _dereq_('promise-polyfill');
  53545. // Check before the polyfill runs.
  53546. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays || !!window.navigator.getVRDevices;
  53547. window.WebVRConfig = window.WebVRConfig || {
  53548. BUFFER_SCALE: 1,
  53549. CARDBOARD_UI_DISABLED: true,
  53550. ROTATE_INSTRUCTIONS_DISABLED: true,
  53551. TOUCH_PANNER_DISABLED: true,
  53552. MOUSE_KEYBOARD_CONTROLS_DISABLED: true
  53553. };
  53554. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  53555. // Only for iOS on versions older than 10.
  53556. if (utils.device.isIOSOlderThan10(window.navigator.userAgent)) {
  53557. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  53558. }
  53559. // WebVR polyfill
  53560. _dereq_('webvr-polyfill');
  53561. _dereq_('present'); // Polyfill `performance.now()`.
  53562. // CSS.
  53563. if (utils.device.isBrowserEnvironment) {
  53564. _dereq_('./style/aframe.css');
  53565. _dereq_('./style/rStats.css');
  53566. }
  53567. // Required before `AEntity` so that all components are registered.
  53568. var AScene = _dereq_('./core/scene/a-scene').AScene;
  53569. var components = _dereq_('./core/component').components;
  53570. var registerComponent = _dereq_('./core/component').registerComponent;
  53571. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  53572. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  53573. var registerShader = _dereq_('./core/shader').registerShader;
  53574. var registerSystem = _dereq_('./core/system').registerSystem;
  53575. var shaders = _dereq_('./core/shader').shaders;
  53576. var systems = _dereq_('./core/system').systems;
  53577. // Exports THREE to window so three.js can be used without alteration.
  53578. var THREE = window.THREE = _dereq_('./lib/three');
  53579. var TWEEN = window.TWEEN = _dereq_('@tweenjs/tween.js');
  53580. var pkg = _dereq_('../package');
  53581. _dereq_('./components/index'); // Register standard components.
  53582. _dereq_('./geometries/index'); // Register standard geometries.
  53583. _dereq_('./shaders/index'); // Register standard shaders.
  53584. _dereq_('./systems/index'); // Register standard systems.
  53585. var ANode = _dereq_('./core/a-node');
  53586. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  53587. _dereq_('./core/a-animation');
  53588. _dereq_('./core/a-assets');
  53589. _dereq_('./core/a-cubemap');
  53590. _dereq_('./core/a-mixin');
  53591. // Extras.
  53592. _dereq_('./extras/components/');
  53593. _dereq_('./extras/primitives/');
  53594. console.log('A-Frame Version: 0.7.0 (Date 19-10-2017, Commit #187f520)');
  53595. console.log('three Version:', pkg.dependencies['three']);
  53596. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  53597. module.exports = window.AFRAME = {
  53598. AComponent: _dereq_('./core/component').Component,
  53599. AEntity: AEntity,
  53600. ANode: ANode,
  53601. AScene: AScene,
  53602. components: components,
  53603. geometries: _dereq_('./core/geometry').geometries,
  53604. registerComponent: registerComponent,
  53605. registerElement: _dereq_('./core/a-register-element').registerElement,
  53606. registerGeometry: registerGeometry,
  53607. registerPrimitive: registerPrimitive,
  53608. registerShader: registerShader,
  53609. registerSystem: registerSystem,
  53610. primitives: {
  53611. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  53612. primitives: _dereq_('./extras/primitives/primitives').primitives
  53613. },
  53614. scenes: _dereq_('./core/scene/scenes'),
  53615. schema: _dereq_('./core/schema'),
  53616. shaders: shaders,
  53617. systems: systems,
  53618. THREE: THREE,
  53619. TWEEN: TWEEN,
  53620. utils: utils,
  53621. version: pkg.version
  53622. };
  53623. },{"../package":76,"./components/index":85,"./core/a-animation":118,"./core/a-assets":119,"./core/a-cubemap":120,"./core/a-entity":121,"./core/a-mixin":122,"./core/a-node":123,"./core/a-register-element":124,"./core/component":125,"./core/geometry":126,"./core/scene/a-scene":128,"./core/scene/scenes":131,"./core/schema":133,"./core/shader":134,"./core/system":135,"./extras/components/":136,"./extras/primitives/":139,"./extras/primitives/getMeshMixin":138,"./extras/primitives/primitives":140,"./geometries/index":162,"./lib/three":173,"./shaders/index":175,"./style/aframe.css":180,"./style/rStats.css":181,"./systems/index":184,"./utils/":195,"@tweenjs/tween.js":1,"present":32,"promise-polyfill":34,"webvr-polyfill":61}],172:[function(_dereq_,module,exports){
  53624. window.aframeStats = function (scene) {
  53625. var _rS = null;
  53626. var _scene = scene;
  53627. var _values = {
  53628. te: {
  53629. caption: 'Entities'
  53630. },
  53631. lt: {
  53632. caption: 'Load Time'
  53633. }
  53634. };
  53635. var _groups = [ {
  53636. caption: 'A-Frame',
  53637. values: [ 'te', 'lt' ]
  53638. } ];
  53639. function _update () {
  53640. _rS('te').set(getEntityCount());
  53641. if (window.performance.getEntriesByName) {
  53642. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  53643. }
  53644. }
  53645. function getEntityCount () {
  53646. var elements = _scene.querySelectorAll('*');
  53647. Array.prototype.slice.call(elements).filter(function (el) {
  53648. return el.isEntity;
  53649. });
  53650. return elements.length;
  53651. }
  53652. function _start () {}
  53653. function _end () {}
  53654. function _attach (r) {
  53655. _rS = r;
  53656. }
  53657. return {
  53658. update: _update,
  53659. start: _start,
  53660. end: _end,
  53661. attach: _attach,
  53662. values: _values,
  53663. groups: _groups,
  53664. fractions: []
  53665. };
  53666. };
  53667. if (typeof module === 'object') {
  53668. module.exports = {
  53669. aframeStats: window.aframeStats
  53670. };
  53671. }
  53672. },{}],173:[function(_dereq_,module,exports){
  53673. (function (global){
  53674. var THREE = global.THREE = _dereq_('three');
  53675. // Allow cross-origin images to be loaded.
  53676. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  53677. // Must be on `THREE.TextureLoader`.
  53678. if (THREE.TextureLoader) {
  53679. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  53680. }
  53681. // This is for images loaded from the model loaders.
  53682. if (THREE.ImageLoader) {
  53683. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  53684. }
  53685. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  53686. if (THREE.Cache) {
  53687. THREE.Cache.enabled = true;
  53688. }
  53689. // TODO: Eventually include these only if they are needed by a component.
  53690. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  53691. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  53692. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  53693. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  53694. _dereq_('../../vendor/VRControls'); // THREE.VRControls
  53695. _dereq_('../../vendor/VREffect'); // THREE.VREffect
  53696. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  53697. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  53698. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  53699. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  53700. module.exports = THREE;
  53701. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  53702. },{"../../vendor/VRControls":201,"../../vendor/VREffect":202,"three":41,"three/examples/js/loaders/ColladaLoader":42,"three/examples/js/loaders/GLTFLoader":43,"three/examples/js/loaders/MTLLoader":44,"three/examples/js/loaders/OBJLoader":45}],174:[function(_dereq_,module,exports){
  53703. var registerShader = _dereq_('../core/shader').registerShader;
  53704. var THREE = _dereq_('../lib/three');
  53705. var utils = _dereq_('../utils/');
  53706. /**
  53707. * Flat shader using THREE.MeshBasicMaterial.
  53708. */
  53709. module.exports.Shader = registerShader('flat', {
  53710. schema: {
  53711. color: {type: 'color'},
  53712. fog: {default: true},
  53713. height: {default: 256},
  53714. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53715. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53716. src: {type: 'map'},
  53717. width: {default: 512},
  53718. wireframe: {default: false},
  53719. wireframeLinewidth: {default: 2}
  53720. },
  53721. /**
  53722. * Initializes the shader.
  53723. * Adds a reference from the scene to this entity as the camera.
  53724. */
  53725. init: function (data) {
  53726. this.textureSrc = null;
  53727. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  53728. utils.material.updateMap(this, data);
  53729. },
  53730. update: function (data) {
  53731. this.updateMaterial(data);
  53732. utils.material.updateMap(this, data);
  53733. },
  53734. /**
  53735. * Updating existing material.
  53736. *
  53737. * @param {object} data - Material component data.
  53738. */
  53739. updateMaterial: function (data) {
  53740. var material = this.material;
  53741. data = getMaterialData(data);
  53742. Object.keys(data).forEach(function (key) {
  53743. material[key] = data[key];
  53744. });
  53745. }
  53746. });
  53747. /**
  53748. * Builds and normalize material data, normalizing stuff along the way.
  53749. *
  53750. * @param {object} data - Material data.
  53751. * @returns {object} data - Processed material data.
  53752. */
  53753. function getMaterialData (data) {
  53754. return {
  53755. fog: data.fog,
  53756. color: new THREE.Color(data.color),
  53757. wireframe: data.wireframe,
  53758. wireframeLinewidth: data.wireframeLinewidth
  53759. };
  53760. }
  53761. },{"../core/shader":134,"../lib/three":173,"../utils/":195}],175:[function(_dereq_,module,exports){
  53762. _dereq_('./flat');
  53763. _dereq_('./standard');
  53764. _dereq_('./sdf');
  53765. _dereq_('./msdf');
  53766. _dereq_('./ios10hls');
  53767. },{"./flat":174,"./ios10hls":176,"./msdf":177,"./sdf":178,"./standard":179}],176:[function(_dereq_,module,exports){
  53768. var registerShader = _dereq_('../core/shader').registerShader;
  53769. /**
  53770. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  53771. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  53772. */
  53773. module.exports.Shader = registerShader('ios10hls', {
  53774. schema: {
  53775. src: {type: 'map', is: 'uniform'},
  53776. opacity: {type: 'number', is: 'uniform', default: 1}
  53777. },
  53778. vertexShader: [
  53779. 'varying vec2 vUV;',
  53780. 'void main(void) {',
  53781. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53782. ' vUV = uv;',
  53783. '}'
  53784. ].join('\n'),
  53785. fragmentShader: [
  53786. 'uniform sampler2D src;',
  53787. 'uniform float opacity;',
  53788. 'varying vec2 vUV;',
  53789. 'void main() {',
  53790. ' vec2 offset = vec2(0, 0);',
  53791. ' vec2 repeat = vec2(1, 1);',
  53792. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  53793. ' gl_FragColor = vec4(color.rgb, opacity);',
  53794. '}'
  53795. ].join('\n')
  53796. });
  53797. },{"../core/shader":134}],177:[function(_dereq_,module,exports){
  53798. var registerShader = _dereq_('../core/shader').registerShader;
  53799. /**
  53800. * Multi-channel signed distance field.
  53801. * Used by text component.
  53802. */
  53803. module.exports.Shader = registerShader('msdf', {
  53804. schema: {
  53805. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53806. color: {type: 'color', is: 'uniform', default: 'white'},
  53807. map: {type: 'map', is: 'uniform'},
  53808. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53809. },
  53810. raw: true,
  53811. vertexShader: [
  53812. 'attribute vec2 uv;',
  53813. 'attribute vec3 position;',
  53814. 'uniform mat4 projectionMatrix;',
  53815. 'uniform mat4 modelViewMatrix;',
  53816. 'varying vec2 vUV;',
  53817. 'void main(void) {',
  53818. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53819. ' vUV = uv;',
  53820. '}'
  53821. ].join('\n'),
  53822. fragmentShader: [
  53823. '#ifdef GL_OES_standard_derivatives',
  53824. '#extension GL_OES_standard_derivatives: enable',
  53825. '#endif',
  53826. 'precision highp float;',
  53827. // FIXME: Experimentally determined constants.
  53828. '#define BIG_ENOUGH 0.001',
  53829. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53830. '#define ALL_SMOOTH 0.4',
  53831. '#define ALL_ROUGH 0.02',
  53832. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53833. 'uniform sampler2D map;',
  53834. 'uniform vec3 color;',
  53835. 'uniform float opacity;',
  53836. 'uniform float alphaTest;',
  53837. 'varying vec2 vUV;',
  53838. 'float median(float r, float g, float b) {',
  53839. ' return max(min(r, g), min(max(r, g), b));',
  53840. '}',
  53841. 'void main() {',
  53842. ' vec3 sample = 1.0 - texture2D(map, vUV).rgb;',
  53843. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  53844. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  53845. ' float dscale = 0.353505;',
  53846. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  53847. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53848. // When texel is too small, blend raw alpha value rather than supersampling.
  53849. // FIXME: Experimentally determined constant.
  53850. ' if (isBigEnough > BIG_ENOUGH) {',
  53851. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53852. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  53853. ' }',
  53854. // When texel is big enough, do standard alpha test.
  53855. // FIXME: Experimentally determined constant.
  53856. // Looks much better if we *don't* do this, but do we get Z fighting?
  53857. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  53858. // Else, do modified alpha test.
  53859. // FIXME: Experimentally determined constant.
  53860. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53861. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  53862. '}'
  53863. ].join('\n')
  53864. });
  53865. },{"../core/shader":134}],178:[function(_dereq_,module,exports){
  53866. var registerShader = _dereq_('../core/shader').registerShader;
  53867. /**
  53868. * Signed distance field.
  53869. * Used by text component.
  53870. */
  53871. module.exports.Shader = registerShader('sdf', {
  53872. schema: {
  53873. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53874. color: {type: 'color', is: 'uniform', default: 'white'},
  53875. map: {type: 'map', is: 'uniform'},
  53876. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53877. },
  53878. raw: true,
  53879. vertexShader: [
  53880. 'attribute vec2 uv;',
  53881. 'attribute vec3 position;',
  53882. 'uniform mat4 projectionMatrix;',
  53883. 'uniform mat4 modelViewMatrix;',
  53884. 'varying vec2 vUV;',
  53885. 'void main(void) {',
  53886. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53887. ' vUV = uv;',
  53888. '}'
  53889. ].join('\n'),
  53890. fragmentShader: [
  53891. '#ifdef GL_OES_standard_derivatives',
  53892. '#extension GL_OES_standard_derivatives: enable',
  53893. '#endif',
  53894. 'precision highp float;',
  53895. // FIXME: experimentally determined constants
  53896. '#define BIG_ENOUGH 0.001',
  53897. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53898. '#define ALL_SMOOTH 0.4',
  53899. '#define ALL_ROUGH 0.02',
  53900. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53901. 'uniform sampler2D map;',
  53902. 'uniform vec3 color;',
  53903. 'uniform float opacity;',
  53904. 'uniform float alphaTest;',
  53905. 'varying vec2 vUV;',
  53906. '#ifdef GL_OES_standard_derivatives',
  53907. 'float contour(float width, float value) {',
  53908. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  53909. '}',
  53910. '#else',
  53911. 'float aastep(float value, float afwidth) {',
  53912. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  53913. '}',
  53914. '#endif',
  53915. 'void main() {',
  53916. '#ifdef GL_OES_standard_derivatives',
  53917. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  53918. ' vec2 uv = vUV;',
  53919. ' vec4 texColor = texture2D(map, uv);',
  53920. ' float dist = texColor.a;',
  53921. ' float width = fwidth(dist);',
  53922. ' float alpha = contour(dist, width);',
  53923. ' float dscale = 0.353505;',
  53924. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  53925. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53926. // when texel is too small, blend raw alpha value rather than supersampling etc.
  53927. // FIXME: experimentally determined constant
  53928. ' if (isBigEnough > BIG_ENOUGH) {',
  53929. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53930. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  53931. ' }',
  53932. // otherwise do weighted supersampling
  53933. // FIXME: why this weighting?
  53934. ' else if (isBigEnough <= BIG_ENOUGH) {',
  53935. ' vec4 box = vec4 (uv - duv, uv + duv);',
  53936. ' alpha = (alpha + 0.5 * (',
  53937. ' contour(texture2D(map, box.xy).a, width)',
  53938. ' + contour(texture2D(map, box.zw).a, width)',
  53939. ' + contour(texture2D(map, box.xw).a, width)',
  53940. ' + contour(texture2D(map, box.zy).a, width)',
  53941. ' )) / 3.0;',
  53942. ' }',
  53943. // when texel is big enough, do standard alpha test
  53944. // FIXME: experimentally determined constant
  53945. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  53946. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  53947. // else do modified alpha test
  53948. // FIXME: experimentally determined constant
  53949. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53950. '#else',
  53951. ' vec4 texColor = texture2D(map, vUV);',
  53952. ' float value = texColor.a;',
  53953. // when we don't have derivatives, use approximations
  53954. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53955. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  53956. ' float alpha = aastep(value, afwidth);',
  53957. // use gl_FragCoord.w to guess when we should blend
  53958. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53959. ' 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);',
  53960. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  53961. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  53962. ' if (ratio < 1.0)',
  53963. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  53964. '#endif',
  53965. ' gl_FragColor = vec4(color, opacity * alpha);',
  53966. '}'
  53967. ].join('\n')
  53968. });
  53969. },{"../core/shader":134}],179:[function(_dereq_,module,exports){
  53970. var registerShader = _dereq_('../core/shader').registerShader;
  53971. var THREE = _dereq_('../lib/three');
  53972. var utils = _dereq_('../utils/');
  53973. var CubeLoader = new THREE.CubeTextureLoader();
  53974. var texturePromises = {};
  53975. /**
  53976. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  53977. */
  53978. module.exports.Shader = registerShader('standard', {
  53979. schema: {
  53980. ambientOcclusionMap: {type: 'map'},
  53981. ambientOcclusionMapIntensity: {default: 1},
  53982. ambientOcclusionTextureOffset: {type: 'vec2'},
  53983. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53984. color: {type: 'color'},
  53985. displacementMap: {type: 'map'},
  53986. displacementScale: {default: 1},
  53987. displacementBias: {default: 0.5},
  53988. displacementTextureOffset: {type: 'vec2'},
  53989. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53990. emissive: {type: 'color', default: '#000'},
  53991. emissiveIntensity: {default: 1},
  53992. envMap: {default: ''},
  53993. fog: {default: true},
  53994. height: {default: 256},
  53995. metalness: {default: 0.0, min: 0.0, max: 1.0},
  53996. normalMap: {type: 'map'},
  53997. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  53998. normalTextureOffset: {type: 'vec2'},
  53999. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  54000. offset: {type: 'vec2', default: {x: 0, y: 0}},
  54001. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  54002. roughness: {default: 0.5, min: 0.0, max: 1.0},
  54003. sphericalEnvMap: {type: 'map'},
  54004. src: {type: 'map'},
  54005. width: {default: 512},
  54006. wireframe: {default: false},
  54007. wireframeLinewidth: {default: 2}
  54008. },
  54009. /**
  54010. * Initializes the shader.
  54011. * Adds a reference from the scene to this entity as the camera.
  54012. */
  54013. init: function (data) {
  54014. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  54015. utils.material.updateMap(this, data);
  54016. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  54017. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  54018. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  54019. this.updateEnvMap(data);
  54020. },
  54021. update: function (data) {
  54022. this.updateMaterial(data);
  54023. utils.material.updateMap(this, data);
  54024. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  54025. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  54026. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  54027. this.updateEnvMap(data);
  54028. },
  54029. /**
  54030. * Updating existing material.
  54031. *
  54032. * @param {object} data - Material component data.
  54033. * @returns {object} Material.
  54034. */
  54035. updateMaterial: function (data) {
  54036. var material = this.material;
  54037. data = getMaterialData(data);
  54038. Object.keys(data).forEach(function (key) {
  54039. material[key] = data[key];
  54040. });
  54041. },
  54042. /**
  54043. * Handle environment cubemap. Textures are cached in texturePromises.
  54044. */
  54045. updateEnvMap: function (data) {
  54046. var self = this;
  54047. var material = this.material;
  54048. var envMap = data.envMap;
  54049. var sphericalEnvMap = data.sphericalEnvMap;
  54050. // No envMap defined or already loading.
  54051. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  54052. material.envMap = null;
  54053. material.needsUpdate = true;
  54054. return;
  54055. }
  54056. this.isLoadingEnvMap = true;
  54057. // if a spherical env map is defined then use it.
  54058. if (sphericalEnvMap) {
  54059. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  54060. self.isLoadingEnvMap = false;
  54061. texture.mapping = THREE.SphericalReflectionMapping;
  54062. material.envMap = texture;
  54063. utils.material.handleTextureEvents(self.el, texture);
  54064. material.needsUpdate = true;
  54065. });
  54066. return;
  54067. }
  54068. // Another material is already loading this texture. Wait on promise.
  54069. if (texturePromises[envMap]) {
  54070. texturePromises[envMap].then(function (cube) {
  54071. self.isLoadingEnvMap = false;
  54072. material.envMap = cube;
  54073. utils.material.handleTextureEvents(self.el, cube);
  54074. material.needsUpdate = true;
  54075. });
  54076. return;
  54077. }
  54078. // Material is first to load this texture. Load and resolve texture.
  54079. texturePromises[envMap] = new Promise(function (resolve) {
  54080. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  54081. CubeLoader.load(urls, function (cube) {
  54082. // Texture loaded.
  54083. self.isLoadingEnvMap = false;
  54084. material.envMap = cube;
  54085. utils.material.handleTextureEvents(self.el, cube);
  54086. resolve(cube);
  54087. });
  54088. });
  54089. });
  54090. }
  54091. });
  54092. /**
  54093. * Builds and normalize material data, normalizing stuff along the way.
  54094. *
  54095. * @param {object} data - Material data.
  54096. * @returns {object} data - Processed material data.
  54097. */
  54098. function getMaterialData (data) {
  54099. var newData = {
  54100. color: new THREE.Color(data.color),
  54101. emissive: new THREE.Color(data.emissive),
  54102. emissiveIntensity: data.emissiveIntensity,
  54103. fog: data.fog,
  54104. metalness: data.metalness,
  54105. roughness: data.roughness,
  54106. wireframe: data.wireframe,
  54107. wireframeLinewidth: data.wireframeLinewidth
  54108. };
  54109. if (data.normalMap) { newData.normalScale = data.normalScale; }
  54110. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  54111. if (data.displacementMap) {
  54112. newData.displacementScale = data.displacementScale;
  54113. newData.displacementBias = data.displacementBias;
  54114. }
  54115. return newData;
  54116. }
  54117. },{"../core/shader":134,"../lib/three":173,"../utils/":195}],180:[function(_dereq_,module,exports){
  54118. var css = ".a-html{bottom:0;left:0;position:fixed;right:0;top:0}.a-body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}:-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}.a-canvas.a-grab-cursor:active,.a-grabbing{cursor:grabbing;cursor:-moz-grabbing;cursor:-webkit-grabbing}// Class is removed when doing <a-scene embedded>. a-scene.fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;z-index:999999!important;position:fixed!important}.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.embedded{right:5px;bottom:5px}.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}"; (_dereq_("browserify-css").createStyle(css, { "href": "src/style/aframe.css"})); module.exports = css;
  54119. },{"browserify-css":5}],181:[function(_dereq_,module,exports){
  54120. 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;
  54121. },{"browserify-css":5}],182:[function(_dereq_,module,exports){
  54122. var bind = _dereq_('../utils/bind');
  54123. var constants = _dereq_('../constants/');
  54124. var registerSystem = _dereq_('../core/system').registerSystem;
  54125. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  54126. /**
  54127. * Camera system. Manages which camera is active among multiple cameras in scene.
  54128. *
  54129. * @member {object} activeCameraEl - Active camera entity.
  54130. */
  54131. module.exports.System = registerSystem('camera', {
  54132. init: function () {
  54133. this.activeCameraEl = null;
  54134. // Wait for all entities to fully load before checking for existence of camera.
  54135. // Since entities wait for <a-assets> to load, any cameras attaching to the scene
  54136. // will do so asynchronously.
  54137. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultCamera, this));
  54138. },
  54139. /**
  54140. * Create a default camera if user has not added one during the initial scene traversal.
  54141. *
  54142. * Default camera offset height is at average eye level (~1.6m).
  54143. */
  54144. setupDefaultCamera: function () {
  54145. var sceneEl = this.sceneEl;
  54146. var defaultCameraEl;
  54147. // Camera already defined.
  54148. if (sceneEl.camera) {
  54149. sceneEl.emit('camera-ready', {cameraEl: sceneEl.camera.el});
  54150. return;
  54151. }
  54152. // Set up default camera.
  54153. defaultCameraEl = document.createElement('a-entity');
  54154. defaultCameraEl.setAttribute('position', '0 0 0');
  54155. defaultCameraEl.setAttribute(DEFAULT_CAMERA_ATTR, '');
  54156. defaultCameraEl.setAttribute('camera', {active: true, userHeight: constants.DEFAULT_CAMERA_HEIGHT});
  54157. defaultCameraEl.setAttribute('wasd-controls', '');
  54158. defaultCameraEl.setAttribute('look-controls', '');
  54159. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  54160. sceneEl.appendChild(defaultCameraEl);
  54161. sceneEl.addEventListener('enter-vr', this.removeDefaultOffset);
  54162. sceneEl.addEventListener('exit-vr', this.addDefaultOffset);
  54163. sceneEl.emit('camera-ready', {cameraEl: defaultCameraEl});
  54164. },
  54165. /**
  54166. * Set a different active camera.
  54167. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  54168. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  54169. * the new camera.
  54170. */
  54171. disableActiveCamera: function () {
  54172. var cameraEls = this.sceneEl.querySelectorAll('[camera]');
  54173. var newActiveCameraEl = cameraEls[cameraEls.length - 1];
  54174. newActiveCameraEl.setAttribute('camera', 'active', true);
  54175. },
  54176. /**
  54177. * Set active camera to be used by renderer.
  54178. * Removes the default camera (if present).
  54179. * Disables all other cameras in the scene.
  54180. *
  54181. * @param {Element} newCameraEl - Entity with camera component.
  54182. */
  54183. setActiveCamera: function (newCameraEl) {
  54184. var cameraEl;
  54185. var cameraEls;
  54186. var i;
  54187. var newCamera;
  54188. var previousCamera = this.activeCameraEl;
  54189. var sceneEl = this.sceneEl;
  54190. // Same camera.
  54191. newCamera = newCameraEl.getObject3D('camera');
  54192. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  54193. // Grab the default camera.
  54194. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  54195. var defaultCameraEl = defaultCameraWrapper &&
  54196. defaultCameraWrapper.querySelector('[camera]');
  54197. // Remove default camera if new camera is not the default camera.
  54198. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  54199. // Make new camera active.
  54200. this.activeCameraEl = newCameraEl;
  54201. this.activeCameraEl.play();
  54202. sceneEl.camera = newCamera;
  54203. // Disable current camera
  54204. if (previousCamera) {
  54205. previousCamera.setAttribute('camera', 'active', false);
  54206. }
  54207. // Disable other cameras in the scene
  54208. cameraEls = sceneEl.querySelectorAll('[camera]');
  54209. for (i = 0; i < cameraEls.length; i++) {
  54210. cameraEl = cameraEls[i];
  54211. if (newCameraEl === cameraEl) { continue; }
  54212. cameraEl.setAttribute('camera', 'active', false);
  54213. cameraEl.pause();
  54214. }
  54215. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  54216. }
  54217. });
  54218. /**
  54219. * Remove injected default camera from scene, if present.
  54220. *
  54221. * @param {Element} sceneEl
  54222. */
  54223. function removeDefaultCamera (sceneEl) {
  54224. var defaultCamera;
  54225. var camera = sceneEl.camera;
  54226. if (!camera) { return; }
  54227. // Remove default camera if present.
  54228. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  54229. if (!defaultCamera) { return; }
  54230. sceneEl.removeChild(defaultCamera);
  54231. }
  54232. },{"../constants/":116,"../core/system":135,"../utils/bind":189}],183:[function(_dereq_,module,exports){
  54233. var geometries = _dereq_('../core/geometry').geometries;
  54234. var registerSystem = _dereq_('../core/system').registerSystem;
  54235. var THREE = _dereq_('../lib/three');
  54236. /**
  54237. * System for geometry component.
  54238. * Handle geometry caching.
  54239. *
  54240. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  54241. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  54242. * know whether to dispose on removal.
  54243. */
  54244. module.exports.System = registerSystem('geometry', {
  54245. init: function () {
  54246. this.cache = {};
  54247. this.cacheCount = {};
  54248. },
  54249. /**
  54250. * Reset cache. Mainly for testing.
  54251. */
  54252. clearCache: function () {
  54253. this.cache = {};
  54254. this.cacheCount = {};
  54255. },
  54256. /**
  54257. * Attempt to retrieve from cache.
  54258. *
  54259. * @returns {Object|null} A geometry if it exists, else null.
  54260. */
  54261. getOrCreateGeometry: function (data) {
  54262. var cache = this.cache;
  54263. var cachedGeometry;
  54264. var hash;
  54265. // Skip all caching logic.
  54266. if (data.skipCache || data.mergeTo) { return createGeometry(data); }
  54267. // Try to retrieve from cache first.
  54268. hash = this.hash(data);
  54269. cachedGeometry = cache[hash];
  54270. incrementCacheCount(this.cacheCount, hash);
  54271. if (cachedGeometry) { return cachedGeometry; }
  54272. // Create geometry.
  54273. cachedGeometry = createGeometry(data);
  54274. // Cache and return geometry.
  54275. cache[hash] = cachedGeometry;
  54276. return cachedGeometry;
  54277. },
  54278. /**
  54279. * Let system know that an entity is no longer using a geometry.
  54280. */
  54281. unuseGeometry: function (data) {
  54282. var cache = this.cache;
  54283. var cacheCount = this.cacheCount;
  54284. var geometry;
  54285. var hash;
  54286. if (data.skipCache || data.mergeTo) { return; }
  54287. hash = this.hash(data);
  54288. if (!cache[hash]) { return; }
  54289. decrementCacheCount(cacheCount, hash);
  54290. // Another entity is still using this geometry. No need to do anything.
  54291. if (cacheCount[hash] > 0) { return; }
  54292. // No more entities are using this geometry. Dispose.
  54293. geometry = cache[hash];
  54294. geometry.dispose();
  54295. delete cache[hash];
  54296. delete cacheCount[hash];
  54297. },
  54298. /**
  54299. * Use JSON.stringify to turn component data into hash.
  54300. * Should be deterministic within a single browser engine.
  54301. * If not, then look into json-stable-stringify.
  54302. */
  54303. hash: function (data) {
  54304. return JSON.stringify(data);
  54305. }
  54306. });
  54307. /**
  54308. * Create geometry using component data.
  54309. *
  54310. * @param {object} data - Component data.
  54311. * @returns {object} Geometry.
  54312. */
  54313. function createGeometry (data) {
  54314. var geometryType = data.primitive;
  54315. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  54316. var geometryInstance = new GeometryClass();
  54317. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  54318. geometryInstance.init(data);
  54319. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  54320. }
  54321. /**
  54322. * Decreate count of entity using a geometry.
  54323. */
  54324. function decrementCacheCount (cacheCount, hash) {
  54325. cacheCount[hash]--;
  54326. }
  54327. /**
  54328. * Increase count of entity using a geometry.
  54329. */
  54330. function incrementCacheCount (cacheCount, hash) {
  54331. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  54332. }
  54333. /**
  54334. * Transform geometry to BufferGeometry if `doBuffer`.
  54335. *
  54336. * @param {object} geometry
  54337. * @param {boolean} doBuffer
  54338. * @returns {object} Geometry.
  54339. */
  54340. function toBufferGeometry (geometry, doBuffer) {
  54341. var bufferGeometry;
  54342. if (!doBuffer) { return geometry; }
  54343. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  54344. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  54345. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  54346. return bufferGeometry;
  54347. }
  54348. },{"../core/geometry":126,"../core/system":135,"../lib/three":173}],184:[function(_dereq_,module,exports){
  54349. _dereq_('./camera');
  54350. _dereq_('./geometry');
  54351. _dereq_('./light');
  54352. _dereq_('./material');
  54353. _dereq_('./shadow');
  54354. _dereq_('./tracked-controls');
  54355. },{"./camera":182,"./geometry":183,"./light":185,"./material":186,"./shadow":187,"./tracked-controls":188}],185:[function(_dereq_,module,exports){
  54356. var registerSystem = _dereq_('../core/system').registerSystem;
  54357. var bind = _dereq_('../utils/bind');
  54358. var constants = _dereq_('../constants/');
  54359. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  54360. /**
  54361. * Light system.
  54362. *
  54363. * Prescribes default lighting if not specified (one ambient, one directional).
  54364. * Removes default lighting from the scene when a new light is added.
  54365. *
  54366. * @param {bool} defaultLights - Whether default lighting are defined.
  54367. * @param {bool} userDefinedLights - Whether user lighting is defined.
  54368. */
  54369. module.exports.System = registerSystem('light', {
  54370. schema: {
  54371. defaultLightsEnabled: {default: true}
  54372. },
  54373. init: function () {
  54374. this.defaultLights = false;
  54375. this.userDefinedLights = false;
  54376. // Wait for all entities to fully load before checking for existence of lights.
  54377. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  54378. // will do so asynchronously.
  54379. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  54380. },
  54381. /**
  54382. * Notify scene that light has been added and to remove the default.
  54383. *
  54384. * @param {object} el - element holding the light component.
  54385. */
  54386. registerLight: function (el) {
  54387. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  54388. // User added a light, remove default lights through DOM.
  54389. this.removeDefaultLights();
  54390. this.userDefinedLights = true;
  54391. }
  54392. },
  54393. removeDefaultLights: function () {
  54394. var defaultLights;
  54395. var sceneEl = this.sceneEl;
  54396. if (!this.defaultLights) { return; }
  54397. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  54398. for (var i = 0; i < defaultLights.length; i++) {
  54399. sceneEl.removeChild(defaultLights[i]);
  54400. }
  54401. this.defaultLights = false;
  54402. },
  54403. /**
  54404. * Prescibe default lights to the scene.
  54405. * Does so by injecting markup such that this state is not invisible.
  54406. * These lights are removed if the user adds any lights.
  54407. */
  54408. setupDefaultLights: function () {
  54409. var sceneEl = this.sceneEl;
  54410. var ambientLight;
  54411. var directionalLight;
  54412. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  54413. return;
  54414. }
  54415. ambientLight = document.createElement('a-entity');
  54416. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  54417. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54418. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  54419. sceneEl.appendChild(ambientLight);
  54420. directionalLight = document.createElement('a-entity');
  54421. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  54422. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  54423. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54424. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  54425. sceneEl.appendChild(directionalLight);
  54426. this.defaultLights = true;
  54427. }
  54428. });
  54429. },{"../constants/":116,"../core/system":135,"../utils/bind":189}],186:[function(_dereq_,module,exports){
  54430. var registerSystem = _dereq_('../core/system').registerSystem;
  54431. var THREE = _dereq_('../lib/three');
  54432. var utils = _dereq_('../utils/');
  54433. var isHLS = _dereq_('../utils/material').isHLS;
  54434. var bind = utils.bind;
  54435. var debug = utils.debug;
  54436. var error = debug('components:texture:error');
  54437. var TextureLoader = new THREE.TextureLoader();
  54438. var warn = debug('components:texture:warn');
  54439. TextureLoader.setCrossOrigin('anonymous');
  54440. /**
  54441. * System for material component.
  54442. * Handle material registration, updates (for fog), and texture caching.
  54443. *
  54444. * @member {object} materials - Registered materials.
  54445. * @member {object} textureCounts - Number of times each texture is used. Tracked
  54446. * separately from textureCache, because the cache (1) is populated in
  54447. * multiple places, and (2) may be cleared at any time.
  54448. * @member {object} textureCache - Texture cache for:
  54449. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  54450. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  54451. */
  54452. module.exports.System = registerSystem('material', {
  54453. init: function () {
  54454. this.materials = {};
  54455. this.textureCounts = {};
  54456. this.textureCache = {};
  54457. this.sceneEl.addEventListener(
  54458. 'materialtextureloaded',
  54459. bind(this.onMaterialTextureLoaded, this)
  54460. );
  54461. },
  54462. clearTextureCache: function () {
  54463. this.textureCache = {};
  54464. },
  54465. /**
  54466. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  54467. *
  54468. * @param {string, or element} src - Texture URL or element.
  54469. * @param {string} data - Relevant texture data used for caching.
  54470. * @param {function} cb - Callback to pass texture to.
  54471. */
  54472. loadTexture: function (src, data, cb) {
  54473. var self = this;
  54474. // Canvas.
  54475. if (src.tagName === 'CANVAS') {
  54476. this.loadCanvas(src, data, cb);
  54477. return;
  54478. }
  54479. // Video element.
  54480. if (src.tagName === 'VIDEO') {
  54481. if (!src.src && !src.srcObject && !src.childElementCount) {
  54482. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  54483. }
  54484. this.loadVideo(src, data, cb);
  54485. return;
  54486. }
  54487. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  54488. function loadImageCb (src) { self.loadImage(src, data, cb); }
  54489. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  54490. },
  54491. /**
  54492. * High-level function for loading image textures (THREE.Texture).
  54493. *
  54494. * @param {Element|string} src - Texture source.
  54495. * @param {object} data - Texture data.
  54496. * @param {function} cb - Callback to pass texture to.
  54497. */
  54498. loadImage: function (src, data, handleImageTextureLoaded) {
  54499. var hash = this.hash(data);
  54500. var textureCache = this.textureCache;
  54501. // Texture already being loaded or already loaded. Wait on promise.
  54502. if (textureCache[hash]) {
  54503. textureCache[hash].then(handleImageTextureLoaded);
  54504. return;
  54505. }
  54506. // Texture not yet being loaded. Start loading it.
  54507. textureCache[hash] = loadImageTexture(src, data);
  54508. textureCache[hash].then(handleImageTextureLoaded);
  54509. },
  54510. /**
  54511. * High-level function for loading canvas textures (THREE.Texture).
  54512. *
  54513. * @param {Element|string} src - Texture source.
  54514. * @param {object} data - Texture data.
  54515. * @param {function} cb - Callback to pass texture to.
  54516. */
  54517. loadCanvas: function (src, data, cb) {
  54518. // Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
  54519. src.readyState = 2;
  54520. src.HAVE_CURRENT_DATA = 2;
  54521. this.loadVideo(src, data, cb);
  54522. },
  54523. /**
  54524. * Load video texture (THREE.VideoTexture).
  54525. * Which is just an image texture that RAFs + needsUpdate.
  54526. * Note that creating a video texture is synchronous unlike loading an image texture.
  54527. * Made asynchronous to be consistent with image textures.
  54528. *
  54529. * @param {Element|string} src - Texture source.
  54530. * @param {object} data - Texture data.
  54531. * @param {function} cb - Callback to pass texture to.
  54532. */
  54533. loadVideo: function (src, data, cb) {
  54534. var hash;
  54535. var texture;
  54536. var textureCache = this.textureCache;
  54537. var videoEl;
  54538. var videoTextureResult;
  54539. function handleVideoTextureLoaded (result) {
  54540. result.texture.needsUpdate = true;
  54541. cb(result.texture, result.videoEl);
  54542. }
  54543. // Video element provided.
  54544. if (typeof src !== 'string') {
  54545. // Check cache before creating texture.
  54546. videoEl = src;
  54547. hash = this.hashVideo(data, videoEl);
  54548. if (textureCache[hash]) {
  54549. textureCache[hash].then(handleVideoTextureLoaded);
  54550. return;
  54551. }
  54552. // If not in cache, fix up the attributes then start to create the texture.
  54553. fixVideoAttributes(videoEl);
  54554. }
  54555. // Only URL provided. Use video element to create texture.
  54556. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  54557. // Generated video element already cached. Use that.
  54558. hash = this.hashVideo(data, videoEl);
  54559. if (textureCache[hash]) {
  54560. textureCache[hash].then(handleVideoTextureLoaded);
  54561. return;
  54562. }
  54563. // Create new video texture.
  54564. texture = new THREE.VideoTexture(videoEl);
  54565. texture.minFilter = THREE.LinearFilter;
  54566. setTextureProperties(texture, data);
  54567. // If iOS and video is HLS, do some hacks.
  54568. if (this.sceneEl.isIOS &&
  54569. isHLS(videoEl.src || videoEl.getAttribute('src'),
  54570. videoEl.type || videoEl.getAttribute('type'))) {
  54571. // Actually BGRA. Tell shader to correct later.
  54572. texture.format = THREE.RGBAFormat;
  54573. texture.needsCorrectionBGRA = true;
  54574. // Apparently needed for HLS. Tell shader to correct later.
  54575. texture.flipY = false;
  54576. texture.needsCorrectionFlipY = true;
  54577. }
  54578. // Cache as promise to be consistent with image texture caching.
  54579. videoTextureResult = {texture: texture, videoEl: videoEl};
  54580. textureCache[hash] = Promise.resolve(videoTextureResult);
  54581. handleVideoTextureLoaded(videoTextureResult);
  54582. },
  54583. /**
  54584. * Create a hash of the material properties for texture cache key.
  54585. */
  54586. hash: function (data) {
  54587. if (data.src.tagName) {
  54588. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  54589. data = utils.extendDeep({}, data);
  54590. data.src = data.src.src;
  54591. }
  54592. return JSON.stringify(data);
  54593. },
  54594. hashVideo: function (data, videoEl) {
  54595. return calculateVideoCacheHash(data, videoEl);
  54596. },
  54597. /**
  54598. * Keep track of material in case an update trigger is needed (e.g., fog).
  54599. *
  54600. * @param {object} material
  54601. */
  54602. registerMaterial: function (material) {
  54603. this.materials[material.uuid] = material;
  54604. },
  54605. /**
  54606. * Stop tracking material, and dispose of any textures not being used by
  54607. * another material component.
  54608. *
  54609. * @param {object} material
  54610. */
  54611. unregisterMaterial: function (material) {
  54612. delete this.materials[material.uuid];
  54613. // If any textures on this material are no longer in use, dispose of them.
  54614. var textureCounts = this.textureCounts;
  54615. Object.keys(material)
  54616. .filter(function (propName) {
  54617. return material[propName] && material[propName].isTexture;
  54618. })
  54619. .forEach(function (mapName) {
  54620. textureCounts[material[mapName].uuid]--;
  54621. if (textureCounts[material[mapName].uuid] <= 0) {
  54622. material[mapName].dispose();
  54623. }
  54624. });
  54625. },
  54626. /**
  54627. * Trigger update to all registered materials.
  54628. */
  54629. updateMaterials: function (material) {
  54630. var materials = this.materials;
  54631. Object.keys(materials).forEach(function (uuid) {
  54632. materials[uuid].needsUpdate = true;
  54633. });
  54634. },
  54635. /**
  54636. * Track textures used by material components, so that they can be safely
  54637. * disposed when no longer in use. Textures must be registered here, and not
  54638. * through registerMaterial(), because textures may not be attached at the
  54639. * time the material is registered.
  54640. *
  54641. * @param {Event} e
  54642. */
  54643. onMaterialTextureLoaded: function (e) {
  54644. if (!this.textureCounts[e.detail.texture.uuid]) {
  54645. this.textureCounts[e.detail.texture.uuid] = 0;
  54646. }
  54647. this.textureCounts[e.detail.texture.uuid]++;
  54648. }
  54649. });
  54650. /**
  54651. * Calculates consistent hash from a video element using its attributes.
  54652. * If the video element has an ID, use that.
  54653. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  54654. *
  54655. * @param data {object} - Texture data such as repeat.
  54656. * @param videoEl {Element} - Video element.
  54657. * @returns {string}
  54658. */
  54659. function calculateVideoCacheHash (data, videoEl) {
  54660. var i;
  54661. var id = videoEl.getAttribute('id');
  54662. var hash;
  54663. var videoAttributes;
  54664. if (id) { return id; }
  54665. // Calculate hash using sorted video attributes.
  54666. hash = '';
  54667. videoAttributes = data || {};
  54668. for (i = 0; i < videoEl.attributes.length; i++) {
  54669. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  54670. }
  54671. Object.keys(videoAttributes).sort().forEach(function (name) {
  54672. hash += name + ':' + videoAttributes[name] + ';';
  54673. });
  54674. return hash;
  54675. }
  54676. /**
  54677. * Load image texture.
  54678. *
  54679. * @private
  54680. * @param {string|object} src - An <img> element or url to an image file.
  54681. * @param {object} data - Data to set texture properties like `repeat`.
  54682. * @returns {Promise} Resolves once texture is loaded.
  54683. */
  54684. function loadImageTexture (src, data) {
  54685. return new Promise(doLoadImageTexture);
  54686. function doLoadImageTexture (resolve, reject) {
  54687. var isEl = typeof src !== 'string';
  54688. function resolveTexture (texture) {
  54689. setTextureProperties(texture, data);
  54690. texture.needsUpdate = true;
  54691. resolve(texture);
  54692. }
  54693. // Create texture from an element.
  54694. if (isEl) {
  54695. resolveTexture(new THREE.Texture(src));
  54696. return;
  54697. }
  54698. // Request and load texture from src string. THREE will create underlying element.
  54699. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  54700. TextureLoader.load(
  54701. src,
  54702. resolveTexture,
  54703. function () { /* no-op */ },
  54704. function (xhr) {
  54705. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  54706. xhr.statusText);
  54707. }
  54708. );
  54709. }
  54710. }
  54711. /**
  54712. * Set texture properties such as repeat and offset.
  54713. *
  54714. * @param {object} data - With keys like `repeat`.
  54715. */
  54716. function setTextureProperties (texture, data) {
  54717. var offset = data.offset || {x: 0, y: 0};
  54718. var repeat = data.repeat || {x: 1, y: 1};
  54719. var npot = data.npot || false;
  54720. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  54721. // and filters must not use mipmaps (i.e. Nearest or Linear).
  54722. if (npot) {
  54723. texture.wrapS = THREE.ClampToEdgeWrapping;
  54724. texture.wrapT = THREE.ClampToEdgeWrapping;
  54725. texture.magFilter = THREE.LinearFilter;
  54726. texture.minFilter = THREE.LinearFilter;
  54727. }
  54728. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  54729. if (repeat.x !== 1 || repeat.y !== 1) {
  54730. texture.wrapS = THREE.RepeatWrapping;
  54731. texture.wrapT = THREE.RepeatWrapping;
  54732. texture.repeat.set(repeat.x, repeat.y);
  54733. }
  54734. // Don't bother setting offset if it is 0/0.
  54735. if (offset.x !== 0 || offset.y !== 0) {
  54736. texture.offset.set(offset.x, offset.y);
  54737. }
  54738. }
  54739. /**
  54740. * Create video element to be used as a texture.
  54741. *
  54742. * @param {string} src - Url to a video file.
  54743. * @param {number} width - Width of the video.
  54744. * @param {number} height - Height of the video.
  54745. * @returns {Element} Video element.
  54746. */
  54747. function createVideoEl (src, width, height) {
  54748. var videoEl = document.createElement('video');
  54749. videoEl.width = width;
  54750. videoEl.height = height;
  54751. // Support inline videos for iOS webviews.
  54752. videoEl.setAttribute('playsinline', '');
  54753. videoEl.setAttribute('webkit-playsinline', '');
  54754. videoEl.autoplay = true;
  54755. videoEl.loop = true;
  54756. videoEl.crossOrigin = 'anonymous';
  54757. videoEl.addEventListener('error', function () {
  54758. warn('`$s` is not a valid video', src);
  54759. }, true);
  54760. videoEl.src = src;
  54761. return videoEl;
  54762. }
  54763. /**
  54764. * Fixes a video element's attributes to prevent developers from accidentally passing the
  54765. * wrong attribute values to commonly misused video attributes.
  54766. *
  54767. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  54768. * as booleans. Existence of those attributes will mean truthy.
  54769. *
  54770. * For example, translates <video loop="false"> to <video>.
  54771. *
  54772. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  54773. * @param {Element} videoEl - Video element.
  54774. * @returns {Element} Video element with the correct properties updated.
  54775. */
  54776. function fixVideoAttributes (videoEl) {
  54777. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  54778. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  54779. if (videoEl.getAttribute('loop') === 'false') {
  54780. videoEl.removeAttribute('loop');
  54781. }
  54782. if (videoEl.getAttribute('preload') === 'false') {
  54783. videoEl.preload = 'none';
  54784. }
  54785. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  54786. // To support inline videos in iOS webviews.
  54787. videoEl.setAttribute('playsinline', '');
  54788. videoEl.setAttribute('webkit-playsinline', '');
  54789. return videoEl;
  54790. }
  54791. },{"../core/system":135,"../lib/three":173,"../utils/":195,"../utils/material":196}],187:[function(_dereq_,module,exports){
  54792. var registerSystem = _dereq_('../core/system').registerSystem;
  54793. var bind = _dereq_('../utils/bind');
  54794. var THREE = _dereq_('../lib/three');
  54795. var SHADOW_MAP_TYPE_MAP = {
  54796. basic: THREE.BasicShadowMap,
  54797. pcf: THREE.PCFShadowMap,
  54798. pcfsoft: THREE.PCFSoftShadowMap
  54799. };
  54800. /**
  54801. * Shadow system.
  54802. *
  54803. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  54804. * options on the WebGLRenderer for configuring shadow appearance.
  54805. */
  54806. module.exports.System = registerSystem('shadow', {
  54807. schema: {
  54808. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']},
  54809. renderReverseSided: {default: true},
  54810. renderSingleSided: {default: true}
  54811. },
  54812. init: function () {
  54813. var sceneEl = this.sceneEl;
  54814. var data = this.data;
  54815. this.shadowMapEnabled = false;
  54816. sceneEl.addEventListener('render-target-loaded', bind(function () {
  54817. // Renderer is not initialized in most tests.
  54818. if (!sceneEl.renderer) { return; }
  54819. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  54820. sceneEl.renderer.shadowMap.renderReverseSided = data.renderReverseSided;
  54821. sceneEl.renderer.shadowMap.renderSingleSided = data.renderSingleSided;
  54822. this.setShadowMapEnabled(this.shadowMapEnabled);
  54823. }, this));
  54824. },
  54825. /**
  54826. * Enables/disables the renderer shadow map.
  54827. * @param {boolean} enabled
  54828. */
  54829. setShadowMapEnabled: function (enabled) {
  54830. var renderer = this.sceneEl.renderer;
  54831. this.shadowMapEnabled = enabled;
  54832. if (renderer) {
  54833. renderer.shadowMap.enabled = enabled;
  54834. }
  54835. }
  54836. });
  54837. },{"../core/system":135,"../lib/three":173,"../utils/bind":189}],188:[function(_dereq_,module,exports){
  54838. var registerSystem = _dereq_('../core/system').registerSystem;
  54839. /**
  54840. * Tracked controls system.
  54841. * Maintain list with available tracked controllers.
  54842. */
  54843. module.exports.System = registerSystem('tracked-controls', {
  54844. init: function () {
  54845. var self = this;
  54846. this.controllers = [];
  54847. this.updateControllerList();
  54848. if (!navigator.getVRDisplays) { return; }
  54849. this.sceneEl.addEventListener('enter-vr', function () {
  54850. navigator.getVRDisplays().then(function (displays) {
  54851. if (displays.length) { self.vrDisplay = displays[0]; }
  54852. });
  54853. });
  54854. },
  54855. tick: function () {
  54856. this.updateControllerList();
  54857. },
  54858. /**
  54859. * Update controller list.
  54860. */
  54861. updateControllerList: function () {
  54862. var controllers = this.controllers;
  54863. var gamepad;
  54864. var gamepads;
  54865. var i;
  54866. var prevCount;
  54867. gamepads = navigator.getGamepads && navigator.getGamepads();
  54868. if (!gamepads) { return; }
  54869. prevCount = controllers.length;
  54870. controllers.length = 0;
  54871. for (i = 0; i < gamepads.length; ++i) {
  54872. gamepad = gamepads[i];
  54873. if (gamepad && gamepad.pose) {
  54874. controllers.push(gamepad);
  54875. }
  54876. }
  54877. if (controllers.length !== prevCount) {
  54878. this.el.emit('controllersupdated', undefined, false);
  54879. }
  54880. }
  54881. });
  54882. },{"../core/system":135}],189:[function(_dereq_,module,exports){
  54883. /**
  54884. * Faster version of Function.prototype.bind
  54885. * @param {Function} fn - Function to wrap.
  54886. * @param {Object} ctx - What to bind as context.
  54887. * @param {...*} arguments - Arguments to pass through.
  54888. */
  54889. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  54890. return (function (prependedArgs) {
  54891. return function bound () {
  54892. // Concat the bound function arguments with those passed to original bind
  54893. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  54894. return fn.apply(ctx, args);
  54895. };
  54896. })(Array.prototype.slice.call(arguments, 2));
  54897. };
  54898. },{}],190:[function(_dereq_,module,exports){
  54899. /* global THREE */
  54900. var debug = _dereq_('./debug');
  54901. var extend = _dereq_('object-assign');
  54902. var warn = debug('utils:coordinates:warn');
  54903. // Coordinate string regex. Handles negative, positive, and decimals.
  54904. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  54905. module.exports.regex = regex;
  54906. /**
  54907. * Parses coordinates from an "x y z" string.
  54908. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  54909. *
  54910. * @param {string} val - An "x y z" string.
  54911. * @param {string} defaults - fallback value.
  54912. * @returns {object} An object with keys [x, y, z].
  54913. */
  54914. function parse (value, defaultVec) {
  54915. var coordinate;
  54916. var vec;
  54917. if (value && value instanceof Object) {
  54918. if (defaultVec) {
  54919. value.x = value.x === undefined ? defaultVec.x : value.x;
  54920. value.y = value.y === undefined ? defaultVec.y : value.y;
  54921. value.z = value.z === undefined ? defaultVec.z : value.z;
  54922. value.w = value.w === undefined ? defaultVec.w : value.w;
  54923. }
  54924. return vecParseFloat(value);
  54925. }
  54926. if (value === null || value === undefined) {
  54927. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  54928. }
  54929. coordinate = value.trim().replace(/\s+/g, ' ').split(' ');
  54930. vec = {};
  54931. vec.x = coordinate[0] || defaultVec && defaultVec.x;
  54932. vec.y = coordinate[1] || defaultVec && defaultVec.y;
  54933. vec.z = coordinate[2] || defaultVec && defaultVec.z;
  54934. vec.w = coordinate[3] || defaultVec && defaultVec.w;
  54935. return vecParseFloat(vec);
  54936. }
  54937. module.exports.parse = parse;
  54938. /**
  54939. * Stringify coordinates from an object with keys [x y z].
  54940. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  54941. *
  54942. * @param {object|string} data - An object with keys [x y z].
  54943. * @returns {string} An "x y z" string.
  54944. */
  54945. function stringify (data) {
  54946. if (typeof data !== 'object') { return data; }
  54947. return [data.x, data.y, data.z, data.w].join(' ').trim();
  54948. }
  54949. module.exports.stringify = stringify;
  54950. /**
  54951. * @returns {bool}
  54952. */
  54953. function isCoordinates (value) {
  54954. return regex.test(value);
  54955. }
  54956. module.exports.isCoordinates = isCoordinates;
  54957. module.exports.isCoordinate = function (value) {
  54958. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  54959. return isCoordinates(value);
  54960. };
  54961. function vecParseFloat (vec) {
  54962. var key;
  54963. for (key in vec) {
  54964. if (vec[key] === undefined) {
  54965. delete vec[key];
  54966. continue;
  54967. }
  54968. if (vec[key].constructor === String) {
  54969. vec[key] = parseFloat(vec[key], 10);
  54970. }
  54971. }
  54972. return vec;
  54973. }
  54974. /**
  54975. * Convert {x, y, z} object to three.js Vector3.
  54976. */
  54977. module.exports.toVector3 = function (vec3) {
  54978. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  54979. };
  54980. },{"./debug":191,"object-assign":26}],191:[function(_dereq_,module,exports){
  54981. (function (process){
  54982. var debugLib = _dereq_('debug');
  54983. var extend = _dereq_('object-assign');
  54984. var settings = {
  54985. colors: {
  54986. debug: 'gray',
  54987. error: 'red',
  54988. info: 'gray',
  54989. warn: 'orange'
  54990. }
  54991. };
  54992. /**
  54993. * Monkeypatches `debug` so we can colorize error/warning messages.
  54994. *
  54995. * (See issue: https://github.com/visionmedia/debug/issues/137)
  54996. */
  54997. var debug = function (namespace) {
  54998. var d = debugLib(namespace);
  54999. d.color = getDebugNamespaceColor(namespace);
  55000. return d;
  55001. };
  55002. extend(debug, debugLib);
  55003. /**
  55004. * Returns the type of the namespace (e.g., `error`, `warn`).
  55005. *
  55006. * @param {String} namespace
  55007. * The debug logger's namespace (e.g., `components:geometry:warn`).
  55008. * @returns {String} The type of the namespace (e.g., `warn`).
  55009. * @api private
  55010. */
  55011. function getDebugNamespaceType (namespace) {
  55012. var chunks = namespace.split(':');
  55013. return chunks[chunks.length - 1]; // Return the last one
  55014. }
  55015. /**
  55016. * Returns the color of the namespace (e.g., `orange`).
  55017. *
  55018. * @param {String} namespace
  55019. * The debug logger's namespace (e.g., `components:geometry:warn`).
  55020. * @returns {String} The color of the namespace (e.g., `orange`).
  55021. * @api private
  55022. */
  55023. function getDebugNamespaceColor (namespace) {
  55024. var type = getDebugNamespaceType(namespace);
  55025. var color = settings.colors && settings.colors[type];
  55026. return color || null;
  55027. }
  55028. /**
  55029. * Returns `localStorage` if possible.
  55030. *
  55031. * This is necessary because Safari throws when a user disables
  55032. * cookies or `localStorage` and you attempt to access it.
  55033. *
  55034. * @returns {localStorage}
  55035. * @api private
  55036. */
  55037. function storage () {
  55038. try {
  55039. return window.localStorage;
  55040. } catch (e) {
  55041. }
  55042. }
  55043. /**
  55044. * To enable console logging, type this in the Console of your Dev Tools:
  55045. *
  55046. * localStorage.logs = 1
  55047. *
  55048. * To disable console logging:
  55049. *
  55050. * localStorage.logs = 0
  55051. *
  55052. */
  55053. var ls = storage();
  55054. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  55055. debug.enable('*');
  55056. } else {
  55057. debug.enable('*:error,*:info,*:warn');
  55058. }
  55059. if (process.browser) { window.logs = debug; }
  55060. module.exports = debug;
  55061. }).call(this,_dereq_('_process'))
  55062. },{"_process":33,"debug":8,"object-assign":26}],192:[function(_dereq_,module,exports){
  55063. (function (process){
  55064. var THREE = _dereq_('../lib/three');
  55065. var dolly = new THREE.Object3D();
  55066. var controls = new THREE.VRControls(dolly);
  55067. /**
  55068. * Determine if a headset is connected by checking if the orientation is available.
  55069. */
  55070. function checkHeadsetConnected () {
  55071. var orientation;
  55072. var vrDisplay = controls.getVRDisplay();
  55073. // If `isConnected` is available, just use that.
  55074. if (vrDisplay && 'isConnected' in vrDisplay) { return vrDisplay.isConnected; }
  55075. controls.update();
  55076. orientation = dolly.quaternion;
  55077. if (orientation._x !== 0 || orientation._y !== 0 || orientation._z !== 0) {
  55078. return true;
  55079. }
  55080. return false;
  55081. }
  55082. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  55083. /**
  55084. * Check for positional tracking.
  55085. */
  55086. function checkHasPositionalTracking () {
  55087. var vrDisplay = controls.getVRDisplay();
  55088. if (isMobile() || isGearVR()) { return false; }
  55089. return vrDisplay && vrDisplay.capabilities.hasPosition;
  55090. }
  55091. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  55092. /**
  55093. * Checks if browser is mobile.
  55094. * @return {Boolean} True if mobile browser detected.
  55095. */
  55096. var isMobile = (function () {
  55097. var _isMobile = false;
  55098. (function (a) {
  55099. // eslint-disable-next-line no-useless-escape
  55100. 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))) {
  55101. _isMobile = true;
  55102. }
  55103. if (isIOS() || isTablet() || isR7()) {
  55104. _isMobile = true;
  55105. }
  55106. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  55107. return function () { return _isMobile; };
  55108. })();
  55109. module.exports.isMobile = isMobile;
  55110. /**
  55111. * Detect tablet devices.
  55112. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  55113. */
  55114. function isTablet (mockUserAgent) {
  55115. var userAgent = mockUserAgent || window.navigator.userAgent;
  55116. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  55117. }
  55118. module.exports.isTablet = isTablet;
  55119. function isIOS () {
  55120. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  55121. }
  55122. module.exports.isIOS = isIOS;
  55123. function isGearVR () {
  55124. return /SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  55125. }
  55126. module.exports.isGearVR = isGearVR;
  55127. function isR7 () {
  55128. return /R7 Build/.test(window.navigator.userAgent);
  55129. }
  55130. module.exports.isR7 = isR7;
  55131. /**
  55132. * Checks mobile device orientation.
  55133. * @return {Boolean} True if landscape orientation.
  55134. */
  55135. module.exports.isLandscape = function () {
  55136. var orientation = window.orientation;
  55137. if (isR7()) { orientation += 90; }
  55138. return orientation === 90 || orientation === -90;
  55139. };
  55140. /**
  55141. * Check if device is iOS and older than version 10.
  55142. */
  55143. module.exports.isIOSOlderThan10 = function (userAgent) {
  55144. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  55145. };
  55146. /**
  55147. * Check if running in a browser or spoofed browser (bundler).
  55148. * We need to check a node api that isn't mocked on either side.
  55149. * `require` and `module.exports` are mocked in browser by bundlers.
  55150. * `window` is mocked in node.
  55151. * `process` is also mocked by browserify, but has custom properties.
  55152. */
  55153. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  55154. /**
  55155. * Check if running in node on the server.
  55156. */
  55157. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  55158. }).call(this,_dereq_('_process'))
  55159. },{"../lib/three":173,"_process":33}],193:[function(_dereq_,module,exports){
  55160. /**
  55161. * Split a delimited component property string (e.g., `material.color`) to an object
  55162. * containing `component` name and `property` name. If there is no delimiter, just return the
  55163. * string back.
  55164. */
  55165. module.exports.getComponentPropertyPath = function (str, delimiter) {
  55166. delimiter = delimiter || '.';
  55167. if (str.indexOf(delimiter) === -1) { return str; }
  55168. return str.split(delimiter);
  55169. };
  55170. /**
  55171. * Get component property using encoded component name + component property name with a
  55172. * delimiter.
  55173. */
  55174. module.exports.getComponentProperty = function (el, name, delimiter) {
  55175. var splitName;
  55176. delimiter = delimiter || '.';
  55177. if (name.indexOf(delimiter) !== -1) {
  55178. splitName = name.split(delimiter);
  55179. return el.getAttribute(splitName[0])[splitName[1]];
  55180. }
  55181. return el.getAttribute(name);
  55182. };
  55183. /**
  55184. * Set component property using encoded component name + component property name with a
  55185. * delimiter.
  55186. */
  55187. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  55188. var data = {};
  55189. var splitName;
  55190. delimiter = delimiter || '.';
  55191. if (name.indexOf(delimiter) !== -1) {
  55192. splitName = name.split(delimiter);
  55193. data[splitName[1]] = value;
  55194. el.setAttribute(splitName[0], data);
  55195. return;
  55196. }
  55197. el.setAttribute(name, value);
  55198. };
  55199. },{}],194:[function(_dereq_,module,exports){
  55200. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  55201. var width = canvasEl.style.width;
  55202. var height = canvasEl.style.height;
  55203. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  55204. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  55205. // By changing the size 1 pixel and restoring the previous value
  55206. // we trigger a size recalculation cycle.
  55207. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  55208. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  55209. setTimeout(function () {
  55210. canvasEl.style.width = width;
  55211. canvasEl.style.height = height;
  55212. }, 200);
  55213. };
  55214. },{}],195:[function(_dereq_,module,exports){
  55215. /* global CustomEvent, location */
  55216. /* Centralized place to reference utilities since utils is exposed to the user. */
  55217. var debug = _dereq_('./debug');
  55218. var deepAssign = _dereq_('deep-assign');
  55219. var device = _dereq_('./device');
  55220. var objectAssign = _dereq_('object-assign');
  55221. var objectPool = _dereq_('./object-pool');
  55222. var warn = debug('utils:warn');
  55223. module.exports.bind = _dereq_('./bind');
  55224. module.exports.coordinates = _dereq_('./coordinates');
  55225. module.exports.debug = debug;
  55226. module.exports.device = device;
  55227. module.exports.entity = _dereq_('./entity');
  55228. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  55229. module.exports.material = _dereq_('./material');
  55230. module.exports.objectPool = objectPool;
  55231. module.exports.styleParser = _dereq_('./styleParser');
  55232. module.exports.trackedControls = _dereq_('./tracked-controls');
  55233. module.exports.checkHeadsetConnected = function () {
  55234. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  55235. return device.checkHeadsetConnected(arguments);
  55236. };
  55237. module.exports.isGearVR = function () {
  55238. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  55239. return device.isGearVR(arguments);
  55240. };
  55241. module.exports.isIOS = function () {
  55242. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  55243. return device.isIOS(arguments);
  55244. };
  55245. module.exports.isMobile = function () {
  55246. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  55247. return device.isMobile(arguments);
  55248. };
  55249. /**
  55250. * Returns throttle function that gets called at most once every interval.
  55251. *
  55252. * @param {function} functionToThrottle
  55253. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55254. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55255. * @returns {function} Throttled function.
  55256. */
  55257. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  55258. var lastTime;
  55259. if (optionalContext) {
  55260. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55261. }
  55262. return function () {
  55263. var time = Date.now();
  55264. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  55265. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55266. lastTime = time;
  55267. functionToThrottle.apply(null, arguments);
  55268. }
  55269. };
  55270. };
  55271. /**
  55272. * Returns throttle function that gets called at most once every interval.
  55273. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  55274. *
  55275. * @param {function} functionToThrottle
  55276. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55277. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55278. * @returns {function} Throttled function.
  55279. */
  55280. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  55281. var lastTime;
  55282. if (optionalContext) {
  55283. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55284. }
  55285. return function (time, delta) {
  55286. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  55287. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55288. lastTime = time;
  55289. functionToThrottle(time, sinceLastTime);
  55290. }
  55291. };
  55292. };
  55293. /**
  55294. * Returns debounce function that gets called only once after a set of repeated calls.
  55295. *
  55296. * @param {function} functionToDebounce
  55297. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  55298. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  55299. * @returns {function} Debounced function.
  55300. */
  55301. module.exports.debounce = function (func, wait, immediate) {
  55302. var timeout;
  55303. return function () {
  55304. var context = this;
  55305. var args = arguments;
  55306. var later = function () {
  55307. timeout = null;
  55308. if (!immediate) func.apply(context, args);
  55309. };
  55310. var callNow = immediate && !timeout;
  55311. clearTimeout(timeout);
  55312. timeout = setTimeout(later, wait);
  55313. if (callNow) func.apply(context, args);
  55314. };
  55315. };
  55316. /**
  55317. * Fires a custom DOM event.
  55318. *
  55319. * @param {Element} el Element on which to fire the event.
  55320. * @param {String} name Name of the event.
  55321. * @param {Object=} [data={bubbles: true, {detail: <el>}}]
  55322. * Data to pass as `customEventInit` to the event.
  55323. */
  55324. module.exports.fireEvent = function (el, name, data) {
  55325. data = data || {};
  55326. data.detail = data.detail || {};
  55327. data.detail.target = data.detail.target || el;
  55328. var evt = new CustomEvent(name, data);
  55329. el.dispatchEvent(evt);
  55330. };
  55331. /**
  55332. * Mix the properties of source object(s) into a destination object.
  55333. *
  55334. * @param {object} dest - The object to which properties will be copied.
  55335. * @param {...object} source - The object(s) from which properties will be copied.
  55336. */
  55337. module.exports.extend = objectAssign;
  55338. module.exports.extendDeep = deepAssign;
  55339. module.exports.clone = function (obj) {
  55340. return JSON.parse(JSON.stringify(obj));
  55341. };
  55342. /**
  55343. * Checks if two values are equal.
  55344. * Includes objects and arrays and nested objects and arrays.
  55345. * Try to keep this function performant as it will be called often to see if a component
  55346. * should be updated.
  55347. *
  55348. * @param {object} a - First object.
  55349. * @param {object} b - Second object.
  55350. * @returns {boolean} Whether two objects are deeply equal.
  55351. */
  55352. var deepEqual = (function () {
  55353. var arrayPool = objectPool.createPool(function () { return []; });
  55354. return function (a, b) {
  55355. var key;
  55356. var keysA;
  55357. var keysB;
  55358. var i;
  55359. var valA;
  55360. var valB;
  55361. // If not objects or arrays, compare as values.
  55362. if (a === undefined || b === undefined || a === null || b === null ||
  55363. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  55364. (a.constructor === Array && b.constructor === Array))) {
  55365. return a === b;
  55366. }
  55367. // Different number of keys, not equal.
  55368. keysA = arrayPool.use();
  55369. keysB = arrayPool.use();
  55370. keysA.length = 0;
  55371. keysB.length = 0;
  55372. for (key in a) { keysA.push(key); }
  55373. for (key in b) { keysB.push(key); }
  55374. if (keysA.length !== keysB.length) {
  55375. arrayPool.recycle(keysA);
  55376. arrayPool.recycle(keysB);
  55377. return false;
  55378. }
  55379. // Return `false` at the first sign of inequality.
  55380. for (i = 0; i < keysA.length; ++i) {
  55381. valA = a[keysA[i]];
  55382. valB = b[keysA[i]];
  55383. // Check nested array and object.
  55384. if ((typeof valA === 'object' || typeof valB === 'object') ||
  55385. (Array.isArray(valA) && Array.isArray(valB))) {
  55386. if (valA === valB) { continue; }
  55387. if (!deepEqual(valA, valB)) {
  55388. arrayPool.recycle(keysA);
  55389. arrayPool.recycle(keysB);
  55390. return false;
  55391. }
  55392. } else if (valA !== valB) {
  55393. arrayPool.recycle(keysA);
  55394. arrayPool.recycle(keysB);
  55395. return false;
  55396. }
  55397. }
  55398. arrayPool.recycle(keysA);
  55399. arrayPool.recycle(keysB);
  55400. return true;
  55401. };
  55402. })();
  55403. module.exports.deepEqual = deepEqual;
  55404. /**
  55405. * Computes the difference between two objects.
  55406. *
  55407. * @param {object} a - First object to compare (e.g., oldData).
  55408. * @param {object} b - Second object to compare (e.g., newData).
  55409. * @returns {object}
  55410. * Difference object where set of keys note which values were not equal, and values are
  55411. * `b`'s values.
  55412. */
  55413. module.exports.diff = function (a, b) {
  55414. var diff = {};
  55415. var keys = Object.keys(a);
  55416. if (!b) { return diff; }
  55417. Object.keys(b).forEach(function collectKeys (bKey) {
  55418. if (keys.indexOf(bKey) === -1) {
  55419. keys.push(bKey);
  55420. }
  55421. });
  55422. keys.forEach(function doDiff (key) {
  55423. var aVal = a[key];
  55424. var bVal = b[key];
  55425. var isComparingObjects = aVal && bVal &&
  55426. aVal.constructor === Object && bVal.constructor === Object;
  55427. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  55428. (!isComparingObjects && aVal !== bVal)) {
  55429. diff[key] = bVal;
  55430. }
  55431. });
  55432. return diff;
  55433. };
  55434. /**
  55435. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  55436. * @param {Event} event Event object.
  55437. * @returns {Boolean} Whether the key event should be captured.
  55438. */
  55439. module.exports.shouldCaptureKeyEvent = function (event) {
  55440. if (event.metaKey) { return false; }
  55441. return document.activeElement === document.body;
  55442. };
  55443. /**
  55444. * Splits a string into an array based on a delimiter.
  55445. *
  55446. * @param {string=} [str=''] Source string
  55447. * @param {string=} [delimiter=' '] Delimiter to use
  55448. * @returns {array} Array of delimited strings
  55449. */
  55450. module.exports.splitString = function (str, delimiter) {
  55451. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  55452. // First collapse the whitespace (or whatever the delimiter is).
  55453. var regex = new RegExp(delimiter, 'g');
  55454. str = (str || '').replace(regex, delimiter);
  55455. // Then split.
  55456. return str.split(delimiter);
  55457. };
  55458. /**
  55459. * Extracts data from the element given an object that contains expected keys.
  55460. *
  55461. * @param {Element} Source element.
  55462. * @param {Object} [defaults={}] Object of default key-value pairs.
  55463. * @returns {Object}
  55464. */
  55465. module.exports.getElData = function (el, defaults) {
  55466. defaults = defaults || {};
  55467. var data = {};
  55468. Object.keys(defaults).forEach(copyAttribute);
  55469. function copyAttribute (key) {
  55470. if (el.hasAttribute(key)) {
  55471. data[key] = el.getAttribute(key);
  55472. }
  55473. }
  55474. return data;
  55475. };
  55476. /**
  55477. * Retrieves querystring value.
  55478. * @param {String} name Name of querystring key.
  55479. * @return {String} Value
  55480. */
  55481. module.exports.getUrlParameter = function (name) {
  55482. // eslint-disable-next-line no-useless-escape
  55483. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  55484. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  55485. var results = regex.exec(location.search);
  55486. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  55487. };
  55488. /**
  55489. * Detects whether context is within iframe.
  55490. */
  55491. module.exports.isIframed = function () {
  55492. return window.top !== window.self;
  55493. };
  55494. /**
  55495. * Finds all elements under the element that have the isScene
  55496. * property set to true
  55497. */
  55498. module.exports.findAllScenes = function (el) {
  55499. var matchingElements = [];
  55500. var allElements = el.getElementsByTagName('*');
  55501. for (var i = 0, n = allElements.length; i < n; i++) {
  55502. if (allElements[i].isScene) {
  55503. // Element exists with isScene set.
  55504. matchingElements.push(allElements[i]);
  55505. }
  55506. }
  55507. return matchingElements;
  55508. };
  55509. // Must be at bottom to avoid circular dependency.
  55510. module.exports.srcLoader = _dereq_('./src-loader');
  55511. },{"./bind":189,"./coordinates":190,"./debug":191,"./device":192,"./entity":193,"./forceCanvasResizeSafariMobile":194,"./material":196,"./object-pool":197,"./src-loader":198,"./styleParser":199,"./tracked-controls":200,"deep-assign":10,"object-assign":26}],196:[function(_dereq_,module,exports){
  55512. var THREE = _dereq_('../lib/three');
  55513. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  55514. /**
  55515. * Update `material` texture property (usually but not always `map`)
  55516. * from `data` property (usually but not always `src`)
  55517. *
  55518. * @param {object} shader - A-Frame shader instance.
  55519. * @param {object} data
  55520. */
  55521. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  55522. var el = shader.el;
  55523. var material = shader.material;
  55524. var src = data[dataName];
  55525. // Because a single material / shader may have multiple textures,
  55526. // we need to remember the source value for this data property
  55527. // to avoid redundant operations which can be expensive otherwise
  55528. // (e.g. video texture loads).
  55529. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  55530. if (!src) {
  55531. // Forget the prior material src.
  55532. delete shader.materialSrcs[materialName];
  55533. // Remove the texture.
  55534. setMap(null);
  55535. return;
  55536. }
  55537. // Don't process if material src hasn't changed.
  55538. if (src === shader.materialSrcs[materialName]) { return; }
  55539. // Remember the new src for this texture (there may be multiple).
  55540. shader.materialSrcs[materialName] = src;
  55541. // If the new material src is already a texture, just use it.
  55542. if (src instanceof THREE.Texture) { setMap(src); } else {
  55543. // Load texture for the new material src.
  55544. // (And check if we should still use it once available in callback.)
  55545. el.sceneEl.systems.material.loadTexture(src,
  55546. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  55547. checkSetMap);
  55548. }
  55549. function checkSetMap (texture) {
  55550. // If the source has been changed, don't use loaded texture.
  55551. if (shader.materialSrcs[materialName] !== src) { return; }
  55552. setMap(texture);
  55553. }
  55554. function setMap (texture) {
  55555. material[materialName] = texture;
  55556. material.needsUpdate = true;
  55557. handleTextureEvents(el, texture);
  55558. }
  55559. };
  55560. /**
  55561. * Update `material.map` given `data.src`. For standard and flat shaders.
  55562. *
  55563. * @param {object} shader - A-Frame shader instance.
  55564. * @param {object} data
  55565. */
  55566. module.exports.updateMap = function (shader, data) {
  55567. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  55568. };
  55569. /**
  55570. * Updates the material's maps which give the illusion of extra geometry.
  55571. *
  55572. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  55573. * @param {object} shader - A-Frame shader instance
  55574. * @param {object} data
  55575. */
  55576. module.exports.updateDistortionMap = function (longType, shader, data) {
  55577. var shortType = longType;
  55578. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  55579. var el = shader.el;
  55580. var material = shader.material;
  55581. var src = data[longType + 'Map'];
  55582. var info = {};
  55583. info.src = src;
  55584. // Pass through the repeat and offset to be handled by the material loader.
  55585. info.offset = data[longType + 'TextureOffset'];
  55586. info.repeat = data[longType + 'TextureRepeat'];
  55587. info.wrap = data[longType + 'TextureWrap'];
  55588. if (src) {
  55589. if (src === shader[longType + 'TextureSrc']) { return; }
  55590. // Texture added or changed.
  55591. shader[longType + 'TextureSrc'] = src;
  55592. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  55593. return;
  55594. }
  55595. // Texture removed.
  55596. if (!material.map) { return; }
  55597. setMap(null);
  55598. function setMap (texture) {
  55599. material[shortType + 'Map'] = texture;
  55600. material.needsUpdate = true;
  55601. handleTextureEvents(el, texture);
  55602. }
  55603. };
  55604. /**
  55605. * Emit event on entities on texture-related events.
  55606. *
  55607. * @param {Element} el - Entity.
  55608. * @param {object} texture - three.js Texture.
  55609. */
  55610. function handleTextureEvents (el, texture) {
  55611. if (!texture) { return; }
  55612. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  55613. // Video events.
  55614. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  55615. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  55616. // Check to see if we need to use iOS 10 HLS shader.
  55617. // Only override the shader if it is stock shader that we know doesn't correct.
  55618. if (!el.components || !el.components.material) { return; }
  55619. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  55620. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  55621. el.setAttribute('material', 'shader', 'ios10hls');
  55622. }
  55623. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  55624. });
  55625. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  55626. // Works for non-looping videos only.
  55627. el.emit('materialvideoended', {src: texture.image, texture: texture});
  55628. });
  55629. }
  55630. module.exports.handleTextureEvents = handleTextureEvents;
  55631. /**
  55632. * Given video element src and type, guess whether stream is HLS.
  55633. *
  55634. * @param {string} src - src from video element (generally URL to content).
  55635. * @param {string} type - type from video element (generally MIME type if present).
  55636. */
  55637. module.exports.isHLS = function (src, type) {
  55638. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  55639. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  55640. return false;
  55641. };
  55642. },{"../lib/three":173}],197:[function(_dereq_,module,exports){
  55643. /*
  55644. Adapted deePool by Kyle Simpson.
  55645. MIT License: http://getify.mit-license.org
  55646. */
  55647. var EMPTY_SLOT = Object.freeze(Object.create(null));
  55648. // Default object factory.
  55649. function defaultObjectFactory () { return {}; }
  55650. /**
  55651. * Create a new pool.
  55652. */
  55653. module.exports.createPool = function createPool (objectFactory) {
  55654. var objPool = [];
  55655. var nextFreeSlot = null; // Pool location to look for a free object to use.
  55656. objectFactory = objectFactory || defaultObjectFactory;
  55657. function use () {
  55658. var objToUse;
  55659. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  55660. grow(objPool.length || 5);
  55661. }
  55662. objToUse = objPool[nextFreeSlot];
  55663. objPool[nextFreeSlot++] = EMPTY_SLOT;
  55664. clearObject(objToUse);
  55665. return objToUse;
  55666. }
  55667. function recycle (obj) {
  55668. if (!(obj instanceof Object)) { return; }
  55669. if (nextFreeSlot === null || nextFreeSlot === -1) {
  55670. objPool[objPool.length] = obj;
  55671. return;
  55672. }
  55673. objPool[--nextFreeSlot] = obj;
  55674. }
  55675. function grow (count) {
  55676. var currentLength;
  55677. var i;
  55678. count = count === undefined ? objPool.length : count;
  55679. if (count > 0 && nextFreeSlot == null) {
  55680. nextFreeSlot = 0;
  55681. }
  55682. if (count > 0) {
  55683. currentLength = objPool.length;
  55684. objPool.length += Number(count);
  55685. for (i = currentLength; i < objPool.length; i++) {
  55686. // Add new obj to pool.
  55687. objPool[i] = objectFactory();
  55688. }
  55689. }
  55690. return objPool.length;
  55691. }
  55692. function size () {
  55693. return objPool.length;
  55694. }
  55695. return {
  55696. grow: grow,
  55697. pool: objPool,
  55698. recycle: recycle,
  55699. size: size,
  55700. use: use
  55701. };
  55702. };
  55703. function clearObject (obj) {
  55704. var key;
  55705. if (!(obj.constructor === Object)) { return; }
  55706. for (key in obj) { obj[key] = undefined; }
  55707. }
  55708. module.exports.clearObject = clearObject;
  55709. },{}],198:[function(_dereq_,module,exports){
  55710. /* global Image, XMLHttpRequest */
  55711. var debug = _dereq_('./debug');
  55712. var warn = debug('utils:src-loader:warn');
  55713. /**
  55714. * Validate a texture, either as a selector or as a URL.
  55715. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  55716. * callback.
  55717. *
  55718. * `src` will be passed into the callback
  55719. *
  55720. * @params {string|Element} src - URL or media element.
  55721. * @params {function} isImageCb - callback if texture is an image.
  55722. * @params {function} isVideoCb - callback if texture is a video.
  55723. */
  55724. function validateSrc (src, isImageCb, isVideoCb) {
  55725. checkIsImage(src, function isAnImageUrl (isImage) {
  55726. if (isImage) {
  55727. isImageCb(src);
  55728. return;
  55729. }
  55730. isVideoCb(src);
  55731. });
  55732. }
  55733. /**
  55734. * Validates six images as a cubemap, either as selector or comma-separated
  55735. * URLs.
  55736. *
  55737. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55738. must be wrapped by `url()`.
  55739. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55740. must be wrapped by `url()`.
  55741. */
  55742. function validateCubemapSrc (src, cb) {
  55743. var aCubemap;
  55744. var cubemapSrcRegex = '';
  55745. var i;
  55746. var urls;
  55747. var validatedUrls = [];
  55748. for (i = 0; i < 5; i++) {
  55749. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  55750. }
  55751. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  55752. urls = src.match(new RegExp(cubemapSrcRegex));
  55753. // `src` is a comma-separated list of URLs.
  55754. // In this case, re-use validateSrc for each side of the cube.
  55755. function isImageCb (url) {
  55756. validatedUrls.push(url);
  55757. if (validatedUrls.length === 6) {
  55758. cb(validatedUrls);
  55759. }
  55760. }
  55761. if (urls) {
  55762. for (i = 1; i < 7; i++) {
  55763. validateSrc(parseUrl(urls[i]), isImageCb);
  55764. }
  55765. return;
  55766. }
  55767. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  55768. aCubemap = validateAndGetQuerySelector(src);
  55769. if (!aCubemap) { return; }
  55770. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  55771. return cb(aCubemap.srcs);
  55772. }
  55773. // Else if aCubeMap is not a <a-cubemap>.
  55774. warn('Selector "%s" does not point to <a-cubemap>', src);
  55775. }
  55776. /**
  55777. * Parses src from `url(src)`.
  55778. * @param {string} src - String to parse.
  55779. * @return {string} The parsed src, if parseable.
  55780. */
  55781. function parseUrl (src) {
  55782. var parsedSrc = src.match(/\url\((.+)\)/);
  55783. if (!parsedSrc) { return; }
  55784. return parsedSrc[1];
  55785. }
  55786. /**
  55787. * Call back whether `src` is an image.
  55788. *
  55789. * @param {string|Element} src - URL or element that will be tested.
  55790. * @param {function} onResult - Callback with whether `src` is an image.
  55791. */
  55792. function checkIsImage (src, onResult) {
  55793. var request;
  55794. if (src.tagName) {
  55795. onResult(src.tagName === 'IMG');
  55796. return;
  55797. }
  55798. request = new XMLHttpRequest();
  55799. // Try to send HEAD request to check if image first.
  55800. request.open('HEAD', src);
  55801. request.addEventListener('load', function (event) {
  55802. var contentType;
  55803. if (request.status >= 200 && request.status < 300) {
  55804. contentType = request.getResponseHeader('Content-Type');
  55805. if (contentType == null) {
  55806. checkIsImageFallback(src, onResult);
  55807. } else {
  55808. if (contentType.startsWith('image')) {
  55809. onResult(true);
  55810. } else {
  55811. onResult(false);
  55812. }
  55813. }
  55814. } else {
  55815. checkIsImageFallback(src, onResult);
  55816. }
  55817. request.abort();
  55818. });
  55819. request.send();
  55820. }
  55821. function checkIsImageFallback (src, onResult) {
  55822. var tester = new Image();
  55823. tester.addEventListener('load', onLoad);
  55824. function onLoad () { onResult(true); }
  55825. tester.addEventListener('error', onError);
  55826. function onError () { onResult(false); }
  55827. tester.src = src;
  55828. }
  55829. /**
  55830. * Query and validate a query selector,
  55831. *
  55832. * @param {string} selector - DOM selector.
  55833. * @return {object|null|undefined} Selected DOM element if exists.
  55834. null if query yields no results.
  55835. undefined if `selector` is not a valid selector.
  55836. */
  55837. function validateAndGetQuerySelector (selector) {
  55838. try {
  55839. var el = document.querySelector(selector);
  55840. if (!el) {
  55841. warn('No element was found matching the selector: "%s"', selector);
  55842. }
  55843. return el;
  55844. } catch (e) { // Capture exception if it's not a valid selector.
  55845. warn('"%s" is not a valid selector', selector);
  55846. return undefined;
  55847. }
  55848. }
  55849. module.exports = {
  55850. parseUrl: parseUrl,
  55851. validateSrc: validateSrc,
  55852. validateCubemapSrc: validateCubemapSrc
  55853. };
  55854. },{"./debug":191}],199:[function(_dereq_,module,exports){
  55855. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  55856. var styleParser = _dereq_('style-attr');
  55857. /**
  55858. * Deserializes style-like string into an object of properties.
  55859. *
  55860. * @param {string} value - HTML attribute value.
  55861. * @returns {object} Property data.
  55862. */
  55863. module.exports.parse = function (value) {
  55864. var parsedData;
  55865. if (typeof value !== 'string') { return value; }
  55866. parsedData = styleParser.parse(value);
  55867. // The style parser returns an object { "" : "test"} when fed a string
  55868. if (parsedData['']) { return value; }
  55869. return transformKeysToCamelCase(parsedData);
  55870. };
  55871. /**
  55872. * Serialize an object of properties into a style-like string.
  55873. *
  55874. * @param {object} data - Property data.
  55875. * @returns {string}
  55876. */
  55877. module.exports.stringify = function (data) {
  55878. if (typeof data === 'string') { return data; }
  55879. return styleParser.stringify(data);
  55880. };
  55881. /**
  55882. * Converts string from hyphen to camelCase.
  55883. *
  55884. * @param {string} str - String to camelCase.
  55885. * @return {string} CamelCased string.
  55886. */
  55887. function toCamelCase (str) {
  55888. return str.replace(/-([a-z])/g, camelCase);
  55889. function camelCase (g) { return g[1].toUpperCase(); }
  55890. }
  55891. module.exports.toCamelCase = toCamelCase;
  55892. /**
  55893. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  55894. * `maxValue`).
  55895. *
  55896. * @param {object} obj - The object to camelCase keys.
  55897. * @return {object} The object with keys camelCased.
  55898. */
  55899. function transformKeysToCamelCase (obj) {
  55900. var keys = Object.keys(obj);
  55901. var camelCaseObj = {};
  55902. keys.forEach(function (key) {
  55903. var camelCaseKey = toCamelCase(key);
  55904. camelCaseObj[camelCaseKey] = obj[key];
  55905. });
  55906. return camelCaseObj;
  55907. }
  55908. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  55909. },{"style-attr":36}],200:[function(_dereq_,module,exports){
  55910. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  55911. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  55912. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  55913. /**
  55914. * Called on controller component `.play` handlers.
  55915. * Check if controller matches parameters and inject tracked-controls component.
  55916. * Handle event listeners.
  55917. * Generate controllerconnected or controllerdisconnected events.
  55918. *
  55919. * @param {object} component - Tracked controls component.
  55920. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55921. * @param {object} queryObject - Map of values to match.
  55922. */
  55923. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  55924. var el = component.el;
  55925. var isPresent = isControllerPresent(component, idPrefix, queryObject);
  55926. // If component was previously paused and now playing, re-add event listeners.
  55927. // Handle the event listeners here since this helper method is control of calling
  55928. // `.addEventListeners` and `.removeEventListeners`.
  55929. if (component.controllerPresent && !component.controllerEventsActive) {
  55930. component.addEventListeners();
  55931. }
  55932. // Nothing changed, no need to do anything.
  55933. if (isPresent === component.controllerPresent) { return isPresent; }
  55934. component.controllerPresent = isPresent;
  55935. // Update controller presence.
  55936. if (isPresent) {
  55937. component.injectTrackedControls();
  55938. component.addEventListeners();
  55939. el.emit('controllerconnected', {name: component.name, component: component});
  55940. } else {
  55941. component.removeEventListeners();
  55942. el.emit('controllerdisconnected', {name: component.name, component: component});
  55943. }
  55944. };
  55945. /**
  55946. * Enumerate controller (that have pose) and check if they match parameters.
  55947. *
  55948. * @param {object} component - Tracked controls component.
  55949. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55950. * @param {object} queryObject - Map of values to match.
  55951. */
  55952. function isControllerPresent (component, idPrefix, queryObject) {
  55953. var gamepads;
  55954. var sceneEl = component.el.sceneEl;
  55955. var trackedControlsSystem;
  55956. var filterControllerIndex = queryObject.index || 0;
  55957. if (!idPrefix) { return false; }
  55958. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  55959. if (!trackedControlsSystem) { return false; }
  55960. gamepads = trackedControlsSystem.controllers;
  55961. if (!gamepads.length) { return false; }
  55962. return !!findMatchingController(gamepads, null, idPrefix, queryObject.hand, filterControllerIndex);
  55963. }
  55964. module.exports.isControllerPresent = isControllerPresent;
  55965. /**
  55966. * Walk through the given controllers to find any where the device ID equals filterIdExact, or startWith filterIdPrefix.
  55967. * A controller where this considered true is considered a 'match'.
  55968. *
  55969. * For each matching controller:
  55970. * If filterHand is set, and the controller:
  55971. * is handed, we further verify that controller.hand equals filterHand.
  55972. * is unhanded (controller.hand is ''), we skip until we have found a number of matching controllers that equals filterControllerIndex
  55973. * If filterHand is not set, we skip until we have found the nth matching controller, where n equals filterControllerIndex
  55974. *
  55975. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND one or both of: [filterHand, filterControllerIndex]
  55976. *
  55977. * @param {object} controllers - Array of gamepads to search
  55978. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  55979. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  55980. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  55981. * @param {object} filterControllerIndex - Find the nth matching controller, where n equals filterControllerIndex. defaults to 0.
  55982. */
  55983. function findMatchingController (controllers, filterIdExact, filterIdPrefix, filterHand, filterControllerIndex) {
  55984. var controller;
  55985. var i;
  55986. var matchingControllerOccurence = 0;
  55987. var targetControllerMatch = filterControllerIndex || 0;
  55988. for (i = 0; i < controllers.length; i++) {
  55989. controller = controllers[i];
  55990. // Determine if the controller ID matches our criteria
  55991. if (filterIdPrefix && controller.id.indexOf(filterIdPrefix) === -1) { continue; }
  55992. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  55993. // If the hand filter and controller handedness are defined we compare them.
  55994. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  55995. // If we have detected an unhanded controller and the component was asking for a particular hand,
  55996. // we need to treat the controllers in the array as pairs of controllers. This effectively means that we
  55997. // need to skip NUM_HANDS matches for each controller number, instead of 1.
  55998. if (filterHand && !controller.hand) {
  55999. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  56000. }
  56001. // We are looking for the nth occurence of a matching controller (n equals targetControllerMatch).
  56002. if (matchingControllerOccurence === targetControllerMatch) {
  56003. return controller;
  56004. }
  56005. ++matchingControllerOccurence;
  56006. }
  56007. return undefined;
  56008. }
  56009. module.exports.findMatchingController = findMatchingController;
  56010. /**
  56011. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  56012. *
  56013. * @param {object} component - Controller component in use.
  56014. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  56015. * @param {object} evt - Event to process.
  56016. */
  56017. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  56018. var axes;
  56019. var buttonTypes;
  56020. var changed;
  56021. var detail;
  56022. var i;
  56023. var j;
  56024. buttonTypes = Object.keys(axesMapping);
  56025. for (i = 0; i < buttonTypes.length; i++) {
  56026. axes = axesMapping[buttonTypes[i]];
  56027. changed = false;
  56028. for (j = 0; j < axes.length; j++) {
  56029. if (evt.detail.changed[axes[j]]) { changed = true; }
  56030. }
  56031. if (!changed) { continue; }
  56032. // Axis has changed. Emit the specific moved event with axis values in detail.
  56033. detail = {};
  56034. for (j = 0; j < axes.length; j++) {
  56035. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  56036. }
  56037. component.el.emit(buttonTypes[i] + 'moved', detail);
  56038. }
  56039. };
  56040. },{"../constants":116}],201:[function(_dereq_,module,exports){
  56041. /**
  56042. * @author dmarcos / https://github.com/dmarcos
  56043. * @author mrdoob / http://mrdoob.com
  56044. */
  56045. THREE.VRControls = function ( object, onError ) {
  56046. var scope = this;
  56047. var vrDisplay, vrDisplays;
  56048. var standingMatrix = new THREE.Matrix4();
  56049. var frameData = null;
  56050. if ( 'VRFrameData' in window ) {
  56051. frameData = new window.VRFrameData();
  56052. }
  56053. window.addEventListener('vrdisplayconnect', function (evt) { vrDisplay = evt.display; });
  56054. window.addEventListener('vrdisplaydisconnect', function () { vrDisplay = undefined });
  56055. function gotVRDisplays( displays ) {
  56056. vrDisplays = displays;
  56057. if ( displays.length > 0 ) {
  56058. vrDisplay = displays[ 0 ];
  56059. } else {
  56060. if ( onError ) onError( 'VR input not available.' );
  56061. }
  56062. }
  56063. if ( navigator.getVRDisplays ) {
  56064. navigator.getVRDisplays().then( gotVRDisplays ).catch ( function () {
  56065. console.warn( 'THREE.VRControls: Unable to get VR Displays' );
  56066. } );
  56067. }
  56068. // the Rift SDK returns the position in meters
  56069. // this scale factor allows the user to define how meters
  56070. // are converted to scene units.
  56071. this.scale = 1;
  56072. // If true will use "standing space" coordinate system where y=0 is the
  56073. // floor and x=0, z=0 is the center of the room.
  56074. this.standing = false;
  56075. // Distance from the users eyes to the floor in meters. Used when
  56076. // standing=true but the VRDisplay doesn't provide stageParameters.
  56077. this.userHeight = 1.6;
  56078. this.getVRDisplay = function () {
  56079. return vrDisplay;
  56080. };
  56081. this.setVRDisplay = function ( value ) {
  56082. vrDisplay = value;
  56083. };
  56084. this.getVRDisplays = function () {
  56085. console.warn( 'THREE.VRControls: getVRDisplays() is being deprecated.' );
  56086. return vrDisplays;
  56087. };
  56088. this.getStandingMatrix = function () {
  56089. return standingMatrix;
  56090. };
  56091. this.update = function () {
  56092. if ( vrDisplay ) {
  56093. var pose;
  56094. if ( vrDisplay.getFrameData ) {
  56095. vrDisplay.getFrameData( frameData );
  56096. pose = frameData.pose;
  56097. } else if ( vrDisplay.getPose ) {
  56098. pose = vrDisplay.getPose();
  56099. }
  56100. if ( pose.orientation !== null ) {
  56101. object.quaternion.fromArray( pose.orientation );
  56102. }
  56103. if ( pose.position !== null ) {
  56104. object.position.fromArray( pose.position );
  56105. } else {
  56106. object.position.set( 0, 0, 0 );
  56107. }
  56108. if ( this.standing ) {
  56109. if ( vrDisplay.stageParameters ) {
  56110. object.updateMatrix();
  56111. standingMatrix.fromArray( vrDisplay.stageParameters.sittingToStandingTransform );
  56112. object.applyMatrix( standingMatrix );
  56113. } else {
  56114. object.position.setY( object.position.y + this.userHeight );
  56115. }
  56116. }
  56117. object.position.multiplyScalar( scope.scale );
  56118. }
  56119. };
  56120. this.resetPose = function () {
  56121. if ( vrDisplay ) {
  56122. vrDisplay.resetPose();
  56123. }
  56124. };
  56125. this.resetSensor = function () {
  56126. console.warn( 'THREE.VRControls: .resetSensor() is now .resetPose().' );
  56127. this.resetPose();
  56128. };
  56129. this.zeroSensor = function () {
  56130. console.warn( 'THREE.VRControls: .zeroSensor() is now .resetPose().' );
  56131. this.resetPose();
  56132. };
  56133. this.dispose = function () {
  56134. vrDisplay = null;
  56135. };
  56136. };
  56137. },{}],202:[function(_dereq_,module,exports){
  56138. /**
  56139. * @author dmarcos / https://github.com/dmarcos
  56140. * @author mrdoob / http://mrdoob.com
  56141. *
  56142. * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
  56143. *
  56144. * Firefox: http://mozvr.com/downloads/
  56145. * Chromium: https://webvr.info/get-chrome
  56146. *
  56147. */
  56148. THREE.VREffect = function( renderer, onError ) {
  56149. var vrDisplay, vrDisplays;
  56150. var eyeTranslationL = new THREE.Vector3();
  56151. var eyeTranslationR = new THREE.Vector3();
  56152. var renderRectL, renderRectR;
  56153. var frameData = null;
  56154. if ( 'VRFrameData' in window ) {
  56155. frameData = new window.VRFrameData();
  56156. }
  56157. window.addEventListener('vrdisplayconnect', function (evt) { vrDisplay = evt.display; });
  56158. window.addEventListener('vrdisplaydisconnect', function (evt) {
  56159. var f;
  56160. scope.exitPresent();
  56161. // Cancels current request animation frame.
  56162. f = scope.cancelAnimationFrame();
  56163. vrDisplay = undefined;
  56164. // Resumes the request animation frame.
  56165. scope.requestAnimationFrame(f);
  56166. });
  56167. function gotVRDisplays( displays ) {
  56168. vrDisplays = displays;
  56169. if ( displays.length > 0 ) {
  56170. vrDisplay = displays[ 0 ];
  56171. } else {
  56172. if ( onError ) onError( 'HMD not available' );
  56173. }
  56174. }
  56175. if ( navigator.getVRDisplays ) {
  56176. navigator.getVRDisplays().then( gotVRDisplays ).catch( function() {
  56177. console.warn( 'THREE.VREffect: Unable to get VR Displays' );
  56178. } );
  56179. }
  56180. //
  56181. this.isPresenting = false;
  56182. var scope = this;
  56183. var rendererSize = renderer.getSize();
  56184. var rendererUpdateStyle = false;
  56185. var rendererPixelRatio = renderer.getPixelRatio();
  56186. this.getVRDisplay = function() {
  56187. return vrDisplay;
  56188. };
  56189. this.setVRDisplay = function( value ) {
  56190. vrDisplay = value;
  56191. };
  56192. this.getVRDisplays = function() {
  56193. console.warn( 'THREE.VREffect: getVRDisplays() is being deprecated.' );
  56194. return vrDisplays;
  56195. };
  56196. this.setSize = function( width, height, updateStyle ) {
  56197. rendererSize = { width: width, height: height };
  56198. rendererUpdateStyle = updateStyle;
  56199. if ( scope.isPresenting ) {
  56200. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  56201. renderer.setPixelRatio( 1 );
  56202. renderer.setSize( eyeParamsL.renderWidth * 2, eyeParamsL.renderHeight, false );
  56203. } else {
  56204. renderer.setPixelRatio( rendererPixelRatio );
  56205. renderer.setSize( width, height, updateStyle );
  56206. }
  56207. };
  56208. // VR presentation
  56209. var canvas = renderer.domElement;
  56210. var defaultLeftBounds = [ 0.0, 0.0, 0.5, 1.0 ];
  56211. var defaultRightBounds = [ 0.5, 0.0, 0.5, 1.0 ];
  56212. function onVRDisplayPresentChange() {
  56213. var wasPresenting = scope.isPresenting;
  56214. scope.isPresenting = vrDisplay !== undefined && vrDisplay.isPresenting;
  56215. if ( scope.isPresenting ) {
  56216. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  56217. var eyeWidth = eyeParamsL.renderWidth;
  56218. var eyeHeight = eyeParamsL.renderHeight;
  56219. if ( ! wasPresenting ) {
  56220. rendererPixelRatio = renderer.getPixelRatio();
  56221. rendererSize = renderer.getSize();
  56222. renderer.setPixelRatio( 1 );
  56223. renderer.setSize( eyeWidth * 2, eyeHeight, false );
  56224. }
  56225. } else if ( wasPresenting ) {
  56226. renderer.setPixelRatio( rendererPixelRatio );
  56227. renderer.setSize( rendererSize.width, rendererSize.height, rendererUpdateStyle );
  56228. }
  56229. }
  56230. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  56231. this.setFullScreen = function( boolean ) {
  56232. return new Promise( function( resolve, reject ) {
  56233. if ( vrDisplay === undefined ) {
  56234. reject( new Error( 'No VR hardware found.' ) );
  56235. return;
  56236. }
  56237. if ( scope.isPresenting === boolean ) {
  56238. resolve();
  56239. return;
  56240. }
  56241. if ( boolean ) {
  56242. resolve( vrDisplay.requestPresent( [ { source: canvas } ] ) );
  56243. } else {
  56244. resolve( vrDisplay.exitPresent() );
  56245. }
  56246. } );
  56247. };
  56248. this.requestPresent = function() {
  56249. return this.setFullScreen( true );
  56250. };
  56251. this.exitPresent = function() {
  56252. return this.setFullScreen( false );
  56253. };
  56254. this.requestAnimationFrame = function( f ) {
  56255. var f = scope.f = f || scope.f;
  56256. if (!f) { return; }
  56257. if ( vrDisplay !== undefined ) {
  56258. return vrDisplay.requestAnimationFrame( f );
  56259. } else {
  56260. return window.requestAnimationFrame( f );
  56261. }
  56262. };
  56263. this.cancelAnimationFrame = function( h ) {
  56264. var f = scope.f;
  56265. scope.f = undefined;
  56266. if ( vrDisplay !== undefined ) {
  56267. vrDisplay.cancelAnimationFrame( h );
  56268. } else {
  56269. window.cancelAnimationFrame( h );
  56270. }
  56271. return f;
  56272. };
  56273. this.submitFrame = function() {
  56274. if ( vrDisplay !== undefined && scope.isPresenting ) {
  56275. vrDisplay.submitFrame();
  56276. }
  56277. };
  56278. this.autoSubmitFrame = true;
  56279. // render
  56280. var cameraL = new THREE.PerspectiveCamera();
  56281. cameraL.layers.enable( 1 );
  56282. var cameraR = new THREE.PerspectiveCamera();
  56283. cameraR.layers.enable( 2 );
  56284. this.render = function( scene, camera, renderTarget, forceClear ) {
  56285. if ( vrDisplay && scope.isPresenting ) {
  56286. var autoUpdate = scene.autoUpdate;
  56287. if ( autoUpdate ) {
  56288. scene.updateMatrixWorld();
  56289. scene.autoUpdate = false;
  56290. }
  56291. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  56292. var eyeParamsR = vrDisplay.getEyeParameters( 'right' );
  56293. eyeTranslationL.fromArray( eyeParamsL.offset );
  56294. eyeTranslationR.fromArray( eyeParamsR.offset );
  56295. if ( Array.isArray( scene ) ) {
  56296. console.warn( 'THREE.VREffect.render() no longer supports arrays. Use object.layers instead.' );
  56297. scene = scene[ 0 ];
  56298. }
  56299. // When rendering we don't care what the recommended size is, only what the actual size
  56300. // of the backbuffer is.
  56301. var size = renderer.getSize();
  56302. var layers = vrDisplay.getLayers();
  56303. var leftBounds;
  56304. var rightBounds;
  56305. if ( layers.length ) {
  56306. var layer = layers[ 0 ];
  56307. leftBounds = layer.leftBounds !== null && layer.leftBounds.length === 4 ? layer.leftBounds : defaultLeftBounds;
  56308. rightBounds = layer.rightBounds !== null && layer.rightBounds.length === 4 ? layer.rightBounds : defaultRightBounds;
  56309. } else {
  56310. leftBounds = defaultLeftBounds;
  56311. rightBounds = defaultRightBounds;
  56312. }
  56313. renderRectL = {
  56314. x: Math.round( size.width * leftBounds[ 0 ] ),
  56315. y: Math.round( size.height * leftBounds[ 1 ] ),
  56316. width: Math.round( size.width * leftBounds[ 2 ] ),
  56317. height: Math.round( size.height * leftBounds[ 3 ] )
  56318. };
  56319. renderRectR = {
  56320. x: Math.round( size.width * rightBounds[ 0 ] ),
  56321. y: Math.round( size.height * rightBounds[ 1 ] ),
  56322. width: Math.round( size.width * rightBounds[ 2 ] ),
  56323. height: Math.round( size.height * rightBounds[ 3 ] )
  56324. };
  56325. if ( renderTarget ) {
  56326. renderer.setRenderTarget( renderTarget );
  56327. renderTarget.scissorTest = true;
  56328. } else {
  56329. renderer.setRenderTarget( null );
  56330. renderer.setScissorTest( true );
  56331. }
  56332. if ( renderer.autoClear || forceClear ) renderer.clear();
  56333. if ( camera.parent === null ) camera.updateMatrixWorld();
  56334. camera.matrixWorld.decompose( cameraL.position, cameraL.quaternion, cameraL.scale );
  56335. cameraR.position.copy(cameraL.position);
  56336. cameraR.quaternion.copy(cameraL.quaternion);
  56337. cameraR.scale.copy(cameraL.scale);
  56338. cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x );
  56339. cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x );
  56340. if ( vrDisplay.getFrameData ) {
  56341. vrDisplay.depthNear = camera.near;
  56342. vrDisplay.depthFar = camera.far;
  56343. vrDisplay.getFrameData( frameData );
  56344. cameraL.projectionMatrix.elements = frameData.leftProjectionMatrix;
  56345. cameraR.projectionMatrix.elements = frameData.rightProjectionMatrix;
  56346. } else {
  56347. cameraL.projectionMatrix = fovToProjection( eyeParamsL.fieldOfView, true, camera.near, camera.far );
  56348. cameraR.projectionMatrix = fovToProjection( eyeParamsR.fieldOfView, true, camera.near, camera.far );
  56349. }
  56350. // render left eye
  56351. if ( renderTarget ) {
  56352. renderTarget.viewport.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  56353. renderTarget.scissor.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  56354. } else {
  56355. renderer.setViewport( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  56356. renderer.setScissor( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  56357. }
  56358. renderer.render( scene, cameraL, renderTarget, forceClear );
  56359. // render right eye
  56360. if ( renderTarget ) {
  56361. renderTarget.viewport.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  56362. renderTarget.scissor.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  56363. } else {
  56364. renderer.setViewport( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  56365. renderer.setScissor( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  56366. }
  56367. renderer.render( scene, cameraR, renderTarget, forceClear );
  56368. if ( renderTarget ) {
  56369. renderTarget.viewport.set( 0, 0, size.width, size.height );
  56370. renderTarget.scissor.set( 0, 0, size.width, size.height );
  56371. renderTarget.scissorTest = false;
  56372. renderer.setRenderTarget( null );
  56373. } else {
  56374. renderer.setViewport( 0, 0, size.width, size.height );
  56375. renderer.setScissorTest( false );
  56376. }
  56377. if ( autoUpdate ) {
  56378. scene.autoUpdate = true;
  56379. }
  56380. if ( scope.autoSubmitFrame ) {
  56381. scope.submitFrame();
  56382. }
  56383. return;
  56384. }
  56385. // Regular render mode if not HMD
  56386. renderer.render( scene, camera, renderTarget, forceClear );
  56387. };
  56388. this.dispose = function() {
  56389. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  56390. };
  56391. //
  56392. function fovToNDCScaleOffset( fov ) {
  56393. var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
  56394. var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
  56395. var pyscale = 2.0 / ( fov.upTan + fov.downTan );
  56396. var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
  56397. return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };
  56398. }
  56399. function fovPortToProjection( fov, rightHanded, zNear, zFar ) {
  56400. rightHanded = rightHanded === undefined ? true : rightHanded;
  56401. zNear = zNear === undefined ? 0.01 : zNear;
  56402. zFar = zFar === undefined ? 10000.0 : zFar;
  56403. var handednessScale = rightHanded ? - 1.0 : 1.0;
  56404. // start with an identity matrix
  56405. var mobj = new THREE.Matrix4();
  56406. var m = mobj.elements;
  56407. // and with scale/offset info for normalized device coords
  56408. var scaleAndOffset = fovToNDCScaleOffset( fov );
  56409. // X result, map clip edges to [-w,+w]
  56410. m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
  56411. m[ 0 * 4 + 1 ] = 0.0;
  56412. m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
  56413. m[ 0 * 4 + 3 ] = 0.0;
  56414. // Y result, map clip edges to [-w,+w]
  56415. // Y offset is negated because this proj matrix transforms from world coords with Y=up,
  56416. // but the NDC scaling has Y=down (thanks D3D?)
  56417. m[ 1 * 4 + 0 ] = 0.0;
  56418. m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
  56419. m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
  56420. m[ 1 * 4 + 3 ] = 0.0;
  56421. // Z result (up to the app)
  56422. m[ 2 * 4 + 0 ] = 0.0;
  56423. m[ 2 * 4 + 1 ] = 0.0;
  56424. m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
  56425. m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );
  56426. // W result (= Z in)
  56427. m[ 3 * 4 + 0 ] = 0.0;
  56428. m[ 3 * 4 + 1 ] = 0.0;
  56429. m[ 3 * 4 + 2 ] = handednessScale;
  56430. m[ 3 * 4 + 3 ] = 0.0;
  56431. mobj.transpose();
  56432. return mobj;
  56433. }
  56434. function fovToProjection( fov, rightHanded, zNear, zFar ) {
  56435. var DEG2RAD = Math.PI / 180.0;
  56436. var fovPort = {
  56437. upTan: Math.tan( fov.upDegrees * DEG2RAD ),
  56438. downTan: Math.tan( fov.downDegrees * DEG2RAD ),
  56439. leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
  56440. rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
  56441. };
  56442. return fovPortToProjection( fovPort, rightHanded, zNear, zFar );
  56443. }
  56444. };
  56445. },{}],203:[function(_dereq_,module,exports){
  56446. window.glStats = function () {
  56447. var _rS = null;
  56448. var _totalDrawArraysCalls = 0,
  56449. _totalDrawElementsCalls = 0,
  56450. _totalUseProgramCalls = 0,
  56451. _totalFaces = 0,
  56452. _totalVertices = 0,
  56453. _totalPoints = 0,
  56454. _totalBindTexures = 0;
  56455. function _h ( f, c ) {
  56456. return function () {
  56457. c.apply( this, arguments );
  56458. f.apply( this, arguments );
  56459. };
  56460. }
  56461. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  56462. _totalDrawArraysCalls++;
  56463. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  56464. else _totalVertices += arguments[ 2 ];
  56465. } );
  56466. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  56467. _totalDrawElementsCalls++;
  56468. _totalFaces += arguments[ 1 ] / 3;
  56469. _totalVertices += arguments[ 1 ];
  56470. } );
  56471. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  56472. _totalUseProgramCalls++;
  56473. } );
  56474. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  56475. _totalBindTexures++;
  56476. } );
  56477. var _values = {
  56478. allcalls: {
  56479. over: 3000,
  56480. caption: 'Calls (hook)'
  56481. },
  56482. drawelements: {
  56483. caption: 'drawElements (hook)'
  56484. },
  56485. drawarrays: {
  56486. caption: 'drawArrays (hook)'
  56487. }
  56488. };
  56489. var _groups = [ {
  56490. caption: 'WebGL',
  56491. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  56492. } ];
  56493. var _fractions = [ {
  56494. base: 'allcalls',
  56495. steps: [ 'drawelements', 'drawarrays' ]
  56496. } ];
  56497. function _update () {
  56498. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  56499. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  56500. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  56501. _rS( 'bindTexture' ).set( _totalBindTexures );
  56502. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  56503. _rS( 'glfaces' ).set( _totalFaces );
  56504. _rS( 'glvertices' ).set( _totalVertices );
  56505. _rS( 'glpoints' ).set( _totalPoints );
  56506. }
  56507. function _start () {
  56508. _totalDrawArraysCalls = 0;
  56509. _totalDrawElementsCalls = 0;
  56510. _totalUseProgramCalls = 0;
  56511. _totalFaces = 0;
  56512. _totalVertices = 0;
  56513. _totalPoints = 0;
  56514. _totalBindTexures = 0;
  56515. }
  56516. function _end () {}
  56517. function _attach ( r ) {
  56518. _rS = r;
  56519. }
  56520. return {
  56521. update: _update,
  56522. start: _start,
  56523. end: _end,
  56524. attach: _attach,
  56525. values: _values,
  56526. groups: _groups,
  56527. fractions: _fractions
  56528. };
  56529. };
  56530. window.threeStats = function ( renderer ) {
  56531. var _rS = null;
  56532. var _values = {
  56533. 'renderer.info.memory.geometries': {
  56534. caption: 'Geometries'
  56535. },
  56536. 'renderer.info.memory.textures': {
  56537. caption: 'Textures'
  56538. },
  56539. 'renderer.info.programs': {
  56540. caption: 'Programs'
  56541. },
  56542. 'renderer.info.render.calls': {
  56543. caption: 'Calls'
  56544. },
  56545. 'renderer.info.render.faces': {
  56546. caption: 'Faces',
  56547. over: 1000
  56548. },
  56549. 'renderer.info.render.points': {
  56550. caption: 'Points'
  56551. },
  56552. 'renderer.info.render.vertices': {
  56553. caption: 'Vertices'
  56554. }
  56555. };
  56556. var _groups = [ {
  56557. caption: 'Three.js - Memory',
  56558. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  56559. }, {
  56560. caption: 'Three.js - Render',
  56561. values: [ 'renderer.info.render.calls', 'renderer.info.render.faces', 'renderer.info.render.points', 'renderer.info.render.vertices' ]
  56562. } ];
  56563. var _fractions = [];
  56564. function _update () {
  56565. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  56566. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  56567. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  56568. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  56569. _rS( 'renderer.info.render.faces' ).set( renderer.info.render.faces );
  56570. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  56571. _rS( 'renderer.info.render.vertices' ).set( renderer.info.render.vertices );
  56572. }
  56573. function _start () {}
  56574. function _end () {}
  56575. function _attach ( r ) {
  56576. _rS = r;
  56577. }
  56578. return {
  56579. update: _update,
  56580. start: _start,
  56581. end: _end,
  56582. attach: _attach,
  56583. values: _values,
  56584. groups: _groups,
  56585. fractions: _fractions
  56586. };
  56587. };
  56588. /*
  56589. * From https://github.com/paulirish/memory-stats.js
  56590. */
  56591. window.BrowserStats = function () {
  56592. var _rS = null;
  56593. var _usedJSHeapSize = 0,
  56594. _totalJSHeapSize = 0;
  56595. if ( window.performance && !performance.memory ) {
  56596. performance.memory = {
  56597. usedJSHeapSize: 0,
  56598. totalJSHeapSize: 0
  56599. };
  56600. }
  56601. if ( performance.memory.totalJSHeapSize === 0 ) {
  56602. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  56603. }
  56604. var _values = {
  56605. memory: {
  56606. caption: 'Used Memory',
  56607. average: true,
  56608. avgMs: 1000,
  56609. over: 22
  56610. },
  56611. total: {
  56612. caption: 'Total Memory'
  56613. }
  56614. };
  56615. var _groups = [ {
  56616. caption: 'Browser',
  56617. values: [ 'memory', 'total' ]
  56618. } ];
  56619. var _fractions = [ {
  56620. base: 'total',
  56621. steps: [ 'memory' ]
  56622. } ];
  56623. var log1024 = Math.log( 1024 );
  56624. function _size ( v ) {
  56625. var precision = 100; //Math.pow(10, 2);
  56626. var i = Math.floor( Math.log( v ) / log1024 );
  56627. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  56628. }
  56629. function _update () {
  56630. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  56631. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  56632. _rS( 'memory' ).set( _usedJSHeapSize );
  56633. _rS( 'total' ).set( _totalJSHeapSize );
  56634. }
  56635. function _start () {
  56636. _usedJSHeapSize = 0;
  56637. }
  56638. function _end () {}
  56639. function _attach ( r ) {
  56640. _rS = r;
  56641. }
  56642. return {
  56643. update: _update,
  56644. start: _start,
  56645. end: _end,
  56646. attach: _attach,
  56647. values: _values,
  56648. groups: _groups,
  56649. fractions: _fractions
  56650. };
  56651. };
  56652. if (typeof module === 'object') {
  56653. module.exports = {
  56654. glStats: window.glStats,
  56655. threeStats: window.threeStats,
  56656. BrowserStats: window.BrowserStats
  56657. };
  56658. }
  56659. },{}],204:[function(_dereq_,module,exports){
  56660. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  56661. 'use strict';
  56662. ( function () {
  56663. if ( 'performance' in window == false ) {
  56664. window.performance = {};
  56665. }
  56666. var performance = window.performance;
  56667. if ( 'now' in performance == false ) {
  56668. var nowOffset = Date.now();
  56669. if ( performance.timing && performance.timing.navigationStart ) {
  56670. nowOffset = performance.timing.navigationStart;
  56671. }
  56672. performance.now = function now () {
  56673. return Date.now() - nowOffset;
  56674. };
  56675. }
  56676. if( !performance.mark ) {
  56677. performance.mark = function(){}
  56678. }
  56679. if( !performance.measure ) {
  56680. performance.measure = function(){}
  56681. }
  56682. } )();
  56683. window.rStats = function rStats ( settings ) {
  56684. function iterateKeys ( array, callback ) {
  56685. var keys = Object.keys( array );
  56686. for ( var j = 0, l = keys.length; j < l; j++ ) {
  56687. callback( keys[ j ] );
  56688. }
  56689. }
  56690. function importCSS ( url ) {
  56691. var element = document.createElement( 'link' );
  56692. element.href = url;
  56693. element.rel = 'stylesheet';
  56694. element.type = 'text/css';
  56695. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  56696. }
  56697. var _settings = settings || {};
  56698. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  56699. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  56700. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  56701. var _css = _settings.css || [ _cssFont, _cssRStats ];
  56702. _css.forEach(function (uri) {
  56703. importCSS( uri );
  56704. });
  56705. if ( !_settings.values ) _settings.values = {};
  56706. var _base, _div, _elHeight = 10, _elWidth = 200;
  56707. var _perfCounters = {};
  56708. function Graph ( _dom, _id, _defArg ) {
  56709. var _def = _defArg || {};
  56710. var _canvas = document.createElement( 'canvas' ),
  56711. _ctx = _canvas.getContext( '2d' ),
  56712. _max = 0,
  56713. _current = 0;
  56714. var c = _def.color ? _def.color : '#666666';
  56715. var _dotCanvas = document.createElement( 'canvas' ),
  56716. _dotCtx = _dotCanvas.getContext( '2d' );
  56717. _dotCanvas.width = 1;
  56718. _dotCanvas.height = 2 * _elHeight;
  56719. _dotCtx.fillStyle = '#444444';
  56720. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56721. _dotCtx.fillStyle = c;
  56722. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56723. _dotCtx.fillStyle = '#ffffff';
  56724. _dotCtx.globalAlpha = 0.5;
  56725. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  56726. _dotCtx.globalAlpha = 1;
  56727. var _alarmCanvas = document.createElement( 'canvas' ),
  56728. _alarmCtx = _alarmCanvas.getContext( '2d' );
  56729. _alarmCanvas.width = 1;
  56730. _alarmCanvas.height = 2 * _elHeight;
  56731. _alarmCtx.fillStyle = '#444444';
  56732. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56733. _alarmCtx.fillStyle = '#b70000';
  56734. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56735. _alarmCtx.globalAlpha = 0.5;
  56736. _alarmCtx.fillStyle = '#ffffff';
  56737. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  56738. _alarmCtx.globalAlpha = 1;
  56739. function _init () {
  56740. _canvas.width = _elWidth;
  56741. _canvas.height = _elHeight;
  56742. _canvas.style.width = _canvas.width + 'px';
  56743. _canvas.style.height = _canvas.height + 'px';
  56744. _canvas.className = 'rs-canvas';
  56745. _dom.appendChild( _canvas );
  56746. _ctx.fillStyle = '#444444';
  56747. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56748. }
  56749. function _draw ( v, alarm ) {
  56750. _current += ( v - _current ) * 0.1;
  56751. _max *= 0.99;
  56752. if ( _current > _max ) _max = _current;
  56753. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56754. if ( alarm ) {
  56755. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56756. } else {
  56757. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56758. }
  56759. }
  56760. _init();
  56761. return {
  56762. draw: _draw
  56763. };
  56764. }
  56765. function StackGraph ( _dom, _num ) {
  56766. var _canvas = document.createElement( 'canvas' ),
  56767. _ctx = _canvas.getContext( '2d' );
  56768. function _init () {
  56769. _canvas.width = _elWidth;
  56770. _canvas.height = _elHeight * _num;
  56771. _canvas.style.width = _canvas.width + 'px';
  56772. _canvas.style.height = _canvas.height + 'px';
  56773. _canvas.className = 'rs-canvas';
  56774. _dom.appendChild( _canvas );
  56775. _ctx.fillStyle = '#444444';
  56776. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56777. }
  56778. function _draw ( v ) {
  56779. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56780. var th = 0;
  56781. iterateKeys( v, function ( j ) {
  56782. var h = v[ j ] * _canvas.height;
  56783. _ctx.fillStyle = _colours[ j ];
  56784. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  56785. th += h;
  56786. } );
  56787. }
  56788. _init();
  56789. return {
  56790. draw: _draw
  56791. };
  56792. }
  56793. function PerfCounter ( id, group ) {
  56794. var _id = id,
  56795. _time,
  56796. _value = 0,
  56797. _total = 0,
  56798. _averageValue = 0,
  56799. _accumValue = 0,
  56800. _accumStart = performance.now(),
  56801. _accumSamples = 0,
  56802. _dom = document.createElement( 'div' ),
  56803. _spanId = document.createElement( 'span' ),
  56804. _spanValue = document.createElement( 'div' ),
  56805. _spanValueText = document.createTextNode( '' ),
  56806. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  56807. _graph = new Graph( _dom, _id, _def ),
  56808. _started = false;
  56809. _spanId.className = 'rs-counter-id';
  56810. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  56811. _spanValue.className = 'rs-counter-value';
  56812. _spanValue.appendChild( _spanValueText );
  56813. _dom.appendChild( _spanId );
  56814. _dom.appendChild( _spanValue );
  56815. if ( group ) group.div.appendChild( _dom );
  56816. else _div.appendChild( _dom );
  56817. _time = performance.now();
  56818. function _average ( v ) {
  56819. if ( _def && _def.average ) {
  56820. _accumValue += v;
  56821. _accumSamples++;
  56822. var t = performance.now();
  56823. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  56824. _averageValue = _accumValue / _accumSamples;
  56825. _accumValue = 0;
  56826. _accumStart = t;
  56827. _accumSamples = 0;
  56828. }
  56829. }
  56830. }
  56831. function _start () {
  56832. _time = performance.now();
  56833. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  56834. _started = true;
  56835. }
  56836. function _end () {
  56837. _value = performance.now() - _time;
  56838. if( _settings.userTimingAPI ) {
  56839. performance.mark( _id + '-end' );
  56840. if( _started ) {
  56841. performance.measure( _id, _id + '-start', _id + '-end' );
  56842. }
  56843. }
  56844. _average( _value );
  56845. }
  56846. function _tick () {
  56847. _end();
  56848. _start();
  56849. }
  56850. function _draw () {
  56851. var v = ( _def && _def.average ) ? _averageValue : _value;
  56852. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  56853. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  56854. _graph.draw( _value, a );
  56855. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  56856. }
  56857. function _frame () {
  56858. var t = performance.now();
  56859. var e = t - _time;
  56860. _total++;
  56861. if ( e > 1000 ) {
  56862. if ( _def && _def.interpolate === false ) {
  56863. _value = _total;
  56864. } else {
  56865. _value = _total * 1000 / e;
  56866. }
  56867. _total = 0;
  56868. _time = t;
  56869. _average( _value );
  56870. }
  56871. }
  56872. function _set ( v ) {
  56873. _value = v;
  56874. _average( _value );
  56875. }
  56876. return {
  56877. set: _set,
  56878. start: _start,
  56879. tick: _tick,
  56880. end: _end,
  56881. frame: _frame,
  56882. value: function () {
  56883. return _value;
  56884. },
  56885. draw: _draw
  56886. };
  56887. }
  56888. function sample () {
  56889. var _value = 0;
  56890. function _set ( v ) {
  56891. _value = v;
  56892. }
  56893. return {
  56894. set: _set,
  56895. value: function () {
  56896. return _value;
  56897. }
  56898. };
  56899. }
  56900. function _perf ( idArg ) {
  56901. var id = idArg.toLowerCase();
  56902. if ( id === undefined ) id = 'default';
  56903. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  56904. var group = null;
  56905. if ( _settings && _settings.groups ) {
  56906. iterateKeys( _settings.groups, function ( j ) {
  56907. var g = _settings.groups[ parseInt( j, 10 ) ];
  56908. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  56909. group = g;
  56910. }
  56911. } );
  56912. }
  56913. var p = new PerfCounter( id, group );
  56914. _perfCounters[ id ] = p;
  56915. return p;
  56916. }
  56917. function _init () {
  56918. if ( _settings.plugins ) {
  56919. if ( !_settings.values ) _settings.values = {};
  56920. if ( !_settings.groups ) _settings.groups = [];
  56921. if ( !_settings.fractions ) _settings.fractions = [];
  56922. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  56923. _settings.plugins[ j ].attach( _perf );
  56924. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  56925. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  56926. } );
  56927. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  56928. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  56929. }
  56930. } else {
  56931. _settings.plugins = {};
  56932. }
  56933. _base = document.createElement( 'div' );
  56934. _base.className = 'rs-base';
  56935. _div = document.createElement( 'div' );
  56936. _div.className = 'rs-container';
  56937. _div.style.height = 'auto';
  56938. _base.appendChild( _div );
  56939. document.body.appendChild( _base );
  56940. if ( !_settings ) return;
  56941. if ( _settings.groups ) {
  56942. iterateKeys( _settings.groups, function ( j ) {
  56943. var g = _settings.groups[ parseInt( j, 10 ) ];
  56944. var div = document.createElement( 'div' );
  56945. div.className = 'rs-group';
  56946. g.div = div;
  56947. var h1 = document.createElement( 'h1' );
  56948. h1.textContent = g.caption;
  56949. h1.addEventListener( 'click', function ( e ) {
  56950. this.classList.toggle( 'hidden' );
  56951. e.preventDefault();
  56952. }.bind( div ) );
  56953. _div.appendChild( h1 );
  56954. _div.appendChild( div );
  56955. } );
  56956. }
  56957. if ( _settings.fractions ) {
  56958. iterateKeys( _settings.fractions, function ( j ) {
  56959. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56960. var div = document.createElement( 'div' );
  56961. div.className = 'rs-fraction';
  56962. var legend = document.createElement( 'div' );
  56963. legend.className = 'rs-legend';
  56964. var h = 0;
  56965. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56966. var p = document.createElement( 'p' );
  56967. p.textContent = _settings.fractions[ j ].steps[ k ];
  56968. p.style.color = _colours[ h ];
  56969. legend.appendChild( p );
  56970. h++;
  56971. } );
  56972. div.appendChild( legend );
  56973. div.style.height = h * _elHeight + 'px';
  56974. f.div = div;
  56975. var graph = new StackGraph( div, h );
  56976. f.graph = graph;
  56977. _div.appendChild( div );
  56978. } );
  56979. }
  56980. }
  56981. function _update () {
  56982. iterateKeys( _settings.plugins, function ( j ) {
  56983. _settings.plugins[ j ].update();
  56984. } );
  56985. iterateKeys( _perfCounters, function ( j ) {
  56986. _perfCounters[ j ].draw();
  56987. } );
  56988. if ( _settings && _settings.fractions ) {
  56989. iterateKeys( _settings.fractions, function ( j ) {
  56990. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56991. var v = [];
  56992. var base = _perfCounters[ f.base.toLowerCase() ];
  56993. if ( base ) {
  56994. base = base.value();
  56995. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56996. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  56997. var val = _perfCounters[ s ];
  56998. if ( val ) {
  56999. v.push( val.value() / base );
  57000. }
  57001. } );
  57002. }
  57003. f.graph.draw( v );
  57004. } );
  57005. }
  57006. /*if( _height != _div.clientHeight ) {
  57007. _height = _div.clientHeight;
  57008. _base.style.height = _height + 2 * _elHeight + 'px';
  57009. console.log( _base.clientHeight );
  57010. }*/
  57011. }
  57012. _init();
  57013. return function ( id ) {
  57014. if ( id ) return _perf( id );
  57015. return {
  57016. element: _base,
  57017. update: _update
  57018. };
  57019. };
  57020. }
  57021. if (typeof module === 'object') {
  57022. module.exports = window.rStats;
  57023. }
  57024. },{}],205:[function(_dereq_,module,exports){
  57025. /*
  57026. * Copyright 2015 Google Inc. All Rights Reserved.
  57027. * Licensed under the Apache License, Version 2.0 (the "License");
  57028. * you may not use this file except in compliance with the License.
  57029. * You may obtain a copy of the License at
  57030. *
  57031. * http://www.apache.org/licenses/LICENSE-2.0
  57032. *
  57033. * Unless required by applicable law or agreed to in writing, software
  57034. * distributed under the License is distributed on an "AS IS" BASIS,
  57035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57036. * See the License for the specific language governing permissions and
  57037. * limitations under the License.
  57038. */
  57039. var Util = {};
  57040. Util.base64 = function(mimeType, base64) {
  57041. return 'data:' + mimeType + ';base64,' + base64;
  57042. };
  57043. Util.isMobile = function() {
  57044. var check = false;
  57045. (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);
  57046. return check;
  57047. };
  57048. Util.isIOS = function() {
  57049. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  57050. };
  57051. Util.isIFrame = function() {
  57052. try {
  57053. return window.self !== window.top;
  57054. } catch (e) {
  57055. return true;
  57056. }
  57057. };
  57058. Util.appendQueryParameter = function(url, key, value) {
  57059. // Determine delimiter based on if the URL already GET parameters in it.
  57060. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  57061. url += delimiter + key + '=' + value;
  57062. return url;
  57063. };
  57064. // From http://goo.gl/4WX3tg
  57065. Util.getQueryParameter = function(name) {
  57066. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  57067. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  57068. results = regex.exec(location.search);
  57069. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  57070. };
  57071. Util.isLandscapeMode = function() {
  57072. return (window.orientation == 90 || window.orientation == -90);
  57073. };
  57074. module.exports = Util;
  57075. },{}],206:[function(_dereq_,module,exports){
  57076. /*
  57077. * Copyright 2015 Google Inc. All Rights Reserved.
  57078. * Licensed under the Apache License, Version 2.0 (the "License");
  57079. * you may not use this file except in compliance with the License.
  57080. * You may obtain a copy of the License at
  57081. *
  57082. * http://www.apache.org/licenses/LICENSE-2.0
  57083. *
  57084. * Unless required by applicable law or agreed to in writing, software
  57085. * distributed under the License is distributed on an "AS IS" BASIS,
  57086. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  57087. * See the License for the specific language governing permissions and
  57088. * limitations under the License.
  57089. */
  57090. var Util = _dereq_('./util.js');
  57091. /**
  57092. * Android and iOS compatible wakelock implementation.
  57093. *
  57094. * Refactored thanks to dkovalev@.
  57095. */
  57096. function AndroidWakeLock() {
  57097. var video = document.createElement('video');
  57098. video.addEventListener('ended', function() {
  57099. video.play();
  57100. });
  57101. this.request = function() {
  57102. if (video.paused) {
  57103. // Base64 version of videos_src/no-sleep-60s.webm.
  57104. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  57105. video.play();
  57106. }
  57107. };
  57108. this.release = function() {
  57109. video.pause();
  57110. video.src = '';
  57111. };
  57112. }
  57113. function iOSWakeLock() {
  57114. var timer = null;
  57115. this.request = function() {
  57116. if (!timer) {
  57117. timer = setInterval(function() {
  57118. window.location.href = '/';
  57119. setTimeout(window.stop, 0);
  57120. }, 15000);
  57121. }
  57122. }
  57123. this.release = function() {
  57124. if (timer) {
  57125. clearInterval(timer);
  57126. timer = null;
  57127. }
  57128. }
  57129. }
  57130. function getWakeLock() {
  57131. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  57132. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  57133. return iOSWakeLock;
  57134. } else {
  57135. return AndroidWakeLock;
  57136. }
  57137. }
  57138. module.exports = getWakeLock();
  57139. },{"./util.js":205}]},{},[171])(171)
  57140. });
  57141. //# sourceMappingURL=aframe-master.js.map